Build a Timed and Recurring Task Execution Platform
System DesignModel answerLast updated
Design a service that accepts tasks, fires them immediately, at a future time or on a cron schedule, runs them on a worker fleet, and tracks each execution reliably.
Design a platform that lets clients register units of work and have them executed on a fleet of worker machines at the correct moment. The platform must record the progress of every execution until it ends.
Required behavior
- A task can be launched right away, launched once at a chosen future timestamp, or launched repeatedly according to a recurrence rule such as a cron expression.
- Every individual execution (an attempt window for one trigger, which we call a run) has a status that clients can query, plus its result and logs.
- A failed run is retried according to a retry policy attached to the task. Clients can pause, modify or remove a task, and can cancel a run that is in flight.
Scope notes
- Treat the task payload as opaque, for example a container image or a command with arguments. The platform decides when and where it runs, not what it does.
- Volume, timing precision, task duration and delivery semantics are intentionally unspecified. Ask about them or state your own assumptions explicitly.
What to discuss
- Clarifying questions and the assumptions you settle on.
- Data model and the run lifecycle.
- How due work is discovered efficiently at scale and how multiple scheduler instances divide it.
- How each run is dispatched exactly once in effect, and how crashed or unresponsive workers are detected.
- Retries, timeouts, cancellation, and what happens to recurring runs missed during an outage.
- Behavior under bursts (for example thousands of tasks due at midnight), including priorities, tenant limits and back-pressure.
- Failure of each component and the metrics you would monitor. </hints_placeholder>
Hints
Hint 1
Separate the long-lived task definition from the short-lived run record, and write down the run state machine (for example scheduled, queued, running, succeeded, failed, canceled) before drawing boxes.
Hint 2
Think about how to query 'what is due in the next few seconds' without scanning everything: index or partition by next fire time, and let each scheduler instance own a shard of the keyspace via a lease or consistent hashing.
Hint 3
You cannot get true exactly-once execution over an unreliable network. Aim for at-least-once dispatch combined with leases, heartbeats and a unique run ID so owners can make their work idempotent.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions
I would state these up front:
- About 50M task definitions and about 100M runs per day (roughly 1,200 runs/s on average), with peaks of 20-50x at round times such as the top of the hour or midnight.
- A run should start within about 1-5 seconds of its due time.
- Delivery is at-least-once, and task owners are asked to make work idempotent. True exactly-once is not achievable across worker crashes and network partitions.
- Durations range from seconds to hours, so timeouts and cancellation are needed.
- Priorities and per-tenant quotas are in scope. Cross-task dependencies are a follow-up.
- Missed recurring runs follow a per-task policy:
run_once_late(default),skip, orcatch_up_all.
2. Data model
- Task (definition):
task_id,tenant_id, payload spec, schedule (immediate /run_at/ cron plus timezone), retry policy, timeout, priority,status(active / paused / deleted),next_fire_time,misfire_policy, version. - Run:
run_id,task_id,scheduled_time,attempt,state,worker_id,lease_expiry,started_at,finished_at,result,log_pointer.
Run states: SCHEDULED -> QUEUED -> RUNNING -> SUCCEEDED | FAILED | TIMED_OUT | CANCELED. A failed run with retries left goes back to SCHEDULED with a later time and a higher attempt. Every transition is a conditional update (compare-and-set on state or version), which prevents two actors from both advancing the same run.
Storage: a sharded relational or strongly consistent KV store (shard by task_id) for tasks and runs. Logs and large outputs go to object storage. A unique constraint on (task_id, scheduled_time) guarantees one run per trigger even if two schedulers race.
3. Finding due work
Do not scan. Keep an index on (shard, next_fire_time) for active tasks.
- The keyspace is split into many partitions (for example 1,024). Each scheduler instance holds leases on a subset of partitions (via etcd or ZooKeeper, or a lease table). If an instance dies, its lease expires and another takes over.
- Each scheduler loops every second: select tasks with
next_fire_time <= now + small lookaheadin its partitions, in batches. - For each one, in a single transaction: insert the run row (the unique constraint protects against duplicates), and advance
next_fire_timeusing the cron expression (or mark a one-off as done). Then publish the run to the dispatch queue. - The lookahead lets us place near-future runs into an in-memory timing wheel or delay queue so they fire precisely rather than at poll granularity.
To avoid a crash between commit and publish losing a run, use a transactional outbox: the run row is in SCHEDULED, and a relay publishes it and marks it QUEUED. A sweeper re-publishes runs stuck in SCHEDULED past their due time.
4. Dispatch and execution
- Dispatch queues are split by priority class (and optionally by tenant or resource class such as GPU). Workers pull rather than being pushed to, which gives natural back-pressure.
- A worker claims a run with a conditional update
QUEUED -> RUNNINGthat setsworker_idand alease_expiry. Only one claimant wins. - While running, the worker heartbeats to extend the lease (for example every 10 s with a 30-60 s lease).
- A reaper scans for
RUNNINGruns whose lease expired. It marks the attempt as lost and re-enqueues it under the retry policy. This is where duplicates can arise: a worker that was merely partitioned may still be executing. Fencing the status writes with the attempt number stops the stale worker from overwriting results, but side effects may still occur, so the run ID is passed to the job as an idempotency key. - Timeouts are enforced by the worker (kill the process) and backed up by the reaper in case the worker is gone.
- Cancel: set a
cancel_requestedflag. The worker sees it on its next heartbeat response and terminates the job. If the run is still queued, the conditional update toCANCELEDremoves it.
5. Retries and missed runs
- Retry policy: max attempts, exponential backoff with jitter (for example
min(cap, base * 2^n) * rand(0.5, 1)), and a list of retryable versus fatal failure types. After the last attempt, the run is terminal and an alert or dead-letter record is created. - Misfires: after an outage, a scheduler finds
next_fire_timefar in the past. Withrun_once_lateit creates a single run and jumpsnext_fire_timeto the next future slot. Withskipit just jumps ahead. Withcatch_up_allit creates a run per missed slot, rate-limited to avoid a stampede. - Cron specifics: store the timezone, and define behavior across DST (skipped hour runs once at the next valid time; repeated hour runs once).
- Overlap policy per task: allow, skip if the previous run is still going, or queue.
6. Bursts and fairness
- Add jitter or spreading for tasks that opt in, since many users choose
0 0 * * *. - Pre-stage: load due runs a few seconds early so the midnight spike is a queue-drain problem, not a database-query problem.
- Per-tenant concurrency limits and token-bucket submission rates; weighted fair queuing between tenants so one noisy tenant cannot starve others.
- Autoscale workers on queue depth and oldest-message age. Shed or delay low-priority runs first and return a clear status when quotas are hit.
7. Failure modes
| Component | Failure | Mitigation |
|---|---|---|
| Scheduler instance | Crash | Partition lease expires, another instance takes over; unique constraint prevents duplicate runs |
| Queue | Outage or loss | Runs remain in the DB; sweeper re-publishes |
| Worker | Crash or partition | Heartbeat lease expiry, reaper retries |
| DB shard | Failover | Replicated, leader election; schedulers retry idempotently |
| Clock skew | Early or late firing | Use DB time or a single time source for comparisons; keep leases generous |
8. Metrics
Scheduling lag (actual start minus due time, p50/p99), queue depth and oldest age, run success rate, retry rate, lease-expiry count, duplicate-start count, misfire count, per-tenant utilization, and worker saturation. Alert mainly on scheduling lag p99 and oldest queued age.
Common mistakes
- Claiming exactly-once without explaining idempotency and fencing.
- Polling the whole task table instead of using a time-indexed, partitioned lookup.
- Storing only the definition and not modeling runs separately.
- Forgetting a policy for missed recurring runs, DST, and overlapping runs.
- Using a single scheduler leader as a bottleneck and a single point of failure.
- Ignoring the thundering herd at round timestamps.