Video in progress

You need to automatically cancel orders that are unpaid after 30 minutes. How do you build a delayed job queue in Redis, and where do you need to be careful?

A Sorted Set: the member is the order ID, the score is the execution time. A poller atomically takes the due items with Lua and hands them to a worker. Several pods must not take the same job twice, a job must not be lost when a pod dies, and there must be a way to recover if Redis loses data.

📖 Answer

The basis:

ZADD delayed:order-cancel 1730622600000 order:77     # score = the cancel time (ms)

Every second a poller "claims" the due items. If you do ZRANGEBYSCORE and ZREM separately, two pods take the same order, hence Lua:

local due = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', 0, 100)
for _, id in ipairs(due) do
  redis.call('ZREM', KEYS[1], id)
  redis.call('XADD', KEYS[2], '*', 'orderId', id)
end
return #due

Here the due job is moved straight into a Stream. Why: if the poller takes a job and dies before processing it, the job is gone after a plain ZREM. With a Stream and a consumer group, the message stays in the PEL until the worker calls XACK, and another worker can pick it up again. Both keys must be in the same slot in a cluster, with the {orders} hash tag.

The worker is idempotent:

UPDATE orders SET status = 'CANCELLED'
WHERE id = :id AND status = 'PENDING';   -- 0 rows if it was paid, we do nothing

When a payment arrives you don't have to ZREM, since the check is in the DB anyway. But if you do, the queue stays smaller.

Where to be careful:

  • Redis data loss: on failover the latest ZADDs can be lost. So the truth is in the DB, and every 5 minutes a "cleaner" job runs with WHERE status = 'PENDING' AND created_at < now() - interval '30 min'. Redis is only for precision and speed;
  • a big Sorted Set: with millions of jobs, one key is hot and large; keys split by time (delayed:2026-11-03T14) are better;
  • the clock: compute the score from Redis TIME rather than the pod's clock if you can.

Honestly, if you have a few thousand orders a day, a scheduler in the DB (Quartz, db-scheduler, or plain @Scheduled + ShedLock) is enough and simpler. The Redis version pays off when you need high volume and second-level precision. Redisson also has a ready-made RDelayedQueue.