Build a Fault-Tolerant Future Task Execution Engine
System DesignModel answerLast updated
Design a distributed scheduler that durably stores millions of delayed tasks and dispatches them within seconds of their due time, surviving crashes and partitions.
Context
Many product workflows depend on deferred actions: canceling an unpaid order after 10 minutes, sending a follow-up notification 48 hours after a user signs up, or revoking a temporary access token at a precise moment. Rather than building this logic ad hoc in every service, your team wants a shared Future Task Execution Engine — a central service that any client can hand a job to with a target fire time, and trust that it will run.
You are asked to design this system end to end.
What the System Must Do
Core operations:
- Register a task: Accept a payload, an execution target, and a
fire_attimestamp. Return a stable identifier for the task. Acknowledge only after the record is durably stored. - Revoke a task: Cancel a registered task before it fires. If the task has already been dispatched, return an appropriate error.
- Inspect a task: Return the current status, attempt count, and next scheduled time for a given task.
- Worker feedback: Accept a success or failure callback from the downstream worker so the scheduler can drive retries.
Execution behavior:
- Tasks must never fire before their
fire_attime. - At least 99% of tasks must fire within 2 seconds of
fire_at. - Failed executions must be retried automatically with exponential backoff and jitter, up to a configurable attempt ceiling.
- Tasks that exhaust all retries go to a dead-letter destination for manual review.
Constraints and Scale
- Up to 50 million tasks pending at any moment.
- Peak ingestion: 5,000 new tasks per second.
- Peak execution: 5,000 tasks firing per second.
- Scheduled delays range from 5 seconds to 90 days in the future.
- Zero task loss after the client receives an acknowledgment.
- At-least-once delivery; downstream consumers must be idempotent, but unnecessary duplicates should be minimized.
What Your Answer Should Cover
- API surface and data model — the external interface, the storage schema, and how you index tasks for efficient time-based retrieval.
- Discovery mechanism — how the system efficiently finds tasks whose
fire_athas arrived among tens of millions of records; compare relevant approaches and justify your choice. - Atomic claiming — how multiple scheduler nodes coordinate to ensure a task is dispatched exactly once per attempt without a global lock.
- Failure recovery — what happens when a scheduler node crashes mid-dispatch, when a lease expires, or when clocks drift; how you handle a sudden burst of tasks all due at the same moment.
Hints
Hint 1
Start with capacity math: 50M tasks at ~1 KB each is ~50 GB of state. That rules out keeping everything in RAM cheaply, but it fits easily in a sharded database. The 'hot set' — tasks due in the next few minutes — is much smaller and can live in memory on the owning node.
Hint 2
Think in two tiers: a durable database as the source of truth (so the ack guarantee holds) plus an in-memory structure like a min-heap or timing wheel per shard owner for sub-second polling precision. The two tiers are complementary, not alternatives.
Hint 3
Atomic claiming is the hardest coordination problem. A conditional UPDATE that checks both status = PENDING and due_time <= now() acts as a compare-and-swap. Pair that with a lease epoch as a fencing token so a slow or partitioned node cannot corrupt state after it loses ownership of a shard.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing First
Turn the requirements into concrete numbers before touching architecture. This signals you can scope a system, not just describe one.
- Storage: 50M tasks × ~1 KB = ~50 GB raw. With indexes and three-way replication, plan for ~150–200 GB. Fine for a sharded RDBMS or DynamoDB; too expensive for Redis without careful eviction.
- Write throughput: 5k inserts/s, plus roughly 3 state transitions per task (claim → dispatch → complete) = ~20k writes/s at peak.
- Hot set: tasks due in the next 5 minutes = 5k/s × 300s = ~1.5M tasks. This fits in a few hundred MB of RAM per shard owner — an important insight for the two-tier design.
- Key clarifying questions: Is cross-task ordering required? (Usually no.) Does "dispatched" mean handed to a durable broker, or worker completion? (Broker handoff is the right contract; workers own retries from there.)
2. API
POST /tasks
body: { payload, fire_at, target, max_attempts?, idempotency_key? }
-> 201 { task_id } -- only after durable commit
DELETE /tasks/{task_id}
-> 200 CANCELLED | 409 ALREADY_DISPATCHED
GET /tasks/{task_id}
-> { status, attempt, next_fire_at, last_error }
POST /tasks/{task_id}/result
body: { attempt, success, error? } -- worker callback
idempotency_key makes the registration call safe to retry from the client. task_id is a ULID so it is time-sortable and doubles as a shard key.
3. Data Model
One tasks table, sharded by shard_id = hash(task_id) % 256. Having 256 logical shards decouples sharding from physical node count and allows rebalancing without resharding.
| Column | Purpose |
|---|---|
task_id (PK), shard_id | identity and routing |
fire_at | current eligible time; overwritten on each retry |
status | PENDING → CLAIMED → DISPATCHED → DONE / FAILED / DEAD / CANCELLED |
attempt, max_attempts | retry budget |
lease_owner, lease_epoch, lease_expires_at | ownership fencing |
version | optimistic concurrency |
target, payload_ref | where to send it; large payloads stored in object storage |
The critical index is (shard_id, status, fire_at). The polling query — "give me PENDING tasks in shard s with fire_at ≤ now" — becomes a tight range scan with no full-table reads.
4. Discovering Due Tasks
Three common approaches, each with real trade-offs:
| Approach | Strength | Weakness |
|---|---|---|
| Redis sorted set (all tasks) | O(log n) insert, dead-simple range query | 50M entries with payloads is expensive in RAM; AOF durability still leaves a crash window |
| Pure DB polling | Durable, single source of truth | Polling every 500 ms per shard adds steady-state DB load and makes sub-second precision harder |
| Hierarchical timing wheel (in-memory) | O(1) insert and tick, very low CPU overhead | Volatile — needs full rebuild from the DB after any crash |
Recommended: two-tier design. The database is always the source of truth. A shard owner node additionally maintains an in-memory min-heap (or 100 ms-granularity timing wheel) of tasks due within the next 5 minutes. The loader refreshes this window every 30 seconds via a single indexed range scan. Tasks registered with a near-term fire_at (under 5 minutes) are pushed directly into the owner's heap after the DB commit, cutting perceived latency further.
Shard ownership is managed via leases in etcd or ZooKeeper, each carrying a monotonically increasing epoch. This epoch becomes the fencing token used in every write.
5. Atomic Claiming
When the heap fires a batch, the owner runs:
UPDATE tasks
SET status = 'CLAIMED',
lease_owner = :node_id,
lease_epoch = :epoch,
lease_expires_at = now() + interval '30 seconds',
version = version + 1
WHERE shard_id = :s
AND task_id = ANY(:batch)
AND status = 'PENDING'
AND fire_at <= now() -- use DB clock, never application clock
RETURNING task_id, attempt, payload_ref, target;
The status = 'PENDING' predicate makes this a compare-and-swap. Two nodes racing to claim the same row produce exactly one winner. Checking fire_at <= now() with the database clock is the only guarantee against premature dispatch — application clocks can drift.
After claiming, the dispatcher publishes each task to the broker (Kafka, SQS, or a webhook) with the message key task_id:attempt. Then it sets status = 'DISPATCHED' where lease_epoch = :epoch — a stale node's write fails this predicate silently.
This is effectively the transactional outbox pattern: the DB row is the outbox entry, and the state transition to DISPATCHED only completes after the broker acknowledges. A crash between publish and acknowledgment causes a re-publish, but the task_id:attempt dedupe key on the consumer side absorbs it cheaply.
Retries: On a failure callback, increment attempt, set status = PENDING, and compute fire_at = now() + min(cap, base × 2^attempt) × rand(0.5, 1.5) (full jitter). When attempt > max_attempts, set status = DEAD and route to the dead-letter queue.
Cancellation: UPDATE ... SET status = 'CANCELLED' WHERE status = 'PENDING'. Zero rows updated means the task already moved past PENDING — return 409. Even if the task lingers in the heap, the claim step skips non-PENDING rows.
6. Failure Recovery
Node crash mid-dispatch. A background sweeper scans for rows where status = 'CLAIMED' and lease_expires_at < now(), resetting them to PENDING. The worst outcome is one duplicate dispatch, never a dropped task.
Shard owner dies. The lease expires in ~10 seconds. Another node acquires it with a higher epoch, runs the loader for that shard (one range scan), and resumes. Tasks that came due during the gap have fire_at in the past, so they are included in the first load — the latency spike is bounded by the failover window, which is the main driver of the 1% tail beyond 2 seconds.
Network partition / split-brain. A partitioned node may still think it owns a shard. Its claim writes fail because lease_epoch no longer matches, and any publish it completes is absorbed by broker-level deduplication on task_id:attempt.
Hot timestamp (thundering herd). If millions of tasks share the same fire_at (e.g., a midnight batch), load is spread naturally across shards. Within a shard, the dispatcher claims in batches of a few hundred and rate-limits publishing to avoid overwhelming downstream workers.
Clock drift. The scheduler uses the database's now() for both the fire_at check and lease_expires_at. Application clocks are untrusted. This eliminates premature dispatch as long as the DB clock is healthy — a reasonable assumption with NTP-synced clusters.
7. Key Trade-offs to State Explicitly
- Lookahead window size: wider windows reduce DB polling frequency but increase RAM use and rebuild time after a crash. 5 minutes is a reasonable default for most workloads.
- Claim lease length: shorter leases mean faster recovery but more sweeper churn. 30 seconds matches typical network timeout detection.
- At-least-once vs. exactly-once: true exactly-once requires distributed transactions between the scheduler DB and the broker, which adds significant latency and complexity. The
task_id:attemptdedupe key on the consumer is a much cheaper trade-off. - Shard count: 256 logical shards support growth without resharding; physical nodes can be added and shards reassigned via lease transfers.