Build a durable task scheduler with delayed execution
System DesignModel answerLast updated
Design a scheduler that runs jobs after a specified delay, with APIs, data structures, persistence, concurrency control, and recovery.
You need to design a task scheduler that executes jobs after a configurable delay. The scheduler must survive crashes, handle concurrent operations, and support cancellation.
Your design should include:
- API surface: methods for scheduling, cancelling, and querying task status
- Internal data structures: how you organize pending tasks for efficient retrieval
- Persistence layer: ensuring durability across process restarts
- Execution model: how workers claim and run tasks
- Concurrency control: handling race conditions and limiting parallel execution
- Delivery guarantees: at-least-once vs exactly-once semantics
- Time complexity of core operations
Provide class or component diagrams showing the relationships between major pieces. Discuss how you would verify correctness through testing.
Assume you're building for a single-node service handling around 10,000 schedules per second with delays ranging from seconds to weeks, and up to a million pending tasks at any time.
Hints
Hint 1
Start by clarifying functional requirements and scale constraints before proposing structures
Hint 2
Consider min-heap for precise timing or timing wheels for high-throughput cancellation scenarios
Hint 3
Use compare-and-swap or optimistic locking to prevent multiple workers from executing the same task
Hint 4
Design for testability by abstracting time and storage behind interfaces
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Durable Task Scheduler Design
1. Requirements Clarification
I'd begin by establishing scope:
Core functionality:
schedule(task, delaySeconds) -> taskId: enqueue a task to run after the specified delaycancel(taskId) -> boolean: attempt to cancel before execution startsgetStatus(taskId) -> Status: query current state (PENDING, EXECUTING, COMPLETED, FAILED, CANCELLED)
Quality attributes:
- Durability: acknowledged tasks survive crashes
- Timing accuracy: execute within ~100ms of target time (soft real-time)
- Throughput: handle 10K schedules/sec, 2K executions/sec
- Capacity: support 1M pending tasks
- Delivery: at-least-once execution (handlers must be idempotent)
- Concurrency: configurable execution limits globally and per task type
I'd note that exactly-once execution is impossible across failures, so we provide at-least-once with idempotency support.
2. API Design
class TaskScheduler:
def schedule(self, task: Task, delay_sec: float,
idempotency_token: Optional[str] = None) -> str:
"""Returns task_id. Token prevents duplicate scheduling."""
pass
def cancel(self, task_id: str) -> bool:
"""Returns True if cancelled before execution."""
pass
def get_status(self, task_id: str) -> TaskStatus:
pass
def start(self) -> None:
"""Initialize, recover from disk, start dispatcher."""
pass
def shutdown(self, graceful: bool = True) -> None:
pass
The Task object contains a task_type (mapped to a handler function), serialized payload, max_retries, and retry_backoff configuration.
3. Architecture Components
┌──────────────┐ ┌─────────────┐ ┌──────────────┐
│ Scheduler │─────▶│ TaskStore │◀─────│ Loader │
│ (API layer) │ │ (abstract) │ │ (recovery) │
└──────┬───────┘ └─────────────┘ └──────────────┘
│ △
│ ┌─────┴─────┐
▼ │ │
┌──────────────┐ SQLStore FileStore
│ PriorityQueue│
│ (in-memory) │
└──────┬───────┘
│
▼
┌──────────────┐ ┌─────────────┐ ┌──────────────┐
│ Dispatcher │─────▶│ WorkerPool │─────▶│ Handlers │
│ (1 thread) │ │ (N threads) │ │ (registry) │
└──────────────┘ └─────────────┘ └──────────────┘
│
▼
┌──────────────┐ ┌─────────────┐
│ ClockService │ │ TaskRecord │
│ (injectable) │ │ (model) │
└──────────────┘ └─────────────┘
Abstracting TaskStore and ClockService behind interfaces enables unit testing with fakes.
4. Data Structure Selection
Primary choice: Min-heap indexed by execution time
heap: List[Tuple[float, int, str]] # (due_time, sequence, task_id)
index: Dict[str, TaskRecord] # fast lookup for cancel/status
- Insert: O(log n)
- Peek next due: O(1)
- Pop: O(log n)
- Cancel: O(1) lazy deletion—mark CANCELLED in index; skip when popped
For cancel, rather than searching the heap (O(n)), I mark the record as cancelled in the index. When the dispatcher pops it, it checks the index and discards tombstones. Compact the heap when cancelled entries exceed 50%.
Alternative: Hierarchical timing wheel
Better for very high cancellation rates (e.g., connection timeouts). Uses bucketed rings with cascading for longer delays. Insert/cancel/fire are O(1) amortized, but precision is limited to the tick interval. For this scale and accuracy requirement, the heap is simpler.
Memory management for long delays: Keep only tasks due within the next 10 minutes in the heap. Store the rest in the database with an index on (status, due_time). A background thread loads the next window periodically.
5. Dispatcher and Execution Flow
Single dispatcher thread:
def dispatch_loop(self):
while self.running:
with self.lock:
while self.running and (not self.heap or
self.heap[0][0] > clock.now()):
timeout = self.heap[0][0] - clock.now() if self.heap else None
self.condition.wait(timeout)
if not self.running:
break
due_time, _, task_id = heapq.heappop(self.heap)
# Acquire execution lease via CAS
if self.store.claim_task(task_id, lease_duration=60):
self.worker_pool.submit(task_id)
The dispatcher sleeps until the next task is due, wakes up, and attempts to claim it atomically. Only if the claim succeeds does it submit to workers.
Worker execution:
- Load task details from store
- Invoke handler with payload
- On success: mark COMPLETED
- On failure: increment attempts, calculate backoff, update due_time and re-enqueue if under retry limit; otherwise mark FAILED and move to dead-letter queue
Concurrency control:
- Bounded thread pool (e.g., 100 threads)
- Per-task-type semaphores to prevent one type from monopolizing workers
- If pool is saturated, dispatcher blocks—tasks run late rather than being lost
6. Persistence Strategy
On schedule:
INSERT INTO tasks (id, type, payload, status, due_at, idempotency_token, version)
VALUES (?, ?, ?, 'PENDING', ?, ?, 0)
ON CONFLICT (idempotency_token) DO NOTHING RETURNING id;
Only return the task ID after the write commits—acknowledgment equals durability.
On claim (CAS pattern):
UPDATE tasks
SET status = 'EXECUTING', lease_until = ?, version = version + 1
WHERE id = ? AND status = 'PENDING' AND version = ?;
If zero rows updated, another worker claimed it or it was cancelled.
On cancel:
UPDATE tasks SET status = 'CANCELLED' WHERE id = ? AND status = 'PENDING';
Returns false if already executing.
Storage options:
- Relational DB with index on
(status, due_at)for fast pending-task queries - Embedded option: append-only WAL with periodic snapshots
7. Recovery After Restart
On startup:
- Load all tasks with
status IN ('PENDING', 'EXECUTING')anddue_atwithin the next 10 minutes - For tasks marked EXECUTING where
lease_until < now(), reset to PENDING (the previous worker crashed mid-execution) - Rebuild the in-memory heap
- Resume normal operation
Handling clock drift:
- Use monotonic time for internal waits
- Store absolute wall-clock timestamps (
due_at) - On restart, recalculate timeouts relative to current time
- For distributed deployments, require NTP synchronization
8. Delivery Semantics
At-least-once: A task may execute multiple times if:
- A worker crashes mid-execution and lease expires
- Database commit succeeds but the process crashes before marking completion
Making handlers safe:
- Accept an
idempotency_key(the task ID or a client-provided token) - Handlers must check if work was already done (query external state, check a processed-IDs table, etc.)
Exactly-once is unachievable without distributed transactions across all involved systems. At-least-once with idempotent handlers is the pragmatic choice.
9. Time Complexity Summary
| Operation | Complexity |
|---|---|
| schedule | O(log n) heap insert + O(1) DB write |
| cancel | O(1) index update + O(1) DB write |
| getStatus | O(1) index lookup |
| dispatch | O(log n) pop + O(1) claim |
With the windowing strategy, n is bounded to tasks due in the next 10 minutes rather than total pending.
10. Testing Strategy
Unit tests:
- Use
FakeClockto control time progression without sleeps - Use
InMemoryTaskStoreto avoid database setup - Test dispatcher with injected dependencies: schedule tasks, advance clock, verify execution order
- Test race conditions: concurrent cancel while dispatcher claims
Integration tests:
- Real database with transaction rollback between tests
- Verify durability: schedule, kill process, restart, confirm task executes
- Test retry logic with a handler that fails N times then succeeds
- Simulate clock jumps (forward/backward) and verify correctness
Chaos tests:
- Random process kills during execution
- Concurrent schedule/cancel storms
- Inject artificial delays in handlers to test lease expiration
Key properties to verify:
- No task executes before its due time
- Every acknowledged task eventually executes (liveness)
- No task executes twice concurrently (safety via CAS)
- Cancelled tasks never execute (if cancel wins the race)
Common Pitfalls
- Not using CAS for state transitions: leads to duplicate execution
- Sleeping with absolute time instead of relative: causes issues with clock adjustments
- Unbounded in-memory storage: crashes under load
- Forgetting to persist before acknowledging: loses tasks on crash
- No concurrency limits: one slow handler blocks everything
This design balances simplicity, correctness, and performance for the stated scale while remaining testable and maintainable.