Redis fundamentalseasy0-2 years

A service increments a page-view counter in Redis by doing `GET counter`, adding one in application code, then `SET counter <newValue>`. Under load from several instances, the final count is consistently lower than the number of requests. What's happening, and what's the one-line fix?

GET and SET are each individually atomic, but the pair of them together is not — nothing stops two clients from both reading the same value, both adding one in their own application code, and both writing back the same new value, so one of the two increments is silently lost. Redis's own INCR command does the read-modify-write as a single command that runs to completion before anything else touches the key, so it can never lose an increment this way. The fix is to replace GET + application math + SET with INCR counter (or INCRBY counter <n>) and let Redis do the increment itself.

The lesson behind it →
More on Redis fundamentals