Run work later or on a schedule
Send at 9am local time, expire links nightly, retry in 10 minutes.
Say it like this
Work that must happen later needs a durable due time and a worker that claims each job exactly once, so I store jobs with a run_at, poll the due ones with a claim query, and keep the scheduler itself stateless and replaceable.
Basic solution
Store jobs with a due time and have a scheduler enqueue them when due; or use delayed messages.
Durable job rows, atomic claims, lease reaper
Producers only insert a row. Schedulers claim due rows with SKIP LOCKED so they never collide, workers run idempotent handlers, failures reschedule with backoff, and the reaper reclaims jobs whose worker died.
How it works
- The producer inserts a job row: an id, a type, a payload, the run_at time, status = pending and attempts = 0. Writing that row is the only thing the request path does; the work itself happens later.
- A scheduler loop runs every second. It selects jobs whose run_at has passed and whose status is still pending, and claims them in one atomic statement: an UPDATE that sets status = running and records who locked it and when, using SELECT FOR UPDATE SKIP LOCKED so two scheduler instances never pick the same row. Each claimed job is handed to a worker or pushed onto a queue.
- The worker runs the job. On success it marks the row done. On failure it sets run_at to now plus a backoff delay, puts the status back to pending and increments attempts; after N attempts the row is moved to a dead-letter state for a human to inspect.
- A reaper runs periodically and resets any job that has been in running for longer than its lease, which means the worker that claimed it died, so the job can be claimed again.
- A recurring job (a nightly sweep) is just a job that, when it finishes, inserts its own next occurrence. Cron-style definitions are expanded in advance into concrete run_at rows.
The two invariants
- A due job runs at least once, because the row is durable and a dead worker's claim is reclaimed. The handler is idempotent, so running it a second time after a crash does no harm. Exactly-once execution is not promised; exactly-once effect is achieved by the handler.
Worked example
Notification quiet hours and link expiry
- Quiet hours: 20M marketing notifications routed during a user's quiet window are deferred to the end of it. Each becomes a job row with run_at = end of quiet window in the user's time zone. Deferred jobs cluster: 2M become due at 08:00 Europe/London.
- Without jitter the scheduler would release 2M jobs in one second. With run_at spread over 15 minutes (08:00 to 08:15), the release rate is about 2,200 per second, inside the push provider's limit.
- Claim query: every second, each of 4 scheduler instances claims up to 500 due rows with SKIP LOCKED, so instances never fight over the same rows and 2,000 jobs per second flow to the channel queues.
- Index: (status, run_at) so the due query is a range scan on a few thousand rows, not a scan of 20M.
- Link expiry: a nightly job at 03:00 deletes expired aliases in batches of 10K with a short sleep between batches, about 5M rows in 20 minutes, and re-inserts itself for the next night when it finishes; if it crashes midway the reaper reclaims it and the batches are idempotent (DELETE WHERE expires_at < now).
- Storage: done rows are purged after 7 days; the jobs table stays around 50M rows.
Variants and when each wins
Database-backed job table
- Jobs are rows with a run_at and a status, claimed with SKIP LOCKED. It wins when a job must be written in the same transaction as your own data (the order and its reminder together) and when you want to inspect the queue with SQL; polling cost grows with the fleet.
Delayed messages in a queue
- The message is published with a delay (SQS delay, a RabbitMQ delayed exchange) and the broker holds it until due. It wins for short retries because there is no polling and it scales with the broker; delays are capped (SQS at 15 minutes), cancelling or rescheduling is hard, and it is not transactional with your database.
Redis sorted set by due time
- Each job is a member whose score is its run_at, and workers pop due members inside a Lua script. It wins for millions of entries with very fast claims; durability depends on how Redis persistence is configured.
Workflow engine
- Temporal or Step Functions model timers, retries and long-running state as code. It wins when the delayed step is one part of a multi-step process with its own state to track.
Recommendation: a job table with SKIP LOCKED for anything that must be transactional or inspectable; queue delays for short retries; a workflow engine when the schedule is one step of a longer saga.
Failure modes
Double execution
- A reminder is sent twice, or a sweep runs concurrently with itself. Two schedulers selected the same row without a lock, or a lease expired while the worker was still running and the reaper handed the job to someone else. Claim with an atomic UPDATE or SKIP LOCKED, have long jobs heartbeat to extend their lease, and make handlers idempotent using the job id as the key.
Stuck jobs
- Rows sit in running for hours and nothing happens to them. The worker died after claiming the job and nothing noticed. Run a reaper that resets running rows older than the lease back to pending, and alert when the count of stuck rows rises.
Scheduler as a herd source
- A load spike hits every hour on the hour. Many jobs were created with exactly the same run_at. Add jitter so run_at values spread over a window, cap how many jobs the scheduler releases per second, and spread recurring jobs across the hour.
Clock and time zone errors
- Quiet hours end at the wrong time for some users, or every job fires an hour early the day after a daylight-saving change. run_at was computed in local time. Store run_at in UTC, compute it from the user's IANA time zone at scheduling time, and recompute each occurrence of a recurring job rather than adding a fixed interval.
Unbounded table
- The query for due jobs slows from milliseconds to seconds. Done rows were never purged and there is no index on (status, run_at), so every poll scans millions of rows. Add a partial index on pending rows, purge or archive done rows, and partition the table by month if volume is high.
Interviewer follow-ups
Answer out loud before you open each one.
How do two scheduler instances avoid running the same job?
They claim with a single atomic statement: UPDATE the row to running where it is still pending, or SELECT FOR UPDATE SKIP LOCKED so each instance takes different rows. Whichever wins the claim runs the job; the other sees zero rows affected and moves on.
What happens if a worker crashes mid-job?
The row stays in running with a locked_at timestamp. A reaper resets rows whose lease has expired back to pending so another worker picks them up. Because the handler is idempotent, the partial first run does no harm.
How would you schedule millions of jobs for 9am local time?
Compute each run_at in UTC from the user time zone, add jitter over a window so they do not all fire in one second, and index on (status, run_at) so the due scan is cheap. Cap the release rate to what the downstream can absorb.
When is a cron job enough?
For a handful of recurring tasks on a known schedule where running them on one box is acceptable and a missed run just waits for the next. The moment you need per-item schedules, retries, visibility or more than one worker, move to a job table.
Connections
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Router, Scheduler ×4, Workers, Reaper | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |