Build a Large-Scale Job Scheduling System
System DesignModel answerLast updated
Design a fault-tolerant distributed system that executes millions of scheduled tasks with configurable timing, retry logic, and multi-tenant isolation.
You need to design a system that schedules and executes recurring tasks at scale. The system must handle millions of jobs with flexible timing configurations, survive component failures without losing scheduled work, and isolate workloads across multiple tenants.
Your design should address:
Core functionality:
- Jobs are defined with cron-style timing expressions and IANA time zones
- Support pause, resume, and manual triggering of individual jobs
- Handle dependencies between jobs
- Configurable retry behavior with exponential backoff
- Policies for missed executions (catch up, skip, or coalesce)
- Concurrency control when a previous run is still active
Scale and reliability:
- 10 million active jobs across thousands of tenants
- Peak burst of 100,000+ dispatches per second (top-of-hour clustering)
- 99.99% uptime with automatic failover
- Sub-2-second dispatch latency at p99
- At-least-once delivery with idempotency support for effectively-once semantics
Multi-tenancy:
- Quotas and rate limiting per tenant
- Authentication and authorization
- Audit trail of all configuration changes
Operational concerns:
- Worker registration and health monitoring
- Observability: metrics, structured logging, distributed tracing
- Graceful handling of clock skew, network partitions, and worker crashes
Describe your architecture, component responsibilities, data model, scheduling algorithm, consistency guarantees, and how you handle the most critical failure scenarios. Explain capacity planning considerations and how you would test correctness.
Hints
Hint 1
Think about how to partition the scheduling load horizontally while maintaining strong consistency guarantees for each partition
Hint 2
Time zone handling requires storing IANA identifiers and recalculating future fire times when daylight saving transitions occur
Hint 3
Use a transactional outbox pattern to ensure dispatch messages are never lost even if a scheduler crashes immediately after advancing the next fire time
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Start by establishing scale parameters, then design around the hardest constraints: burst traffic at the top of the hour, strong consistency for each job's state, and zero data loss during failover.
1. Requirements and Scale Analysis
Traffic profile:
- 10M jobs, median hourly frequency → ~2,800 sustained dispatches/second
- Top-of-hour clustering: if 20% use
0 * * * *, that's 2M jobs firing simultaneously → 100k/sec burst capacity needed - History accumulation: ~240M runs/day × 500 bytes = 120 GB/day, 3.6 TB for 30-day retention
Key insight: You cannot schedule 10 million timers in-memory on a single node. You need horizontal partitioning of the scheduling work, and you must recover cleanly when a partition owner fails.
2. Architecture Overview
┌─────────────┐
│ API Layer │ (auth, quotas, job CRUD)
└──────┬──────┘
│
┌──────▼──────────┐ ┌──────────────┐
│ Metadata Store │◄────────┤ Coordinator │ (etcd/Consul)
│ (Spanner/ │ │ shard leases │
│ CockroachDB) │ └──────────────┘
└────────┬────────┘
│
┌────▼────────────────┐
│ Scheduler Cluster │ (each node owns subset of 4096 shards)
│ - polls due jobs │
│ - timing wheels │
│ - txn: run + outbox │
└────────┬────────────┘
│
┌────────▼────────┐
│ Message Queue │ (Kafka, partitioned by tenant)
└────────┬────────┘
│
┌────────▼────────┐ ┌──────────────┐
│ Dispatchers │───────►│ Worker Pools │
│ (fair queuing, │ │ (register, │
│ rate limiting) │ │ heartbeat) │
└─────────────────┘ └──────────────┘
│
┌────────▼────────┐
│ Reaper Service │ (expired leases → retry or DLQ)
└─────────────────┘
3. Data Model
Store in a distributed SQL database with horizontal scalability:
jobs table (partitioned by tenant_id):
job_id, tenant_id, cron_expr, iana_tz, next_fire_utc, state (ACTIVE/PAUSED), versionshard_id(hash of job_id mod 4096)retry_config, misfire_policy, concurrency_policy, target_url, payload_blob- Index:
(shard_id, next_fire_utc) WHERE state = ACTIVEfor efficient scanning
job_runs (time-partitioned):
run_id, job_id, scheduled_fire_time, attempt, state (PENDING/DISPATCHED/RUNNING/SUCCESS/FAILED)worker_id, lease_expiry, fencing_token, result, created_at- Unique constraint:
(job_id, scheduled_fire_time)— this prevents duplicate runs
workers: worker_id, pool_name, last_heartbeat, capacity, capabilities
outbox: (outbox_id, run_id, tenant_id, created_at) — transactional bridge to Kafka
4. Core Scheduling Algorithm
Sharding and leadership:
- Hash each job to one of 4096 logical shards
- Scheduler nodes acquire leases on shards through etcd (3-second renewal, 10-second expiry)
- Each lease includes a monotonic fencing token to prevent split-brain writes
Per-node scheduling loop (for each owned shard):
- Every 10 seconds, query:
SELECT * FROM jobs WHERE shard_id = ? AND next_fire_utc < now() + 60s AND state = ACTIVE - Load results into a hierarchical timing wheel (1-second slots for 0–60s, coarser buckets beyond)
- On each tick (1 Hz), for every expired timer:
- Single atomic transaction:
INSERT INTO job_runs (run_id, job_id, scheduled_fire_time, state=PENDING)- Compute next fire time: parse cron in IANA timezone, convert to UTC
UPDATE jobs SET next_fire_utc = ? WHERE job_id = ? AND shard_owner_token = ?INSERT INTO outbox (run_id, tenant_id)
- On conflict (unique violation), skip — another scheduler beat us
- Single atomic transaction:
- Separate relay process reads outbox, publishes to Kafka, deletes outbox rows
Why a timing wheel? Insert and fire are O(1). A min-heap is O(log n) per operation, which becomes a bottleneck at hundreds of thousands of timers.
Recovery on failover: The timing wheel is ephemeral. When a node takes over a shard, it rebuilds the wheel from the database. Because next_fire_utc is the source of truth, no fires are lost.
5. Correctness Guarantees
Fencing against zombie schedulers: A scheduler that's paused (GC, network partition) may wake up and try to advance jobs. The fencing token in the WHERE clause causes its writes to fail. The new lease holder has a higher token.
Deduplication:
- Scheduler level:
UNIQUE(job_id, scheduled_fire_time)prevents two schedulers from creating duplicate runs - Worker level: CAS update
SET state=RUNNING, worker_id=? WHERE run_id=? AND state=DISPATCHED - Application level: pass
idempotency_key = <job_id>:<fire_time>to downstream services; they must deduplicate on this key
At-least-once to effectively-once: The system guarantees at-least-once delivery (Kafka can redeliver, workers can crash after side effects). Combine with idempotency keys for effectively-once outcomes. Make this contract explicit: callers must implement idempotent handlers.
6. Time Zone and DST Handling
- Store IANA identifiers (
America/New_York), never fixed offsets - When computing
next_fire_utc, evaluate cron in local time, then convert - Spring forward (02:30 doesn't exist): fire at 03:00, or skip per policy
- Fall back (01:30 occurs twice): fire once, on the first occurrence
- For interval jobs (
*/15), use UTC arithmetic to avoid double-fires - Distribute timezone database updates; recompute
next_fire_utcfor affected jobs
7. Misfire and Retry Policies
Misfire = a scheduled fire that's more than 60 seconds late. Three policies:
FIRE_ONCE_NOW(default): coalesce all missed fires into a single runFIRE_ALL: catch up on every missed fire, capped and rate-limitedSKIP: advance to the next future fire
Concurrency policy (when previous run still active):
ALLOW: start a new run anywayFORBID: skip this fireREPLACE: cancel the old run, start new
Retries:
- Workers heartbeat every 5 seconds, extending a 30-second
lease_expiry - Reaper scans for expired leases every 10 seconds
- Increment
attempt, apply exponential backoff:delay = min(max_delay, base * 2^attempt) - After max retries, move to dead-letter queue for manual inspection
8. Multi-Tenancy and Fairness
- Kafka topics partitioned by
tenant_idfor isolation - Dispatcher maintains per-tenant token buckets (quota enforcement)
- Fair queuing: round-robin across tenants with pending work, don't let one tenant monopolize workers
- API gateway applies authn/authz and rate limits before job CRUD
9. Failure Modes
| Failure | Impact | Mitigation |
|---|---|---|
| Scheduler crash | Orphaned shard | Lease expires, another node takes over and rescans |
| Worker crash mid-run | Run hangs | Reaper detects expired lease, retries with backoff |
| Database partition | Writes fail | Schedulers back off, alert fires; on recovery, catch up |
| Clock skew | Fires drift | NTP on all nodes; drift beyond threshold triggers alarm |
| Kafka lag | Dispatch delay | Scale consumer group; alert on lag > 10k |
| Top-of-hour spike | Queue saturation | Optional jitter spreads fires ±30s with tenant opt-in |
10. Capacity Planning and Testing
Capacity:
- Schedulers: 4096 shards / 16 nodes = 256 shards/node. Each node scans ~2.5k jobs/shard = 640k jobs per poll cycle. At 10-second poll intervals, easily under 1 CPU core.
- Kafka: 10 partitions at 10k msg/sec = 1k/sec/partition, well within limits
- Workers: if average run = 5 seconds, 10k runs/sec → 50k concurrent workers. Use autoscaling pools.
Testing:
- Unit: cron parsing, timezone math, backoff calculations
- Integration: single scheduler writes runs correctly; failover transfers shard cleanly
- Chaos: kill schedulers during dispatch, partition the database, inject clock skew, saturate Kafka
- Load: simulate 2M jobs firing at
:00, measure dispatch latency and worker queue depth
Complexity
- Time per fire: O(1) for timing wheel insert/pop, O(1) for hash lookup to shard
- Space: O(jobs in next 60 seconds per shard) in-memory; full job metadata in database
- Scalability: horizontal in every layer—schedulers, Kafka, workers
This design balances strong consistency where it matters (job metadata) with eventual consistency where acceptable (metrics, logs), and uses well-understood primitives (sharded leases, outbox pattern, timing wheels) to achieve both high availability and correctness at scale.