Video in progress
How do you count page views in Redis, and why not GET + SET?
With INCR page:42:views. It is atomic: even if a hundred requests arrive at once, each one adds exactly one. With GET followed by SET, the values overwrite each other and updates are lost.
📖 Answer
INCR increments the number stored at the key by one and returns the new value. If the key doesn't exist, it treats it as 0 and sets it to 1.
Long views = redis.opsForValue().increment("page:42:views");
Why GET + SET is wrong:
A thread: GET -> 10
B thread: GET -> 10
A thread: SET 11
B thread: SET 11 // one view was lost
Redis executes commands one at a time, so no other client can sneak in during a single INCR. Similar commands: INCRBY, DECR, HINCRBY, INCRBYFLOAT.
If you need daily statistics, put the date in the key (views:2026-11-03) and set EXPIRE so it disappears after a few days.
Sign up to mark studied questions and save your progress.