Build a Fault-Tolerant Distributed Task Timer Service
System DesignModel answerLast updated
Design a distributed service that runs one-off and repeating tasks on time at the scale of millions of jobs, survives worker crashes, and limits duplicate runs despite clock skew.
Scenario
You are asked to design a backend service that fires tasks at their scheduled time. It must handle two kinds of tasks:
- One-time tasks: run once at a given timestamp.
- Recurring tasks: run again and again at a fixed interval, in seconds.
A fleet of N worker machines executes the tasks. The service must make sure every task runs at least once, while keeping duplicate runs as rare as possible.
Operations to support
ScheduleJob(job_id, payload, run_at_timestamp): durably store a one-time task.ScheduleRecurringJob(job_id, payload, interval): durably store a task that fires repeatedly.ExecuteJobs(): the loop workers use to find tasks that are due and run them.
Requirements
- Scale: millions of active scheduled tasks.
- Fault tolerance: if a worker dies while running a task, another worker must take that task over.
- Precision: a task should start within a few seconds of its scheduled time.
- Latency: keep the gap between "task becomes due" and "task is picked up" small.
Constraints
- You may choose any database for persistence.
- Assume N worker nodes running in parallel.
- Account for clock skew between servers.
What to cover in your answer
- Data model: the schema for task definitions, schedules, and run state.
- Task acquisition: how workers claim tasks without stepping on each other (locks, leases, sharding, etc.).
- Failure handling: how you detect a dead worker and put its task back into circulation.
- Architecture: the main components (API layer, storage, the component that finds due tasks, the execution nodes) and how they interact.
State your assumptions about scale (task count, peak rate) before you begin.
Hints
Hint 1
Say early that exactly-once execution cannot be guaranteed when machines crash. Aim for at-least-once delivery from the scheduler plus idempotent task handlers.
Hint 2
Separate the task definition (with its next fire time) from each individual run record, and give each run a deterministic ID such as job_id plus scheduled time, so a unique constraint collapses duplicate triggers.
Hint 3
Split the system into two roles: a small set of trigger nodes that decide what is due (each owning a hash-based slice of the data) and many executors that do the work. Use time-limited leases, and take all time comparisons from the database clock rather than from worker clocks.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and framing
- About 10M active tasks at roughly 1 KB each, so around 10 GB of hot data. That fits comfortably on a sharded relational store.
- Average load of about 2K triggers/sec, with peaks near 20K/sec because many schedules land on the top of the minute or hour.
- Target pickup latency of 2-5 seconds after the scheduled time.
- Semantics: at-least-once. Exactly-once is impossible once crashes are possible, because a worker can finish the work and die before acknowledging it. So the scheduler guarantees at-least-once, and task handlers must be idempotent.
- Out of scope for v1: dependency graphs, cron expressions, per-tenant quotas.
2. API
ScheduleJob(job_id, payload, run_at)returns success, or a conflict if the ID already exists.ScheduleRecurringJob(job_id, payload, interval, start_ts?).CancelJob(job_id)andGetJob(job_id).
The client-supplied job_id is the idempotency key for creation, so retried requests are safe. ExecuteJobs() is an internal worker loop, not a public endpoint.
3. Data model
Keep the definition separate from each run.
jobs: job_id (PK), shard_id = hash(job_id) % 1024, payload (or a blob pointer), type (one-time or recurring), interval_s, next_run_at, state (active, paused, done, cancelled), version.
Index: (shard_id, next_run_at) restricted to active jobs.
executions: execution_id (PK) = job_id:scheduled_ts, status (pending, claimed, completed, failed, dead), lease_owner, lease_expires_at, fencing_token, attempt, last_error.
Index: (status, lease_expires_at).
The deterministic execution_id is the key trick. If two trigger nodes try to create the same occurrence, the unique constraint makes the second insert a no-op.
4. Architecture
Clients -> API -> Sharded job store
^ |
shard leases | v
(etcd/ZK) Trigger nodes -> Partitioned queue
|
Executor workers -> executions table
|
Reaper / dead-letter queue
Trigger nodes (few, precise):
- Each owns a set of the 1024 logical shards via leases in a coordination service.
- About once per second, each scans its shards for
next_run_at <= db_now()with a batch limit. - In one transaction it inserts the execution row (ignore on conflict), advances
next_run_at(or marks a one-time job done), and writes an outbox record. A relay publishes the outbox to the queue.
Executors (many, stateless):
- Take a message from the queue.
- Claim the execution with a lease.
- Run the task.
- Mark it complete.
This split means slow tasks never delay triggering, executors scale independently, and the queue absorbs top-of-the-minute bursts.
5. Claiming without conflicts
A single conditional update, evaluated with the database clock:
UPDATE executions
SET status='CLAIMED', lease_owner=:w,
lease_expires_at = now() + interval '60 seconds',
fencing_token = fencing_token + 1,
attempt = attempt + 1
WHERE execution_id = :id
AND (status='PENDING'
OR (status='CLAIMED' AND lease_expires_at < now()))
RETURNING fencing_token;
Zero rows returned means someone else holds it, so skip. If you poll the database directly without a queue, SELECT ... FOR UPDATE SKIP LOCKED lets many workers take disjoint batches without blocking.
Partitioning: shard by hash of job_id, not by time range. Time-range partitions put all currently-due work on one hot partition. Using 1024 logical shards over fewer physical nodes allows rebalancing without rehashing, and one trigger owner per shard avoids contention between triggers.
6. Failure handling
- Executor crash: the lease expires, and the claim query lets another worker take over. A reaper sweeps expired claims and re-enqueues them with exponential backoff. After a maximum attempt count the run moves to a dead state and a dead-letter queue, and an alert fires.
- Trigger crash: its coordination-service session expires (around 10 seconds) and shards are reassigned. The new owner rescans for due jobs, so nothing is lost. Overlap during handoff is harmless thanks to the deterministic execution ID.
- Lost queue message: the outbox relay retries, and the reaper republishes pending executions that stay unclaimed too long.
- Slow worker that outlives its lease: the fencing token is passed to downstream writes, which reject stale tokens. Workers also treat their lease as ending a bit early (say 10% of its length).
7. Clock skew
Never compare timestamps produced by different hosts. All "is it due" checks and lease expiries use the database's now(). Worker clocks are used only for local timeouts, with a safety margin.
8. Recurring tasks
- Compute
next_run_at = scheduled_ts + interval, notnow() + interval, otherwise the schedule drifts later every run. - If the system was down and missed several intervals, apply a configurable misfire policy: run once then skip to the next future slot (the usual default), or catch up on every missed run.
9. Precision and trade-offs
A one-second poll per shard satisfies a "few seconds" target. For tighter timing, trigger nodes can preload the next minute of due jobs into an in-memory timing wheel and fire from there, while still committing state to the database.
| Choice | Benefit | Cost |
|---|---|---|
| Pure DB polling | Simple, transactional | Load grows with job count and poll rate |
| Queue between trigger and executor | Burst absorption, decoupling | Extra component, outbox complexity |
| Short leases | Fast recovery | More duplicates for slow jobs |
| Long leases | Fewer duplicates | Slower failover; use heartbeats to extend |
10. Common mistakes
- Claiming exactly-once delivery.
- Using worker clocks for due checks or lease expiry.
- Partitioning by time, creating hot shards.
- Computing the next recurrence from the current time, causing drift.
- Having no dead-letter path, so poison tasks retry forever.
- Letting every worker scan the full table, which causes lock contention and thundering herds.