Design a Recurring Task Scheduler with Pause and Resume
System DesignModel answerLast updated
Design a distributed service that registers one-time and cron-based tasks, dispatches them when due, and supports pausing and resuming schedules reliably.
The Problem
Build a task scheduling service. Clients register tasks that should run either once at a specific future time or repeatedly according to a cron expression. Clients can also pause a task at any point and later resume it.
Your service is responsible for deciding when each task is due, dispatching it to an available worker, and maintaining a complete history of every run. Assume you have as many workers as you need — capacity for actually executing tasks is not a constraint. The hard parts are correctness, timing, and reliability.
What to Design
- A client-facing API to register, pause, resume, and query tasks
- A data model for tasks, their schedules, their pause state, and individual run records
- A mechanism to efficiently find tasks that are due without scanning everything
- A dispatch path from your scheduler to workers
- Handling for failures, duplicate runs, and bursts of tasks that all fire at the same time
Constraints and Clarifications
The following are deliberately left open. Either ask clarifying questions before you start, or state your assumptions explicitly and justify them:
- How many tasks are registered in total, and how many become due in the same second (for example, at the top of the hour)?
- How tight is the start-time requirement — must a task fire within a second of its scheduled time, or is a few seconds acceptable?
- What is the run guarantee: is it acceptable to run a task twice after a crash, or must each scheduled occurrence execute exactly once?
- If a cron task is still executing when the next occurrence is due, should the new occurrence start immediately, queue up, or be skipped?
- When a task is paused, what happens to a run already in progress? On resume, should occurrences that were missed during the pause catch up or be skipped?
- In which time zone are cron expressions evaluated, and what should happen when a clock change causes an occurrence to be skipped or duplicated?
What a Strong Answer Looks Like
A strong answer settles the open questions first, then covers the API and data model, the indexing strategy for due-task lookup, the dispatch pipeline, pause and resume semantics in detail, at-least-once vs. exactly-once trade-offs, and how the scheduler itself scales and recovers from failures.
Hints
Hint 1
Before sketching any architecture, nail down the numbers and guarantees. Volume and timing precision change the indexing strategy. At-least-once vs. exactly-once changes almost everything downstream — lease design, idempotency, retry logic, and worker contracts.
Hint 2
For due-task lookup, think about what you can index. A time-ordered index on next_run_at lets you query with a simple range scan instead of scanning every task. After dispatch, you need to compute and write the next occurrence atomically with claiming the current one.
Hint 3
Pause semantics have two separate sub-problems: what to do with a run that is already in flight when pause is called, and what to do with occurrences that fall inside the paused window when resume is called. Treat these independently and be explicit about each choice.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying Questions and Assumptions
Settling these before designing is the first thing a strong answer does.
- Scale: 10 million registered tasks; up to 100,000 fire within the same second at the top of the hour.
- Start-time precision: within 1–2 seconds of the scheduled time.
- Run guarantee: at-least-once is acceptable; idempotency keys let workers deduplicate if needed. Exactly-once is possible but expensive — cover the trade-off.
- Overlap policy: if a cron task is still running when the next occurrence is due, skip the new occurrence and record it as skipped (simpler, avoids unbounded queue growth).
- Pause semantics: a run already in flight completes normally; occurrences that fall inside the paused window are skipped, not replayed on resume.
- Time zone: cron expressions are stored in UTC; callers convert before registering. DST edge cases are the caller's responsibility.
API
POST /tasks — register a new task (one-time or cron)
GET /tasks/{id} — fetch task config and current state
PATCH /tasks/{id}/pause — pause a task
PATCH /tasks/{id}/resume — resume a paused task
DELETE /tasks/{id} — deregister
GET /tasks/{id}/runs — paginated run history
A task payload carries: schedule (ISO-8601 timestamp or cron expression), payload (opaque bytes forwarded to the worker), overlap_policy (skip | allow | queue), and timezone.
Data Model
tasks table
| column | notes |
|---|---|
| id | UUID |
| schedule_type | once or cron |
| cron_expr / run_at | depends on type |
| status | active, paused, completed |
| next_run_at | indexed; null when paused or completed |
| version | optimistic-lock counter |
runs table
| column | notes |
|---|---|
| id | UUID, also the idempotency key sent to the worker |
| task_id | FK |
| scheduled_at | the intended fire time |
| claimed_at | when a scheduler instance picked it up |
| lease_expires_at | heartbeat deadline |
| status | pending, running, succeeded, failed, skipped |
Due-Task Lookup and Dispatch
The central loop runs on every scheduler instance:
- Range scan:
SELECT … WHERE status = 'active' AND next_run_at <= now() ORDER BY next_run_at LIMIT 500— a simple B-tree index on(status, next_run_at)makes this fast even at 10 M rows. - Optimistic claim: update the row, setting
status = 'running'andlease_expires_at = now() + 30s, using aWHERE version = $current_versionpredicate. If zero rows are updated, another scheduler instance claimed it first — skip and move on. - Insert a run record with a fresh UUID as the idempotency key.
- Enqueue the task payload plus the run ID onto a message queue (Kafka or SQS). The queue is the durability buffer for the burst at the top of the hour.
- Write next_run_at: for cron tasks, compute the next occurrence using the cron expression and write it back; for one-time tasks, set
status = 'completed'.
Workers consume from the queue, execute the task, and call back to mark the run succeeded or failed. The run ID is the idempotency key — workers that process the same message twice are safe to deduplicate at the application layer.
Lease renewal and recovery: a background thread on each worker heartbeats the lease every 10 seconds. A separate reaper process scans for runs where lease_expires_at < now() and the status is still running — these are re-enqueued as retries.
Pause and Resume
Pause:
- Set
status = 'paused'andnext_run_at = NULLon the task row. - Any run currently in the queue may still execute — that is acceptable under at-least-once semantics. Workers check
task.statusbefore starting work if exactly-once behavior is critical.
Resume:
- Set
status = 'active'. - Compute the next occurrence from now, not from the time the task was paused. This skips all missed occurrences, which is the assumed policy. If catch-up is needed instead, enumerate every missed occurrence between pause time and now and insert them as pending run records.
Scaling the Scheduler
Running a single scheduler loop is a SPOF. Run multiple instances with the same loop, relying on the optimistic-lock claim in step 2 to ensure each due task is dispatched exactly once. No leader election is required.
At the top-of-the-hour burst, the range scan produces a large batch. This is fine — the message queue absorbs it and workers drain it over the following seconds. The observable effect is slightly elevated dispatch lag, which should stay within the 1–2 second SLA at typical worker throughput.
Sharding for very high volume: partition the tasks table by task_id % N and assign each scheduler instance a shard. This eliminates cross-instance contention entirely at the cost of operational complexity.
Common Mistakes to Avoid
- Polling every row on every tick. Without the
(status, next_run_at)index this kills the database at scale. - Writing next_run_at after enqueue, not atomically with the claim. A crash between enqueue and the write causes a missed occurrence.
- Forgetting lease expiry. Without it, a crashed worker holds a run in
runningstate forever. - Resuming from the pause timestamp. Unless catch-up is explicitly required, this floods the queue with old occurrences and is almost never what the client wants.
- Ignoring the overlap policy. Silently firing concurrent occurrences of a long-running cron task is a common source of data corruption in production.
Key Metrics to Expose
- Dispatch lag:
now() - scheduled_atat the moment of enqueue. The p99 should stay under 2 seconds. - Lease expiry rate: elevated rate signals worker crashes or slow jobs.
- Queue depth: leading indicator of a burst that workers cannot drain in time.