Build a Crash-Resilient Delayed and Recurring Task Runner
System DesignModel answerLast updated
Design a distributed service that runs one-off and cron-style tasks at scale with no lost work, safe retries, duplicate-submission protection, and cancellation.
Design a Crash-Resilient Task Runner
Your team needs a platform that executes background tasks at a requested time. Some tasks run once, others repeat on a cron-style schedule. Both scheduler processes and worker processes can crash at any moment, and the platform must keep working without a human stepping in.
What the system must do
- Submit: A client sends a task with a payload and a time to run it.
- Timing: A task runs at or after its requested time, never before.
- No lost work: If a worker dies mid-task, the task is retried.
- Duplicate protection: Submitting the same job ID concurrently must not result in the job running more than once.
- Cancel: A client can cancel a task that has not finished.
Non-functional targets
- About 10,000 submissions per second.
- About 1 million pending tasks at any time.
- Task state survives restarts of any component.
- Node failures are handled automatically.
What to cover in your answer
- API: endpoints to submit, cancel, and query status.
- Data model: schema or storage strategy for tasks and their executions.
- Architecture: the scheduler, queue or dispatch path, workers, and storage, and how they talk to each other.
- Failure handling: what happens when a worker crashes mid-task, and when a scheduler crashes while dispatching.
State your delivery guarantee explicitly and justify it. Be prepared to discuss trade-offs and follow-ups such as retries, poison tasks, and idempotency of the work itself.
Hints
Hint 1
Pick the delivery guarantee first. Exactly-once across a network is not realistic, so think about at-least-once delivery combined with idempotent handling and a way to reject stale workers.
Hint 2
Separate the job definition from each individual run. A deterministic run ID (job ID plus scheduled time) makes duplicate creation of a recurring occurrence impossible via a unique key.
Hint 3
Use leases with heartbeats for workers and for scheduler shard ownership, and make the state change plus the intent to dispatch commit atomically (transactional outbox). Add an attempt counter that works as a fencing token.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and semantics
- Guarantee: at-least-once execution, made effectively-once with idempotent handlers and fencing. I would say up front that exactly-once over a network is not achievable.
- Timing: run at or after
run_at. A reasonable target is p99 dispatch lag under 1 to 2 seconds. - Recurring jobs: a cron expression defines the job, and each occurrence is its own run.
Capacity estimate
- 10k submissions/s at ~1 KB is ~10 MB/s of writes and ~860M jobs/day, so finished runs need a TTL or archival to cold storage.
- 1M pending jobs is ~1 GB. Storage is not the problem; write throughput and coordination are.
- If execution also peaks near 10k/s with ~2 s average duration, we need roughly 20k concurrent worker slots.
2. API
POST /v1/jobs { job_id, run_at | cron, payload, max_attempts, timeout_s, priority }
-> 201 created
-> 200 identical job already exists
-> 409 same job_id, different payload
DELETE /v1/jobs/{job_id} -> 200 { status: CANCELLED | CANCEL_REQUESTED }
GET /v1/jobs/{job_id} -> { status, next_run_at, attempts, last_error }
GET /v1/jobs/{job_id}/runs -> paginated run history
The client-supplied job_id is the idempotency key.
3. Data model
Use a sharded, replicated store (Postgres with Vitess or Citus, CockroachDB, or DynamoDB with conditional writes). Shard by hash(job_id) % 1024. Sharding by time would put everything due "now" on one hot shard.
jobs(job_id PK, shard_id, cron_expr NULL, payload, payload_hash,
max_attempts, timeout_s, priority, cancel_requested, created_at)
job_runs(run_id PK, -- job_id + ":" + scheduled_time
job_id, shard_id, next_run_at,
status, -- SCHEDULED|QUEUED|RUNNING|SUCCEEDED|FAILED|CANCELLED
attempt, -- fencing token
lease_owner, lease_expires_at, last_error)
INDEX (shard_id, status, next_run_at)
outbox(id, shard_id, run_id, attempt, created_at)
- Dedup:
INSERT ... ON CONFLICT (job_id) DO NOTHING, then comparepayload_hashto choose 200 vs 409. - Recurring: the deterministic
run_idmeans that two nodes racing to create the next occurrence collide on the primary key and only one wins.
4. Architecture
Clients -> stateless API -> sharded Job Store
Scheduler nodes (own shards via etcd leases) -> poll due runs + write outbox (one txn)
Outbox relay -> Kafka (partitioned by shard/priority)
Worker pool (autoscaled) -> acquire lease, heartbeat, complete -> Job Store
Reaper -> requeues expired leases
Scheduler loop (per owned shard, about every 500 ms):
BEGIN;
SELECT run_id, attempt FROM job_runs
WHERE shard_id=? AND status='SCHEDULED' AND next_run_at <= now()+interval '1s'
ORDER BY next_run_at LIMIT 500
FOR UPDATE SKIP LOCKED;
UPDATE job_runs SET status='QUEUED' WHERE run_id IN (...);
INSERT INTO outbox ...;
COMMIT;
The relay publishes outbox rows and deletes them after the broker acknowledges. Because the state change and the dispatch intent commit together, a crash cannot leave a run marked QUEUED with no message.
Worker flow
- Consume
(run_id, attempt). - Acquire the lease with a conditional update:
UPDATE job_runs SET status='RUNNING', lease_owner=me, lease_expires_at=now()+30s WHERE run_id=? AND attempt=? AND status='QUEUED' AND NOT cancel_requested. Zero rows updated means the message is a duplicate, stale, or cancelled, so drop it. - Heartbeat every ~10 s to extend the lease. The response also reports
cancel_requested. - Complete with
... WHERE run_id=? AND attempt=?. For a recurring job, insert the next run in the same transaction.
5. Failure handling
- Worker crash: heartbeats stop and the lease expires. A sharded reaper finds
RUNNINGrows withlease_expires_at < now(). If attempts remain, it setsSCHEDULED, incrementsattempt, and setsnext_run_at = now() + backoffwith jitter. Otherwise it marks the run FAILED and sends it to a dead-letter queue. - Zombie worker (GC pause, partition): the old worker's completion carries the old
attempt, matches 0 rows, and is rejected. Pass the same token to downstream systems so they can reject stale writes too. - Scheduler crash: shard ownership is a short-TTL lease (~10 s) in etcd or ZooKeeper, so survivors take over orphaned shards. A crash before commit rolls back and the next owner re-polls. A crash after commit leaves the outbox row, which the relay still publishes. In a split-brain window,
SKIP LOCKEDand the conditional status transition prevent double-queuing, and duplicate messages die at the worker's lease check. - Stuck in QUEUED (lost message, expired retention): the reaper requeues runs that sat in QUEUED beyond a threshold.
- Storage failure: synchronous replication with automatic failover. The database is the source of truth; the queue is a rebuildable buffer.
- Cancellation: for SCHEDULED or QUEUED, a conditional update moves the run to CANCELLED and in-flight messages fail the lease check. For RUNNING, set
cancel_requested, let the worker abort at its next heartbeat, and returnCANCEL_REQUESTEDrather than claiming completion.
6. Trade-offs
- DB polling vs. a pure delay queue (Redis sorted set, broker delay topics): database-as-truth is easier to make durable, inspect, and cancel, at the cost of polling load. A delay queue has lower latency but needs a durable backing store anyway.
- Poll interval vs. load: shorter intervals cut lag but increase index scans. A 500 ms poll with a 1 s lookahead is a good default.
- Lease length: short leases recover faster but risk false expiry during GC pauses; heartbeats at one third of the lease duration are a common compromise.
- Hot tenants: add per-tenant rate limits and priority partitions so one noisy client cannot starve others.
7. Common mistakes
- Promising exactly-once execution instead of at-least-once plus idempotency.
- Marking a run QUEUED and publishing to the queue in separate steps (lost dispatch on crash).
- Sharding by
run_at, which creates a hot shard. - No fencing token, so a zombie worker can overwrite a newer attempt's result.
- Retrying forever with no backoff, jitter, or dead-letter queue.
- Treating cancel of a running task as instantaneous.
8. Likely follow-ups
- Idempotent side effects: give handlers
run_idplusattemptas an idempotency key for downstream calls. - Poison tasks: cap attempts, then dead-letter with alerting.
- Clock skew: use the database clock for due-time comparisons, not worker clocks.
- Observability: track dispatch lag, lease expiries per minute, queue depth, and DLQ size.