Video in progress

Strong Middle ⚡ Redis and caching

Is it safe to hand out order numbers with `INCR order:seq` in Redis? When does the same number come out twice?

Within a single node INCR is atomic, and parallel requests won't get the same number. But because replication is asynchronous, the latest increments are lost on failover and the new master hands out numbers that were already given. A restart without persistence resets the counter to zero.

📖 Answer

On ordinary days everything works correctly:

long orderNo = redis.opsForValue().increment("order:seq");

The problem is that even a "confirmed" write can be lost in Redis. A scenario:

  1. The master incremented order:seq from 1000 to 1005, and the orders numbered 1001-1005 were written to the DB.
  2. The replica had only caught up to 1000. The master crashed and Sentinel promoted the replica.
  3. The next INCR returns 1001, a number that already exists.

If the order_no column in the DB has a unique constraint, five orders fail with an error. If there's no constraint, it's worse: two different customers have the same number on their receipts.

appendfsync everysec is similar: on a crash, about 1 second of increments disappears.

What you can do:

  • make a DB sequence the real source (a PostgreSQL SEQUENCE); it's fast enough even without Redis;
  • if you need Redis, have a procedure that resets the counter to max(order_no) + a safety margin after a failover or restart, plus a unique constraint in the DB;
  • reserve blocks: take a range with INCRBY 1000 from Redis or the DB and hand the numbers out inside application memory, which cuts the trips to Redis;
  • if ordering isn't required, a UUIDv7 or a Snowflake-style ID, and no central counter is needed at all.

The point the interviewer expects: the atomicity of INCR and the durability of Redis are two different things.