Design a Recurring Task Scheduler That Never Skips a Run
System DesignModel answerLast updated
Design a service that stores 100K recurring cron-style tasks, keeps up to 10K runs in flight, and guarantees each scheduled fire executes at least once despite crashes.
Problem
Design a backend service that lets users register recurring tasks. Each task carries a cron expression, and the service must start a run of that task every time the expression fires.
Requirements and assumptions
- Roughly 100,000 task definitions are stored.
- Up to 10,000 runs may be executing at the same moment.
- Every task is schedule-driven. There is no "start immediately" request; a run begins only when its cron expression fires.
- Delivery is at least once. Every scheduled fire must eventually produce an execution. Occasionally running the same fire twice is acceptable, but silently dropping a fire is not.
- The following are left open. Ask about them or state your own assumptions:
- What a "run" actually does (HTTP call, container launch, message publish) and how long it lasts.
- How close to the scheduled instant a run must begin.
- The finest schedule resolution (per minute, or per few seconds).
- What should happen to fires that were due while the system was down.
- What to do when a task's previous run is still going as its next fire arrives.
What to produce
Part 1: Data model and API
Define the entities, their keys, and where each task's next fire time lives. Provide endpoints to create, update, pause and delete tasks, and to inspect past runs. Decide whether the schedule should sit on the task record or in a separate entity, and defend the choice. Explain what happens to already-planned runs when a task is edited, paused or deleted.
Part 2: Finding and executing due work
Explain how the system detects which tasks are due among 100,000, hands them to workers, and keeps concurrency within the limit. Cover running several scheduler instances for availability without dispatching twice, and describe what happens when thousands of tasks share one fire time (for example, the top of the hour).
Part 3: At-least-once guarantee
Walk through each place a scheduled run could be lost: a scheduler crashing mid-plan, a dispatch message that never arrives, a worker dying mid-run. Show how the design ensures each fire is eventually executed, where duplicates can appear, and how fires missed during downtime are treated.
Hints
Hint 1
Estimate the load first. 100K tasks with minute-level schedules means at most about 100K fires per minute in the worst case (roughly 1,700 per second on average, far higher in a burst). That is small enough for a single relational database to handle as the source of truth.
Hint 2
Think about what a schedule really is. If each task has exactly one cron expression and nothing else shares it, a separate schedule entity adds a join and a consistency problem without adding capability. What requirement would justify splitting it out?
Hint 3
Make 'plan a run' a single atomic step: insert the run row and advance the task's next_fire_at in one transaction. Then treat the run row as a durable work item that is claimed with a lease, so crashes at any later point leave something a sweeper can find and retry.
Hint 4
Separate 'finding due work' from 'executing it'. Use a queue or a claim query with SKIP LOCKED between them, and enforce the 10K bound with a worker pool size or a semaphore rather than by throttling the scheduler.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying assumptions
I would state these up front:
- A run calls a user-defined target (HTTP endpoint or queue message) and lasts seconds to minutes.
- Schedules have one-minute granularity; a run should start within about 5 seconds of its fire time under normal load.
- Overlap policy is configurable per task, defaulting to "allow", with "skip" as an option.
- After an outage, the system runs the most recent missed fire per task by default (a catch-up policy). Running every missed fire is an option for tasks that need it.
Rough numbers: 100K tasks firing every minute is the worst case, about 1,700 runs per second on average. Realistically most tasks are hourly or daily, so the average is far lower, but top-of-hour bursts of 10K to 50K simultaneous fires are plausible. At 10K concurrent runs averaging 30 seconds, steady throughput is about 330 runs per second. A run row of about 200 bytes at, say, 20M runs per day is 4 GB per day, so retention (for example 30 days) and partitioning matter.
Part 1: Data model and API
Task (task_id PK, owner, target, payload, cron_expr, timezone, status active/paused/deleted, overlap_policy, max_retries, next_fire_at, version).
Run (run_id PK, task_id, fire_time, status pending/leased/succeeded/failed, attempt, lease_owner, lease_expires_at, started_at, finished_at, error). Add a unique key on (task_id, fire_time). This is the idempotency anchor: a fire can only be planned once, no matter how many schedulers race.
Schedule: keep it on the task. Each task has exactly one cron expression, the expression is only ever read together with the task, and next_fire_at must be updated atomically with run creation. A separate table adds a join on the hot path and a possible inconsistency between two rows. I would split it out only if schedules were shared across tasks (many tasks use "every hour"), a task could have multiple schedules, or schedules had their own lifecycle (calendars, blackout windows). None of these hold here.
Index: (status, next_fire_at) on Task, which makes "what is due" a range scan.
API
POST /tasks,GET /tasks/{id},PUT /tasks/{id},DELETE /tasks/{id}POST /tasks/{id}:pause,POST /tasks/{id}:resumeGET /tasks/{id}/runs?cursor=...&status=...,GET /runs/{run_id}
Edits, pauses, deletes: Updating the cron expression recomputes next_fire_at in the same transaction. Pausing and deleting set status; the planner ignores non-active tasks. Runs already pending are either cancelled (delete) or allowed to finish (pause), and I would state the choice. Runs already executing are never killed implicitly.
Part 2: Finding due work and executing it
Planner. Every second, each scheduler instance runs:
SELECT ... FROM task WHERE status='active' AND next_fire_at <= now() ORDER BY next_fire_at LIMIT 500 FOR UPDATE SKIP LOCKED- For each task, in the same transaction: insert a Run with
fire_time = next_fire_at, then setnext_fire_atto the next cron match after now. - Commit.
SKIP LOCKED lets several scheduler instances work in parallel without blocking or double-planning, and the unique key on (task_id, fire_time) is a second safety net. No leader election is required, and any instance can die at any time.
Dispatch. Pending runs go to workers in one of two ways: workers claim directly with UPDATE run SET status='leased', lease_owner=?, lease_expires_at=now()+60s WHERE run_id IN (SELECT ... WHERE status='pending' ORDER BY fire_time LIMIT n FOR UPDATE SKIP LOCKED), or a dispatcher pushes run IDs onto a queue (Kafka, SQS) and the worker claims the row when it receives the message. The database row remains the truth; the queue is only a wake-up signal.
Concurrency bound. The 10K limit is enforced on the pull side. The fleet has a fixed number of slots (for example 100 workers with 100 slots each), and a worker only claims work when it has a free slot. Overload therefore turns into queue delay, not an overload of targets. A global counter of leased runs can add a hard cap if the fleet is elastic.
Bursts. At the top of the hour, 50K fires may be planned within a second or two, since planning is just inserts. Execution then drains at fleet capacity: with 10K slots and 30-second runs, about 330 starts per second, so the last run in a 50K burst starts roughly 150 seconds late. Mitigations include ordering by fire time and priority, autoscaling on queue depth, and optional jitter for tasks that do not need exact timing. I would report start delay as a first-class metric.
Part 3: At-least-once
Walk the failure points:
- Scheduler crashes while planning. Run insert and
next_fire_atadvance share one transaction, so either both happen or neither. If neither, the task is still due and another instance picks it up. No fire is lost, and no fire is planned twice. - Dispatch message lost. The run row remains
pending, so a sweeper that re-enqueues pending runs older than a few seconds recovers it. The queue is never the source of truth. - Worker dies mid-run. The worker holds a lease and heartbeats to extend it. If heartbeats stop,
lease_expires_atpasses and the sweeper returns the run topendingwithattempt+1. This is where duplicates arise: a slow worker whose lease expired may still be running when a second worker starts. - Failures. Retry with exponential backoff and jitter up to
max_retries, then markfailedand alert the owner. Failed runs stay visible in the history. - Downtime. On restart,
next_fire_atis in the past for many tasks. The planner applies the catch-up policy: it creates one run for the latest missed fire (default), or one per missed fire if configured, and then jumpsnext_fire_atforward. Nothing is silently dropped, and the choice is explicit.
Containing duplicates. Pass each handler an idempotency key, task_id + fire_time, so the target can deduplicate. Use fencing: a completion write is accepted only if lease_owner and attempt still match, so a stale worker cannot overwrite a newer result. Document that handlers must be idempotent.
Trade-offs and common mistakes
- Relying on an in-memory timer or a single leader with no durable state loses fires on a crash.
- Advancing
next_fire_atin one step and creating the run in another opens a window in which a crash drops a fire. - Treating the queue as the source of truth makes message loss equal fire loss.
- Putting the schedule in a separate table "because a generic design does" without a requirement for it.
- Ignoring overlap policy and the missed-fire policy.
Observability
Track start delay (actual minus scheduled), pending queue depth, runs in flight versus the 10K bound, expired leases, retry counts, and failed-run counts, with alerts on start-delay p99 and on any run stuck in leased beyond its timeout.
Scaling note
A single well-indexed relational primary handles this load comfortably. If it grows by 10x or more, shard Task and Run by task_id hash and keep the planner per shard.