Distributed Job Scheduler with Pause and Resume
System DesignModel answerLast updated
Build a fault-tolerant scheduler that triggers recurring tasks on cron-like intervals with pause/resume control and multi-instance coordination.
You need to architect a recurring task scheduler that reliably triggers jobs based on time-based rules similar to cron expressions. The execution infrastructure has sufficient capacity, so your design should concentrate on correctness, coordination, and durability rather than autoscaling compute resources.
Your system must handle:
- Time-based recurring tasks using cron-style syntax (for example,
0 */6 * * *means every 6 hours) pause(job_id)— prevent future scheduled triggers, but allow currently-executing instances to completeresume(job_id)— re-enable future scheduled triggers
Provide a complete architectural design that includes: (a) the external API surface, (b) how you model persistent state, (c) the scheduling loop that identifies and fires ready tasks, (d) how pause/resume work correctly even when racing with the scheduler, (e) how multiple scheduler instances coexist safely, and (f) how the system recovers from crashes without losing or silently dropping triggers.
Constraints & Assumptions
- Execution capacity is not a bottleneck — never constrain your design based on worker availability. The complexity is in scheduling correctness, not task execution.
- Scale target (or state your own): approximately $10^6$ task definitions; peak load of tens of thousands of tasks becoming ready in the same minute. Most schedules use minute-level granularity.
- Correctness requirements: every ready, active task must eventually trigger (no silent drops), with at-least-once semantics and best effort to avoid duplicates. Don't assume tasks are inherently idempotent.
- High availability: the scheduler continues operating through single-instance failures; multiple scheduler instances run concurrently.
- The actual task implementation is a black box (HTTP callback, message payload, etc.); you're designing the scheduling infrastructure, not the task logic.
Important Questions to Consider
- What time precision do we need — minute-level only, or sub-second? Should we handle multiple timezones and DST transitions, or is UTC sufficient?
- When resuming after a long pause or outage, should we catch up on missed triggers or simply continue from the next future occurrence?
- Is at-least-once delivery sufficient (assuming task-side deduplication) or do certain task types require at-most-once guarantees?
- What's the usage pattern: many infrequent tasks or few high-frequency tasks? What's the peak per-minute fan-out?
- How do tasks execute — via internal queue, HTTP webhook, container orchestration? What retry and timeout behavior is expected?
- How long should execution history and audit trails be preserved?
Hints
Hint 1
Think about what fields in your task metadata enable safe claiming by competing scheduler instances
Hint 2
Consider how you'd make the query for 'tasks ready to fire' efficient across millions of task definitions
Hint 3
What durable record proves a task was scheduled, even if the scheduler crashes immediately after?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
High-Level Architecture
The system separates concerns into distinct layers:
- API Layer — handles task CRUD, pause/resume operations
- Metadata Store — durable database holding task definitions and scheduling state
- Scheduler Service — multiple replicas scanning for ready tasks and claiming them
- Task Queue — durable buffer decoupling scheduling from execution
- Execution Workers — consume from the queue and run actual task logic
Even with unlimited workers, the queue provides critical benefits: durability (survives scheduler crashes), delivery guarantees (at-least-once semantics), and decoupling (scheduler doesn't block on task completion).
Data Model
Tasks Table:
task_id (PK)
schedule_spec (cron expression)
status (ACTIVE, PAUSED)
next_run_at (timestamp, indexed)
last_scheduled_at (timestamp)
version (optimistic lock counter)
created_at, updated_at
payload (opaque task data)
Executions Table:
execution_id (PK)
task_id (FK)
scheduled_for (timestamp)
idempotency_key (unique: hash of task_id + scheduled_for)
status (PENDING, RUNNING, COMPLETED, FAILED)
created_at
completed_at
result
The version field enables optimistic concurrency control. The idempotency_key prevents duplicate execution records when multiple schedulers race.
Core Scheduler Loop
Each scheduler instance runs this loop (e.g., every 10 seconds):
-
Query:
SELECT * FROM tasks WHERE status = 'ACTIVE' AND next_run_at <= NOW() LIMIT 1000- Index on
(status, next_run_at)makes this cheap even with millions of tasks
- Index on
-
Claim: For each task, attempt optimistic update:
UPDATE tasks SET next_run_at = calculate_next(schedule_spec, next_run_at), last_scheduled_at = NOW(), version = version + 1 WHERE task_id = ? AND version = ?- Only one scheduler succeeds due to version check
-
Record Execution: Insert into executions table with idempotency_key
- Unique constraint prevents duplicates if somehow two schedulers both won the race
-
Enqueue: Publish message to task queue with execution_id
- Queue provides durability; even if scheduler crashes here, the execution record persists
-
Advance: The
next_run_atupdate in step 2 already moved the task forward
The version-based optimistic locking ensures only one scheduler claims each task tick. If the scheduler crashes between steps 3 and 4, a separate recovery process finds PENDING executions older than some threshold and re-enqueues them.
Multi-Instance Coordination
Problem: Multiple schedulers query the same due tasks. Without coordination, they'd double-fire.
Solution: The optimistic lock on version in the UPDATE ensures atomic claiming. If scheduler A and B both read task X at version 5:
- A's UPDATE succeeds, version becomes 6
- B's UPDATE fails (WHERE version = 5 doesn't match), B moves to next task
No distributed locking needed. The database transaction provides the coordination primitive.
Alternative approach: Use explicit leases with claimed_until timestamp and claimer_id. Schedulers only process tasks where claimed_until < NOW(), then set claimed_until = NOW() + 30s. This works but adds lease timeout complexity.
Pause and Resume Semantics
Pause:
UPDATE tasks SET status = 'PAUSED' WHERE task_id = ?
Race condition: A scheduler may have already read the task as ACTIVE and is mid-processing. The optimistic lock doesn't prevent this — the scheduler grabbed the old version before the pause.
Mitigation: After updating status, check executions table for recent entries. If a PENDING execution was just created (within last N seconds), that's expected race behavior. The execution will proceed. This is acceptable: pause means "no new triggers," and the in-flight one was already committed.
Resume:
UPDATE tasks SET status = 'ACTIVE' WHERE task_id = ?
Backfill decision: On resume, should we trigger for all missed occurrences? Two approaches:
- No backfill: Leave
next_run_atas-is. If it's in the past, the next scan fires once, then advances to future. - Backfill: On resume, recalculate
next_run_atfrom current time using schedule_spec.
Most systems choose (1) with a configurable per-task policy, firing once for the entire gap and logging "missed N occurrences."
Crash Recovery and Reliability
Guarantees: At-least-once execution. No task trigger is silently lost.
Mechanisms:
-
Durable execution records: The insert into executions table happens in a transaction. Even if scheduler crashes before enqueueing, the record exists.
-
Orphan detection: A background sweeper finds
PENDINGexecutions older than 60 seconds and re-enqueues them. This handles scheduler crashes between record creation and queue publish. -
Worker heartbeats: Workers update execution status to
RUNNINGand periodically heartbeat. If an execution isRUNNINGfor too long without heartbeat, mark itFAILEDand retry (or dead-letter). -
Queue durability: Use a durable queue (SQS, RabbitMQ with persistence, Kafka). Even if consumers crash, messages survive.
Duplicate handling: At-least-once means tasks may execute twice (scheduler crashes after enqueue but before marking execution started, orphan detector re-enqueues). Solutions:
- Task-side idempotency (best practice)
- Execution-level deduplication: workers check execution_id before starting, skip if already completed
Scaling and Bottlenecks
With unlimited workers, bottlenecks shift to the scheduler layer:
-
Due-task query: The
(status, next_run_at)index keeps the scan at constant cost regardless of total task count. With 10K tasks due per minute and 10-second scan intervals, each scan returns ~1,700 tasks. -
Database writes: Each tick requires an UPDATE (claim) and INSERT (execution record). At peak, 10K writes/minute = 167 writes/second, easily handled by modern databases.
-
Partitioning: For extreme scale, partition tasks by time bucket (hash
task_idmodulo N). Each scheduler instance owns a subset. Rebalance partitions on instance join/leave. -
Queue throughput: 10K messages/minute = 167 msg/sec, negligible for modern queues.
Common Mistakes
- Forgetting the execution record: Directly enqueueing without durable proof means crashed schedulers lose triggers.
- Scanning all tasks on every tick: Without the
next_run_atindex, query cost is O(total tasks). - Using distributed locks instead of optimistic concurrency: Adds complexity; database transactions are sufficient.
- Assuming workers are idempotent: At-least-once requires explicit handling.
- Not handling pause/resume races: Pause must account for in-flight scheduling.
Observability
Key metrics:
- Scheduler lag: 99th percentile time between
next_run_atand actual trigger - Execution creation rate: tasks triggered per minute
- Duplicate rate: executions re-enqueued by orphan detector
- Failure rate: executions ending in FAILED status
- Queue depth: backlog of pending executions
Audit logs for pause/resume operations with timestamps and operator identity enable debugging missed executions.
This design achieves correctness through optimistic concurrency, durability through persistent execution records, and high availability through stateless scheduler replicas coordinated by the database.