Search code examples
rediscounterincrementrace-condition

Check-and-increment a counter in Redis


I have an operation I need to get done N times and no more. The operation is done by many possibly parallel processes that recieve requests. A process has to check if the counter has exceeded N and, if not, then increment the counter and execute the operation. I suppose I could use a Redis counter for that.

Howerver if I just GET and then INCR a value I might run into a race condition that will result in the operation being done more than N times. How do I perform some kind of test-and-incr operation against Redis?

I know I could use WATCH but that's an optimistic lock. I expect there going to be very many collisions each second. This will result in a lot of failures. Maybe I could just wrap simple GET and INCR with some kind of external mutex. But I am not sure if it's good enough for performance.


Solution

    • You can use Redis INCR safely here.
    • INCR returns the value post the increment.

    • You check the value returned by INCR first ( see there is no need to do a GET ) & proceed to do the operation based on that value.

    • Only thing is you would have to set your INCR return value threshold as N+1 for limiting to N operations i.e. one extra redis operation than N. For example, if we want to limit the operation to happen 3 times only, if INCR returns 4 after an increment, then you stop doing further operation as it has already happened 3 times.

    enter image description here