Skip to content Skip to sidebar Skip to footer

Redis: Reset Counter Every Day

I am looking to reset a counter every day using Redis. I am new to Redis so I want to make sure I well understood how transactions and pipes work. Does the following code ensure t

Solution 1:

Consider two concurrent transactions occuring at midnight. Both can execute get(dt_key), but one will execute the MULTI/EXEC block first. It will reset the counter, set the new date, increment the counter. The second one will enter also in its MULTI/EXEC block, but because the value of 'dt' has changed, the execution will fail, and incr_daily_number will be called again. This time get(dt_key) will return the new date, so when the MULTI/EXEC block will be executed, the counter will be incremented without any reset. The two transactions will return the new date with different counter values.

So, I believe there is no race condition here, and that the (date,number) couples will be unique.

You could also have implemented this using a server-side Lua script (whose execution is always atomic). It is usually more convenient.

Note that actually, there is no such thing as a Redis lock. The locking mechanism available in the API is provided by the Python client - not by the Redis server. If you look at its implementation, you will realize it is also based on SETNX + WATCH/MULTI/EXEC blocks or Lua scripting.

Post a Comment for "Redis: Reset Counter Every Day"