A race condition when using Redis command incr and expire

Viewed 14023

Based on the redis document: http://redis.io/commands/incr

In the paragraph Pattern: Rate Limiter 2 A shorter version code:

value = INCR(ip)

IF value == 1 THEN
  EXPIRE(ip, 1)

It's claimed there's a race condition to make EXPIRE never executes. Which means the value of ip can bounces from 0 to 2 some way.

However in my thoughts, since Redis is single thread and INCR is a primitive command, it shouldn't be atomic itself? Even if 2 clients do the INCR at almost the same time, how could them both retrieve 0 or both retrieve 2?

3 Answers
Related