Build a Reliable Delayed and Immediate Task Runner
System DesignModel answerLast updated
Design a durable service that runs tasks right away or at a future time, and explain how it copes with crashes, retries, duplicates, and the limits of exactly-once execution.
You are asked to design a backend service that runs background tasks on behalf of other teams. Clients submit a task and the platform executes it later, outside the request path.
The service must support two kinds of submissions:
- Run-now tasks: these should start as soon as capacity allows.
- Deferred tasks: the client gives a delay (for example "in 1 hour") or an absolute timestamp. When that time arrives, the task should start as soon as possible.
Reliability is the main concern. In your answer, cover:
- What happens when a worker crashes or stalls partway through a task.
- What happens when the scheduler component itself fails or is replaced.
- How retries work, including backoff and what to do with tasks that keep failing.
- How you prevent or tolerate duplicate execution.
- Whether exactly-once execution is achievable, and what you can honestly promise instead.
State your assumptions about scale (task volume, maximum delay, payload size, runtime), then present the API, data model, architecture, and the failure-handling deep dives. Call out trade-offs and the choices you would make under uncertainty.
Hints
Hint 1
Ask whether the two submission types really need separate pipelines. A run-now task can be treated as a deferred task whose due time is the current moment.
Hint 2
Keep a durable record as the source of truth, and give each running attempt a time-limited lease that the worker must renew. Think about what should happen to a stale worker that wakes up after its lease was taken away.
Hint 3
When a crash can happen between two steps (record state, then publish to a queue), decide which failure you prefer: losing a task or running it twice. Then ask what exactly-once can realistically mean when the task has side effects.
Hint 4
Exactly-once execution cannot be guaranteed in general. Aim for at-least-once delivery combined with idempotent handlers and stable idempotency keys.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
Functional
- Submit a run-now or deferred task (relative delay or absolute
run_at). - Check status, cancel a task that has not started.
- Per-task retry limit, timeout, and priority.
Non-functional
- Durability: once submission returns success, the task is never lost.
- Timeliness: dispatched within about 1 second (p99) of becoming due.
- Semantics: at-least-once execution, with tooling for exactly-once effect.
- Availability: submission keeps working when individual scheduler or worker nodes die.
Assumed scale: 100M tasks/day (about 1.2K/s average, 10K/s peak), delays up to 30 days (so roughly 1B pending tasks), payload up to 64 KB (larger ones go to a blob store and are referenced), runtimes from milliseconds to about 30 minutes.
2. API
POST /tasks { handler, payload, run_at | delay_sec, idempotency_key,
max_attempts, timeout_sec, priority } -> { task_id }
GET /tasks/{id} -> status, attempt, last_error, run_at
DELETE /tasks/{id} -> cancel if not yet running
A run-now task is simply run_at = now(). Both types share one code path, which removes a whole class of bugs.
3. Data model
A sharded, replicated tasks table is the source of truth, partitioned by hash(task_id) (not by time, otherwise "everything at midnight" hits one shard).
Key columns: task_id, tenant_id, idempotency_key (unique per tenant), handler, payload_ref, status, run_at, attempt, max_attempts, timeout_sec, lease_token, lease_expires_at, version.
States: SCHEDULED -> QUEUED -> RUNNING -> SUCCEEDED, or back to SCHEDULED on a retryable failure, or DEAD / CANCELED. Index on (shard, status, run_at).
4. Architecture
Client -> API -> Tasks DB (sharded, replicated)
^ |
Reaper | v
Dispatcher (one owner per shard) -> Ready queue (by priority)
|
Workers
- API validates, dedups on
idempotency_key, and commits the row with quorum replication before returning. - Dispatcher (one owner per shard, chosen via an etcd/ZooKeeper lease) repeatedly selects due rows (
status='SCHEDULED' AND run_at <= now(), withSKIP LOCKED, small batches), marks themQUEUED, and publishes to the ready queue. For sub-second precision, preload tasks due in the next minute into an in-memory timing wheel or sorted set; far-future tasks stay cold in the DB. - Workers pull from the queue, atomically claim the task (set
RUNNINGwith a freshlease_tokenand expiry), heartbeat while working, run the handler, then commit the result conditionally and ack. - Reaper finds tasks stuck in
RUNNINGwith an expired lease, or inQUEUEDtoo long, and returns them toSCHEDULED.
5. Failure handling
Worker crashes or stalls
The lease (about 30 s, renewed by heartbeat) covers crashes, network partitions, and long GC pauses. When heartbeats stop, the reaper resets the task, bumps attempt, and applies backoff.
Zombie workers are the subtle case: a paused worker wakes up after its task was reassigned. Make every transition conditional:
UPDATE tasks SET status='SUCCEEDED'
WHERE task_id=? AND lease_token=?;
A stale token matches zero rows, so the late result is discarded. The token acts as a fencing token and should also be sent to downstream systems that can reject stale writers.
Scheduler failures
- Dispatchers are stateless; all state is in the DB. If one dies, its shard lease expires and another node takes over with a higher epoch.
- Split-brain during handover is bounded by writing the epoch with each update; the DB rejects lower epochs.
- Crash between "mark QUEUED" and "publish": the task is stuck in
QUEUED. The reaper re-dispatchesQUEUEDrows older than a threshold. Delayed, not lost. - Reversing the order (publish, then mark) risks a duplicate instead. We deliberately prefer possible duplicate over possible loss. A transactional outbox or change-data-capture into the queue is a cleaner alternative.
Retries
- Exponential backoff with jitter:
run_at = now + min(cap, base * 2^attempt) +/- random. Jitter avoids thundering herds against a struggling dependency. - Classify errors: timeouts and 5xx are retryable; validation errors go straight to
DEAD. - After
max_attempts, move to a dead-letter state with alerting and manual replay. - Enforce
timeout_secin the worker; the lease is the backstop.
Duplicate execution
Sources: client retries (solved with the idempotency key at submit), dispatcher double-publish, queue redelivery, and lease expiry while the original worker is still alive. The conditional claim and conditional completion remove most duplicates cheaply, but not all.
6. Is exactly-once possible?
Not as exactly-once execution. If a worker performs a side effect (charges a card) and crashes before recording success, the system cannot distinguish "did it and died" from "died before doing it." The only options are retry (at-least-once) or never retry (at-most-once).
What we can offer is exactly-once effect = at-least-once delivery + idempotent handlers:
- Effects in our own database: write the effect and a processed-marker keyed by
task_idin the same transaction; reruns find the marker and skip. - External calls: pass
task_idas the downstream idempotency key. - Inherently non-idempotent actions (email): check a dedup store first and document the small residual risk.
The scheduler's contract is at-least-once delivery with stable keys; handler authors are responsible for idempotency.
7. Trade-offs and common mistakes
- Polling the DB is simple and durable but needs the in-memory near-term window to hit sub-second precision; pure queue-with-delay features rarely support 30-day delays.
- Sharding by time creates hot shards.
- Forgetting fencing lets zombie workers overwrite newer results.
- Claiming "exactly-once" without qualification is the most common red flag.
- Marking tasks done before the side effect is durable turns retries into silent loss.
- Not capping retries or adding jitter can amplify an outage.