Build a Fault-Tolerant Job Scheduler for Async Workflows
System DesignModel answerLast updated
Design a distributed scheduling service that fires one-time and recurring jobs on time, at scale, without losing a single task across node failures or clock drift.
Background
Asynchronous workflows are everywhere in data-intensive platforms: kicking off hourly metric rollups, retrying failed delivery webhooks with exponential backoff, or running nightly ETL pipelines. Rather than baking scheduling logic into each individual service, it makes sense to centralize it behind a dedicated scheduling layer that any internal team can call.
Your task is to design that layer: a durable, multi-tenant service that lets clients register future work, forget about it, and trust it will fire correctly — even when nodes crash or the cluster is mid-election.
What to Design
A scheduling service with the following properties:
Core behavior
- Accept both one-shot tasks (fire at a specific UTC timestamp) and recurring tasks (defined by a cron expression with an explicit timezone).
- Be responsible only for triggering execution — dispatching a message or event to downstream workers — not for running the job logic itself.
- Let callers cancel or modify a pending task before it has fired.
- Deliver tasks at least once, and give downstream consumers the tools (idempotency keys) to safely handle re-delivery.
- Retry failed or stalled dispatches with configurable backoff, and route permanently failed tasks to a dead-letter destination.
Scale targets
- Up to 50 million pending tasks in the system at any time.
- Peak dispatch throughput of 10,000 tasks per second.
- Each task must fire within 1 second of its scheduled time.
- Zero task loss once the API has acknowledged a registration request.
- Survive node crashes, clock skew, and concurrent dispatch attempts across nodes.
Expected Coverage
Address all four of the following areas:
- API and data model — endpoints for creating, updating, cancelling, and inspecting tasks; schema for task definitions, run records, and state transitions.
- Due-task discovery and claiming — how the system finds tasks that are ready to fire, partitions responsibility across scheduler nodes, and prevents duplicate dispatches without a centralized lock.
- Dispatch and execution handoff — how the scheduler passes work to executors (push vs. pull, message queues, execution leases), and how execution outcomes flow back.
- Failure handling and edge cases — thundering herds (many tasks scheduled for the same instant), missed runs during downtime, recurring-task catch-up policies, and stale claims from crashed nodes.
Discuss trade-offs where relevant. Numbers and concrete examples carry more weight than vague generalities.
Hints
Hint 1
Start with scale math: 50M tasks at ~1 KB each is ~50 GB of hot state, and 10k dispatches/s means roughly 30–40k DB writes/s when you count state transitions and run history. These numbers should drive your storage and partitioning choices before you sketch any architecture.
Hint 2
A naive 'poll every second' loop against a single table will not hit the 1-second accuracy target at this scale. Think about combining a short lookahead window from the database with an in-memory timer structure (a timing wheel) so the hot path never touches the DB at fire time.
Hint 3
The trickiest correctness problem is: what happens if a scheduler node claims a task and then crashes before it finishes dispatching? Your design needs fencing tokens or versioned leases so a recovered or replacement node can safely reclaim the work without producing a duplicate dispatch.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Nail the Numbers First
Before drawing architecture boxes, derive what the system actually needs to handle.
- Storage: 50M tasks × ~1 KB metadata = ~50 GB of hot state. Inline payloads should be capped around 64 KB; anything larger gets stored in blob storage (S3/GCS) with a reference in the task row.
- Write throughput: Each dispatch involves roughly 3 writes — claim, state transition, run-history insert. Recurring tasks add a next-occurrence update. Budget for 30–40k writes/s at peak.
- Accuracy: 1-second dispatch latency rules out simple "poll the DB every second" designs. Polling introduces jitter and DB pressure at scale. The answer is a short lookahead window feeding an in-memory timing wheel.
- Semantics: at-least-once, never-lose-after-ack, per-tenant fairness.
- Scope boundary: the scheduler's job ends at publishing the "fire" event. It does not execute the task logic.
Minimum cron granularity: 1 second. Cron expressions carry an explicit timezone. Tasks are only mutable while in SCHEDULED state.
2. API Design
POST /v1/tasks
body: { tenant_id, type: ONE_TIME|CRON, run_at | cron_expr + timezone,
target: { topic | url }, payload,
retry_policy: { max_attempts, base_backoff_s, max_backoff_s },
misfire_policy: FIRE_ONCE | FIRE_ALL | SKIP,
idempotency_key }
→ 201 { task_id }
(duplicate submissions with same tenant_id + idempotency_key return the existing task)
PATCH /v1/tasks/{id} reschedule; uses If-Match: <version> for OCC
DELETE /v1/tasks/{id} cancel; returns 409 if already dispatched
GET /v1/tasks/{id} task definition + current state
GET /v1/tasks/{id}/runs paginated run history
POST /v1/runs/{run_id}/heartbeat
POST /v1/runs/{run_id}/complete
POST /v1/runs/{run_id}/fail
The idempotency key is a client-supplied string scoped to a tenant. The backend stores a (tenant_id, idempotency_key) → task_id mapping and returns the original response on collision.
3. Data Model
Use sharded Postgres (or a globally consistent SQL layer like Spanner/CockroachDB). Shard key: hash(task_id) % 256 logical shards mapped to ~8 physical clusters. Never shard by time — that concentrates all midnight writes onto one shard.
tasks table
Key columns: task_id, tenant_id, shard_id, type, cron_expr, timezone, target, payload_ref, retry_policy, misfire_policy, state, next_run_at, attempt, version, claim_owner, claim_token, claim_expires_at
States: SCHEDULED → CLAIMED → DISPATCHED → (DONE | DEAD), with PAUSED and CANCELLED as terminal sidesteps.
Index on (shard_id, state, next_run_at) — this is the due-work lookup index.
runs table
Key columns: run_id (deterministic: task_id:scheduled_time_epoch), task_id, attempt, state, dispatched_at, lease_expires_at, worker_id, error
Append-heavy, time-partitioned with a TTL. The deterministic run_id is the downstream idempotency key — re-dispatching the same occurrence produces the same ID, letting consumers deduplicate safely.
4. Architecture Overview
Clients → API Service → State Store (sharded SQL)
↕
Scheduler Nodes (each owns shards via etcd leases)
│ in-memory timing wheel
↓
Dispatch Queue (Kafka, per-tenant-class partitions)
↓
Executors (pull) → heartbeat / complete / fail → API Service
Reconciler: periodically scans for stale claims and missed runs
Scheduler nodes elect shard ownership through etcd leases with consistent-hash rebalancing. Each lease carries a monotonically increasing fencing token that is written into every claim_token column. A paused or network-partitioned former owner cannot overwrite a newer owner's claims because its token is stale.
5. Due-Work Discovery and Claiming
Every ~500 ms, the shard owner runs a lookahead query:
UPDATE tasks
SET state = 'CLAIMED',
claim_owner = $node_id,
claim_token = $fence_token,
claim_expires_at = now() + interval '30 seconds'
WHERE task_id IN (
SELECT task_id FROM tasks
WHERE shard_id = $shard
AND state = 'SCHEDULED'
AND next_run_at <= now() + interval '5 seconds'
ORDER BY next_run_at
LIMIT 1000
FOR UPDATE SKIP LOCKED
)
RETURNING *;
The 5-second lookahead loads upcoming tasks into a hierarchical timing wheel (second-level buckets). Timers fire in memory — no DB round-trip at the moment of dispatch.
SKIP LOCKED ensures multiple scanner threads or transitional dual-owners during rebalance do not contend; they each claim non-overlapping rows.
At fire time, three things happen atomically (or with the outbox pattern):
- The task's
versionis re-checked — if it changed (due to a cancel or reschedule that arrived after claiming), drop the task. - Publish the fire event to the queue with
run_idas the message key and deduplication ID. - Transition state: one-time tasks go to
DISPATCHED; cron tasks getnext_run_atadvanced and return toSCHEDULED. Arunsrow is inserted.
Why this achieves at-least-once without loss: if the node crashes after publishing but before committing, claim_expires_at will lapse. The reconciler resets the task to SCHEDULED, and it is re-dispatched with the same deterministic run_id. The consumer deduplicates. A task only leaves SCHEDULED/CLAIMED after a durable publish.
6. Dispatch and Execution Leases
Pull-based executors on Kafka/SQS are preferred over push. Pull gives backpressure for free; the queue absorbs burst. Webhook delivery is a specialized executor pool that does HTTP internally.
Execution lease flow:
- Executor marks run
RUNNINGand setslease_expires_at = now + N. - Executor heartbeats every
N/3. - If the heartbeat lapses, the reconciler marks the run
TIMED_OUT, incrementsattempt, and re-queues with backoff:next_run_at = now + min(max_backoff, base × 2^attempt) + jitter. - After
max_attempts, the task moves toDEADand a message is published to a per-tenant dead-letter topic, queryable through the API for manual replay.
7. Failure Modes and Edge Cases
Thundering herd (100k tasks scheduled for midnight):
Hash sharding spreads the rows. The 5-second lookahead pre-claims them before the moment of truth, so dispatch is memory-bound, not DB-bound. Kafka producer batching (~500 messages per batch) absorbs the burst on the queue side. For non-critical recurring jobs, expose an opt-in jitter field (fire_within_s) that adds rand(0..N) seconds to the nominal time.
Scheduler node failure:
Etcd lease expiry hands the shards to another node within seconds. Stale CLAIMED rows are picked up by their claim_expires_at. No manual intervention needed.
Missed recurring runs during downtime. Three policies, chosen per task at registration:
FIRE_ONCE(default): coalesce all missed windows into a single run, then advance to the next future occurrence. Right for "run the benchmark" jobs.FIRE_ALL: replay every missed window in order. Right for financial period-close jobs where each window has distinct business meaning.SKIP: silently advance to the next future window. Right for "best-effort refresh" jobs where stale runs have no value.
Clock skew: All timestamps use UTC. Dispatcher nodes sync via NTP with a maximum accepted drift of 250 ms. The 5-second lookahead window comfortably absorbs normal drift.
Common mistakes to avoid:
- Sharding by
next_run_at— creates hot partitions around common scheduled times. - Using a single global lock for claiming — serialize throughput and creates a SPOF.
- Forgetting the version re-check before dispatch — allows cancelled tasks to fire.
- Storing large payloads inline — bloats the hot index and slows claiming queries.
- Missing the distinction between dispatch failure (scheduler-side) and execution failure (worker-side) — they require different retry owners.