Video in progress

Strong Middle ⚡ Redis and caching

Why is it risky to rely on the `expired` event from Redis keyspace notifications to cancel an unpaid order after 15 minutes?

The expired event isn't emitted at the exact moment the TTL runs out, but when Redis actually deletes the key, and it can be late. It arrives over Pub/Sub, so if the application isn't connected at that moment, the event is lost. And in a cluster, each node only sends its own events.

📖 Answer

The idea looks nice: SET order:timeout:77 1 EX 900, then subscribe to the __keyevent@0__:expired channel and cancel the order when the event arrives. In practice there are several traps.

  • It's off by default: notify-keyspace-events is empty. You need to set Ex, and on managed services CONFIG SET is often forbidden, so you configure it through a parameter group.
  • Delay: if nobody accesses the key, the event isn't emitted until the background cleanup finds it. With many TTL keys, that's seconds, sometimes more.
  • Loss: Pub/Sub doesn't store messages. Orders that expire during the 20 seconds when all pods are reconnecting during a deploy never get canceled.
  • Duplicates: if 5 pods subscribe, each of them gets the event, which means 5 cancel attempts.
  • No value: by the time the event arrives, the key is already gone and only its name is left. You have to cram the data you need into the key name.
  • Cluster: events aren't propagated between nodes, so you have to subscribe to each master separately.

The reliable option: store the deadline in the DB (expires_at) and use a scheduler with a WHERE status = 'PENDING' AND expires_at < now() query, or a Sorted Set in Redis whose score is the deadline. Use keyspace notifications only for work that's fine to lose, for example clearing a local cache.