Delayed job queue
A delayed job queue: "send this reminder in 30 minutes", "time this order out in 15". Millions of pending jobs, several worker processes competing for them, and nothing may be lost when a machine restarts.
Millions of jobs are pending, most of them far in the future. What should workers poll?
- A list scanned every second for due jobs
- A min-heap, or an index ordered by due time
- A hash map keyed by job id
- A queue sorted on every insert
Only the earliest job matters at any instant, so the structure needs a cheap "next due" and a cheap insert — a heap in memory, or an index on due_at in a database. Scanning millions of rows every second to find the handful that are ready is the version that passes review and melts in production.
Assign each responsibility.
- Persist pending jobs so a restart loses nothing
- JobStore
- Find the jobs whose due time has passed
- Scheduler
- Execute the handler and record the outcome
- Worker
- Mark a job as claimed, with an expiry
- Lease
- Return an abandoned job to the pending set
- Lease
Durability is separate from scheduling because "what is due" and "where it lives" change for different reasons — the same scheduler should run over Redis or Postgres unchanged. The lease is its own concept rather than a boolean flag on the job because the thing that expires is precisely what makes a dead worker recoverable without a human noticing.
Two workers poll at the same instant and both see the same due job. What prevents it running twice?
- A mutex inside each worker
- Reading the job, then updating its status to claimed
- One atomic claim that returns the job only to the winner
- Giving each worker a different polling offset
Read-then-update is Tier 2 check-then-act, now spread across two processes: both read "pending", both write "claimed", both run. The claim has to be a single indivisible operation — a conditional update matching only while the row is still pending, so exactly one worker gets a row back. A mutex cannot help, because it orders threads inside one process and these are different machines.
A worker claims a job and its machine dies mid-execution. What should happen?
- The job is lost and the caller must reschedule it
- The lease expires and the job becomes claimable again
- A supervisor detects the crash and re-runs it
- The job stays claimed until an operator clears it
Nothing can distinguish a dead worker from a merely slow one, so recovery has to be time-based: the claim carries an expiry, and an unrenewed lease returns the job to the pending set. The consequence is that a job can run twice — once by the worker that was only slow — which is why every handler must be idempotent. At-least-once is what this design buys, and it is the only thing on offer.