Quick revision
The short answer
We keep job ids in a sorted set scored by their due time in milliseconds, with the payloads in a hash. A Lua script atomically takes the jobs whose score is at or before now, removes them from the sorted set and pushes them to a ready stream, so two workers can never take the same job. Workers then consume the ready stream reliably, which gives at-least-once delivery with timing precision equal to the polling interval, as long as Redis is persistent and protected from eviction.
What to remember
In this answer, we built delayed jobs on a sorted set scored by due time, with payloads in a hash and retries as later scores. A Lua script moves due jobs to a ready stream atomically, which removes the race between parallel workers, and polling every few hundred milliseconds sets the timing precision. A consumer group on the ready stream makes execution at-least-once, so sends must be idempotent. Because everything is in memory, we enable persistence, forbid eviction, and keep a database as the source of truth when a lost job would really matter.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We keep job ids in a sorted set scored by their due time in milliseconds, with the payloads in a hash. A Lua script atomically takes the jobs whose score is at or before now, removes them from the sorted set and pushes them to a ready stream, so two workers can never take the same job. Workers then consume the ready stream reliably, which gives at-least-once delivery with timing precision equal to the polling interval, as long as Redis is persistent and protected from eviction.
Why this question is asked
Reminders, retries with backoff, trial-expiry emails and scheduled reports all need the same thing: run this job at that time. Adding a scheduler product is real operational cost, and many teams already run Redis, so the sorted-set scheduler is a common design. Interviewers ask it because the naive version has a race between workers and a gap where jobs can vanish, and the fixes show how well we understand Redis atomicity. In this answer, we will set out the data model, see the race that a simple read-then-delete has, close it with a Lua script, decide how often workers should look, make the hand-off to execution reliable, and finish with the guarantees and the memory question.
1The Data Model: A Sorted Set Scored by Due Time
A sorted set holds unique members, each with a numeric score, kept ordered by score. If the member is a job id and the score is the due time in Unix milliseconds, the set is a timeline: the first element is always the next job to run, and asking for everything with a score up to now returns exactly the due jobs. Lookups by score range cost O(log N + M), where M is the number of results, so a set of ten million future jobs is still fast to query.
We keep only the id in the sorted set and the payload in a hash, jobs:data, keyed by job id. That keeps the sorted set small, and it lets us change or read a job without touching the timeline.
Notice that a retry is just another ZADD with a later score. Exponential backoff becomes arithmetic on the score: 30 seconds, then 60, then 120, with the attempt number kept in the payload.
2The Race in a Simple Read-Then-Delete
The obvious worker loop reads the due jobs with ZRANGE delayed -inf <now> BYSCORE LIMIT 0 100 and then runs ZREM on each one before processing. With one worker it works. With four workers, two can run the ZRANGE in the same millisecond, both receive job-551, and both process it. ZREM returns 1 for the first caller and 0 for the second, so we could check that, but then the job is removed before it is safely anywhere else, and a crash right after ZREM loses it.
We need the read, the removal and the hand-off to happen as one indivisible step. Redis runs a Lua script atomically: no other command from any client runs while the script runs. So we move the work into a script.
3Moving Due Jobs Atomically With Lua
The script takes the due jobs, removes them from the sorted set and appends each to a ready stream in one go. We pass the current time as an argument from the worker, which keeps the script deterministic and easy to test.
- ZADD delayed dueAt jobIdpayload in jobs:data
- Mover script every 250 msZRANGE BYSCORE up to now, LIMIT 100
- ZREM + XADD to ready streamone atomic step, no double pick
- Worker XREADGROUP from readyentry stays pending until XACK
- Did the send succeed?YesXACK and delete the payloadNoZADD with a later score, XACK
5 steps in order. Play them, or step through them one at a time.
Two workers running this script at the same moment are serialised by Redis, so the second one finds the jobs already gone. The batch limit of 100 keeps each script short, which matters because nothing else runs on the server while it executes. The keys share the hash tag {jobs} so that they live in the same slot in Redis Cluster, where a script may only touch keys of one slot. The trade-off is that the whole scheduler for this tag lives on one shard; for very large volumes we split into several tagged sets, such as {jobs:0} to {jobs:15}, by a hash of the job id.
4How Often Workers Look, and Timing Precision
The simplest choice is to run the mover every few hundred milliseconds. A job due at 09:00:00.000 then starts somewhere between 09:00:00.000 and 09:00:00.250 plus processing time, so our timing precision equals the polling interval. For reminders, that is far better than anyone needs.
If thousands of idle workers polling worries us, a worker can instead read the earliest score with ZRANGE delayed 0 0 WITHSCORES and sleep until that time, capped at, say, one second so that a newly added earlier job is not missed for long. Either way, the mover can run in every worker; the script's atomicity means extra movers cost a little CPU but never cause duplicates.
5A Reliable Hand-Off and the Guarantees We Get
Moving a job to the ready stream is not the same as running it. If the worker that reads it crashes, the job must not vanish, so we consume the ready stream with a consumer group (or a BLMOVE processing list). The entry stays pending until XACK, and a claim loop recovers it from dead consumers.
Put together, the design gives at-least-once delivery: a job runs at least once, sometimes twice after a crash, so the send must be idempotent, for example by recording sent:job-551 before calling the email provider with an idempotency key. Ordering is approximate: jobs due in the same interval may run in any order across workers.
Cancelling or rescheduling is cheap because the job id is the member. ZREM delayed job-551 cancels a job that is not yet due, and ZADD delayed XX <newTime> job-551 reschedules it, where XX means only update an existing member. If the job has already moved to the ready stream, the worker should check a cancelled flag in the payload before sending.
6Memory, Persistence and the Source of Truth
Everything here lives in memory. Ten million future jobs with 300-byte payloads come to roughly 4 GB including overhead, which is fine on one node but must be planned. More importantly, a scheduled job lost from memory is a reminder that never goes out, and nobody notices.
So we turn on persistence (AOF with appendfsync everysec loses at most about a second of writes), set maxmemory-policy to noeviction so Redis refuses writes rather than silently evicting the delayed key, and alert on memory. If losing a scheduled job is unacceptable, for example a contractual notice, the database stays the source of truth: the job is written there first, Redis holds only the near future, say the next 24 hours, and a loader moves due-soon jobs from the database into the sorted set. A rebuild from the database then repairs any loss.
7Follow-up questions
How would you cancel or reschedule a job?
Because the job id is the sorted-set member, cancelling is ZREM delayed job-551 plus HDEL jobs:data job-551, and rescheduling is ZADD delayed XX <newDueAt> job-551. If the job may already have been moved to the ready stream, the worker checks a status field in the payload, such as cancelled, before acting, because removing an entry from the middle of a stream is not how we should cancel work.
Why not use Redis keyspace expiry events to trigger jobs?
Expired-key events are fire-and-forget pub/sub messages, so a subscriber that is down misses them, and Redis does not guarantee that a key expires exactly at its TTL; expiry can lag under load. A sorted set keeps the job until we deliberately move it, which is what a scheduler needs.
8Conclusion
In this answer, we built delayed jobs on a sorted set scored by due time, with payloads in a hash and retries as later scores. A Lua script moves due jobs to a ready stream atomically, which removes the race between parallel workers, and polling every few hundred milliseconds sets the timing precision. A consumer group on the ready stream makes execution at-least-once, so sends must be idempotent. Because everything is in memory, we enable persistence, forbid eviction, and keep a database as the source of truth when a lost job would really matter.
Open with
I would keep a sorted set called delayed where each member is a job id and the score is the due time in milliseconds, with the payload in a hash keyed by job id.
Then, if they want more
Scheduling is ZADD, a retry with backoff is another ZADD with a later score, cancelling is ZREM, and rescheduling is ZADD XX. To take due jobs safely in parallel, I would not do a ZRANGE followed by ZREM from the client, because two workers can read the same job.
Instead a Lua script does ZRANGE delayed minus infinity to now BYSCORE LIMIT 0 100, removes each job and XADDs it to a ready stream, all atomically, so only one worker can ever move a job. The two keys share a hash tag so this works in Cluster.
Workers run the script every couple of hundred milliseconds, or sleep until the earliest score, so timing precision is roughly the polling interval. Then they consume the ready stream with a consumer group, so a crash between moving and processing does not lose the job. The guarantee is at-least-once, so sends must be idempotent.
Finally, millions of future jobs are in memory, so I would enable AOF, set noeviction, and if a lost reminder is unacceptable I would keep the database as the source of truth and rebuild Redis from it.
About this answer
- Last updated
- 13 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Redis documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Design delayed jobs with a sorted set: the data model, how workers pick due jobs safely...": https://scrivio-interview-library.netlify.app/databases/redis-patterns/22f17ce085/