Building a Task Scheduler for Millions of Jobs
System DesignModel answerLast updated
Design a system that persists and triggers jobs at specified times, handling millions of scheduled tasks and thousands of executions per second.
You need to architect a task scheduling platform that executes work at predetermined times or on repeating intervals.
What the System Must Do
Your scheduler should support:
- Delayed execution: tasks that run once at a future timestamp
- Repeating schedules: tasks that fire on cron-style patterns (hourly, daily, custom expressions)
- Durability: tasks survive restarts and failures
- Timing accuracy: tasks fire at or shortly after their scheduled moment
- Scale: accommodate tens of millions of active tasks with peak execution rates around 10–20k/second
What "Good" Looks Like
- Delivery: every task fires at least once; missing a scheduled run is unacceptable
- Latency: p99 delay between scheduled time and actual trigger under 2 seconds
- Uptime: individual server failures don't stop the system
What to Provide
- Overall architecture and component responsibilities
- API surface for creating, modifying, and canceling tasks
- Data modeling: what you store and how you query it efficiently
- The "hot path" — how you find and fire what's due right now at high throughput
- Failure scenarios: node crashes, duplicate triggers, slow workers
Assume tasks are delivered as messages (HTTP callbacks, queue entries, function invocations). Your scheduler doesn't execute user code directly.
Hints
Hint 1
The core bottleneck is 'give me everything due in the next N seconds' — design your index to make that query fast and horizontally scalable.
Hint 2
Partition your timeline into buckets and shards to avoid a single hot spot when thousands of tasks share the same minute.
Hint 3
Use deterministic identifiers for execution attempts so you can recognize and skip duplicate fires after a crash.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Task Scheduler Design
This problem evaluates whether you can partition a time-series workload, reason about consistency under failure, and articulate trade-offs with concrete numbers. Strong candidates spend most of their time on the trigger subsystem and deduplication logic, not CRUD boilerplate.
Step 1: Establish Scale and Constraints
Always anchor your design with numbers.
- Active tasks: ~50–100M, each ~1 KB metadata → 50–100 GB. Too large for a single-node index.
- Trigger throughput: 10k/s average, 20k/s peak. Peaks align with round timestamps (
:00,:30) because cron jobs cluster there. - Latency goal: p99 < 2 seconds from scheduled time to dispatch.
- Execution logs: ~10k/s × 86,400 s/day = 864M events/day at ~200 B each → ~170 GB/day. Retain for 30 days with TTL.
- Delivery semantics: at-least-once. Tasks are opaque payloads sent to external endpoints; downstream systems must handle idempotency.
- Time resolution: 1-second granularity is sufficient.
Step 2: API Design
POST /tasks
Body: {name, schedule: {type: "once"|"cron", fire_at?, cron_expr?, tz},
target: {url|queue|function}, payload, retry: {max, backoff},
idempotency_key}
Returns: {task_id}
PATCH /tasks/{id}
Body: {schedule?, payload?, ...}, if_version: <int>
Returns: 200 | 409 Conflict
DELETE /tasks/{id} → 202 (marks CANCELLED)
GET /tasks/{id} → full task + computed next_fire_at
GET /tasks/{id}/history?start=&end=
Key details:
idempotency_keyprevents duplicate task creation from client retries.if_versionenables optimistic concurrency; a racing update and trigger won't silently clobber each other.
Step 3: Data Model
Use a distributed store like Cassandra or DynamoDB. Three tables:
tasks (key: task_id)
task_id, owner, schedule_type, cron_expr, tz, target, payload,
retry_config, status, next_fire_at, version
fire_index (the critical piece)
- Partition key:
(shard_id, time_bucket)whereshard_id = hash(task_id) % 1024andtime_bucket = truncate(next_fire_at, 1min). - Sort key:
(next_fire_at, task_id). - This structure turns "what's ready now?" into small range scans across many partitions instead of one giant global sort. Sharding prevents any single popular minute from becoming a hotspot.
attempts (key: attempt_id, TTL 30d)
attempt_id = deterministic_hash(task_id, scheduled_ts),
status: PENDING|RUNNING|DONE|FAILED,
try_number, worker_id, lease_until, fence_token
The deterministic attempt_id is the foundation of deduplication.
Step 4: Architecture Overview
Clients
↓
API Layer (stateless)
↓
Task DB + Fire Index
↓
Coordinator (etcd/Consul: shard leases + fencing tokens)
↓
Trigger Nodes (each owns subset of 1024 shards)
- poll fire_index for [now, now+60s]
- hold tasks in memory (min-heap or timing wheel)
- when due: record attempt, publish to queue
↓
Message Queue (Kafka/SQS, partitioned by task_id)
↓
Worker Pool (pull model)
- execute → callback target
- update attempt status
↓
Reconciler (background sweep for stale/stuck attempts)
Step 5: The Trigger Path (Core Logic)
Shard Ownership
- Trigger nodes acquire leases on subsets of the 1024 shards via etcd. Each lease has a monotonically increasing epoch used as a fencing token.
- When a node crashes, its lease expires (~10s TTL) and another node claims those shards. Adding nodes redistributes shards automatically.
Pre-Loading
- Every 10–15 seconds, each node queries its owned shards for tasks with
next_fire_atin[now, now+60s]. - It loads them into an in-memory min-heap or hierarchical timing wheel for O(1) insertion and constant-time firing.
Firing a Task
When a task reaches its scheduled moment:
- Write attempt record: conditionally insert
attempts(attempt_id)withstatus=PENDING. If the row exists, abort (already fired). - Enqueue message: publish
{attempt_id, task_id, payload}to the dispatch queue. - Advance recurrence (cron only): compute the next
next_fire_at, updatefire_indexwith a conditional write checkingversionandepoch. The epoch check fences out zombie writers from expired leases.
Crash Recovery
- If a node dies between steps 2 and 3, the new lease-holder re-reads the stale index entry and tries to fire again. The deterministic
attempt_idcauses step 1 to fail, deduplicating the fire. - If a node dies between steps 1 and 2, a reconciler process sweeps for
PENDINGattempts older than ~60s and re-enqueues them.
Throughput Check
20k fires/s across 20 trigger nodes = 1k/s per node. Each fire is 2–3 conditional writes, well within DB capacity.
Step 6: Worker Execution and Retries
- Pull model: workers pull from the queue (SQS visibility timeout or Kafka consumer groups). Natural load balancing.
- Lease-based safety: on pickup, worker sets
status=RUNNING,lease_until=now+5min, and heartbeats. If the worker crashes, the lease expires and the message reappears (via visibility timeout or reconciler). Attempt increments; exponential backoff applies. - Fencing: the
fence_token(epoch + attempt number) rejects stale writes from zombie workers. - Dead-letter queue: after max retries, route to DLQ and alert.
Handling Duplicates
At-least-once means duplicates are inevitable. Mitigation:
- Deterministic
attempt_iddedups scheduler-side double-fires. - Conditional state transitions ensure only one worker moves
PENDING→RUNNING. - Pass
attempt_idto the target as an idempotency token. True exactly-once semantics require cooperation from the downstream system.
Step 7: Trade-Offs and Alternatives
| Choice | Pro | Con |
|---|---|---|
| DB polling + in-memory wheel | Durable, proven at scale | Higher poll latency (~10s cycle) |
Redis sorted set (ZRANGEBYSCORE) | Sub-second latency, simpler | Memory cost at 100M tasks; durability concerns |
| Smaller time buckets (10s vs 1min) | Tighter scan bounds | More partitions to poll |
| Shorter lease TTL (5s vs 10s) | Faster failover | More churn, more duplicate fires |
A common hybrid: DB as source of truth, Redis for the next hour's window.
Step 8: Common Extensions
- Concurrency control: offer
ALLOW|FORBID|REPLACEpolicies when a task's execution overlaps its next scheduled run (like Kubernetes CronJobs). - Priority tiers: partition the queue; high-priority workers pull from a dedicated topic.
- Multi-region: replicate task metadata; use consensus (Raft) for lease coordination; fire from the region closest to the target.
- Observability: emit metrics on trigger delay distribution, attempt retry rates, DLQ depth.
What Makes This Answer Strong
- Quantified scale before drawing boxes.
- Sharded time index — recognized that a global sort doesn't scale.
- Deterministic attempt IDs — the key insight for crash deduplication.
- Fencing tokens — prevents split-brain and zombie writes.
- Explicit handling of at-least-once — didn't hand-wave duplicates or claim false exactly-once.
- Concrete trade-offs with numbers, not vague "it depends."
Weak answers describe CRUD APIs in detail but gloss over "how do you find what's due now at 20k/s?" or say "just poll the DB every second for everything" (doesn't partition). Strong answers center the trigger path and reason precisely about failure modes.