Design a 100x Scalable Distributed Task Scheduler
System DesignModel answerLast updated
Architect a flexible background job system capable of scaling 100-fold using partitioned time indices, hierarchical timing wheels, and resilient worker leasing.
Problem Context
An online platform relies heavily on background processing to support key features such as digest emails, reverse-geocoding coordinates, boundary calculations, and push notifications. The current system relies on a central relational database to manage and dispatch these background jobs.
As global activity scales, the system needs to support a 100-fold increase in job volume without requiring a complete design teardown. You need to design an architecture that satisfies immediate needs while presenting a clear migration strategy to handle the target scale.
Requirements
Functional Requirements
- Task Submission: Support one-time delayed tasks and recurring (cron-style) schedules with custom parameters and desired execution times.
- State & Control: Expose APIs to fetch job statuses, view execution logs, and cancel pending tasks.
- Delivery & Retries: Guarantee at-least-once task execution, configurable exponential backoff retry policies, and priority handling (e.g., real-time notifications over batch reports).
Scale & Non-Functional Requirements
- Initial Load: ~500 task submissions per minute (~8.3 QPS), with peak execution of 1,000 tasks per minute (~16.7 QPS). Active pending tasks stored: ~1 million.
- Target Scale (100x): ~50,000 task submissions per minute (~833 QPS average, 2,500 QPS peak), with peak execution reaching 100,000 tasks per minute (~1,666 QPS execution rate). Active pending tasks stored: ~100 million.
- Execution Timeliness: Tasks should trigger within a 1 to 5-second window of their target timestamp.
- Fault Tolerance: High availability with no single point of failure; crashes of workers or schedulers must not result in dropped tasks.
Discussion Points
- API Contracts: Interface definition for job registration, status checking, and cancellation.
- Storage Architecture: Data model and storage engine selections for baseline load versus target scale.
- Dispatch & Scheduling: Mechanism for triggering due tasks accurately (e.g., polling, timing wheels, range partitioning).
- Execution & Idempotency: Worker lease management, heartbeat mechanisms, handling late-arriving or crashed workers, and preventing execution duplication.
- Scaling Strategy: Detailed evolution path from baseline relational storage to a distributed 100x architecture.
Hints
Hint 1
Decouple the time index (finding work that is due) from the durable source of truth (job definitions) and the queue (workers execution line).
Hint 2
Avoid materializing infinite recurring cron instances into database rows; materialize only the immediate next run.
Hint 3
Use optimistic concurrency (fencing tokens/versioning) and heartbeat leases to prevent zombie workers from corrupting state.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Designing a Scalable Background Job Scheduler
1. Requirement & Scale Analysis
Scale Matrix
| Metric | Initial Phase | 100x Expansion |
|---|---|---|
| Submission Rate | 500 / min (~8.3 QPS) | 50,000 / min (~833 QPS avg, 2,500 QPS peak) |
| Execution Rate | 1,000 / min (~16.7 QPS) | ~100,000 / min (~1,666 QPS peak) |
| Active Pending Tasks | 1 Million | 100 Million |
| Primary Storage Size | ~1 GB (assuming 1 KB per record) | ~100 GB active + historical logs |
Key Clarifications & SLA Constraints
- Execution Latency: Triggering within 1–5 seconds of the scheduled time.
- Delivery Guarantee: At-least-once execution. Task handlers must be designed to be idempotent.
- Payload Handling: Large payload data is uploaded to object storage (e.g., AWS S3). The job payload only retains metadata references.
- Cron Strategy: Only the next single run instance of a cron job is materialized. This keeps the active record size capped at 100M rows even for indefinitely recurring jobs.
2. API Design
Endpoint Definitions
POST /v1/jobs
Content-Type: application/json
{
"job_type": "SEND_PUSH_NOTIFICATION",
"payload_uri": "s3://payloads/2026/03/req-9912.json",
"scheduled_at": 1774000000,
"cron_expression": null,
"priority": "HIGH",
"retry_policy": {
"max_attempts": 5,
"initial_interval_sec": 5,
"backoff_multiplier": 2.0
},
"idempotency_key": "evt_notification_user_44921"
}
Response: 201 Created with { "job_id": "job_9982401" }
GET /v1/jobs/{job_id}
Response: 200 OK
{
"job_id": "job_9982401",
"state": "ENQUEUED",
"scheduled_at": 1774000000,
"current_attempt": 0,
"updated_at": 1773999950
}
DELETE /v1/jobs/{job_id}
Response: 200 OK (cancels future execution if state is SCHEDULED or RETRY_WAIT).
GET /v1/jobs/{job_id}/history?cursor=eyJpZCI6MTB9&limit=20
Response: Paginated list of historical execution attempts, timings, and error stack traces.
3. Data Model & Storage Strategy
To handle both initial operations and 100x growth without redesigning system logic, decouple data into three separate concerns:
- Job Store (Source of Truth): Full job metadata and current state.
- Time Index: Optimized lookup layer to identify tasks due for execution.
- Execution Queues: Active buffer for ready-to-run tasks consumed by execution workers.
Schema: Primary Job Entity (jobs)
| Column Name | Type | Notes |
|---|---|---|
job_id | UUID / String | Primary key |
idempotency_key | String | Unique constraint to prevent duplicate submissions |
job_type | String | Route selector for worker pools |
payload_ref | String | URI pointer to object storage or direct payload |
cron_expr | String | Cron pattern if recurring; otherwise NULL |
scheduled_at | Timestamp | Intended execution time |
state | Enum | SCHEDULED, ENQUEUED, RUNNING, SUCCEEDED, FAILED, RETRY_WAIT, CANCELED |
priority | Int | 0 = Immediate/High, 10 = Low/Batch |
attempt | Int | Incremented on execution |
max_attempts | Int | Maximum retry count |
lease_owner | String | Worker identity currently executing the job |
lease_expires_at | Timestamp | Lock expiry timestamp for failure detection |
version | BigInt | Fencing token / optimistic locking key |
Schema: Execution Logs (job_executions)
Stored separately from active state (e.g., time-series data store or log aggregator).
- Columns:
job_id,attempt_number,worker_id,started_at,completed_at,status,error_message.
4. Architectural Evolution: Baseline to 100x Scale
+-----------------------------------------------------------------------------+
| BASELINE STAGE |
| |
| [Clients] ---> [API Service] ---> [PostgreSQL DB] |
| | |
| (FOR UPDATE SKIP LOCKED) |
| v |
| [Scheduler Replicas] |
| | |
| v |
| [Worker Nodes] |
+-----------------------------------------------------------------------------+
|
| Migrate to 100x Scale
v
+-----------------------------------------------------------------------------+
| TARGET STAGE (100x) |
| |
| [Clients] ---> [API Svc] ----------> [Job Store: Sharded KV / NoSQL] |
| \ |
| -------> [Time Index: Partitioned KV / Redis] |
| | |
| (Shard Leases) |
| v |
| [Scheduler Nodes] |
| (Timing Wheel Engine) |
| | |
| v |
| [Message Queues: SQS/Kafka] |
| | |
| v |
| [Worker Node Pools] |
+-----------------------------------------------------------------------------+
Baseline Architecture (Initial Scale)
- Database: Single PostgreSQL database instance.
- Dispatch Logic: Multiple scheduler instances poll the relational table using row-level locking:
SELECT job_id FROM jobs WHERE state = 'SCHEDULED' AND scheduled_at <= NOW() ORDER BY priority ASC, scheduled_at ASC LIMIT 100 FOR UPDATE SKIP LOCKED; - Execution: Schedulers update task states to
ENQUEUEDinside the transaction and push the job IDs to a central message queue (e.g., RabbitMQ).
Bottlenecks at 100x Scale
- Index Contention & Table Bloat: A 100-million row relational database table handling thousands of status updates per second experiences heavy B-tree index maintenance, page locks, and VACUUM overhead.
- Polling Overhead: Multiple schedulers executing
SKIP LOCKEDqueries across millions of rows suffer from query latency spikes and high DB CPU usage. - Queue Head-of-Line Blocking: Mixing delay calculations with actual worker delivery prevents priority-based scaling.
Target Architecture (100x Scale)
1. Partitioned Time Index
Create time buckets for fast range queries:
- Partition Bucket:
bucket = floor(scheduled_at / 60)(1-minute slices). - Logical Shard:
shard = hash(job_id) % N(e.g., $N = 1024$). - Store time indices in distributed NoSQL (e.g., Cassandra / DynamoDB) or distributed Redis Sorted Sets (
ZADDwith score =scheduled_at).
2. Sharded Schedulers & In-Memory Timing Wheels
- Leader Election: Use etcd or ZooKeeper to distribute the 1,024 shards across scheduler nodes.
- Prefetching: Every 60 seconds, scheduler nodes load the upcoming time-bucket entries assigned to their shards into local Hierarchical Timing Wheels (1-second tick accuracy).
- Execution Dispatch: On each tick, the timing wheel pops ready task IDs, atomically marks their state in the Job Store, and publishes them to execution queues.
3. Decoupled Execution Queues
- Push ready jobs into distinct message broker queues (e.g., AWS SQS or Apache Kafka topics) segmented by priority (
high-priority,default,batch). - Dedicated worker pools consume from matching priority topics, ensuring high-priority tasks trigger instantly without being starved by batch background digests.
5. Reliability, Leases, and Failover
Worker Lifecycle & Fencing:
[Worker A] -- (1) CAS acquire lease (version=1, owner=Worker A, exp=T+30s) --> [Job Store]
|
|---- (2) Long GC Pause / Delayed Network (>30s)... (Lease Expires)
|
[Reaper Engine] -- (3) Reset expired job (version=2) --> [Job Store]
|
[Worker B] <-- (4) Re-enqueued & claimed (version=3) --+
[Worker A] -- (5) Completes job, attempts write (version=1) --> [Job Store]
*** REJECTED: Version 1 < Current Version 3 *** (Fencing prevents double write)
Worker Lease Management & Fencing Tokens
- Claim Task: When a worker picks up a task from the queue, it issues a Compare-And-Swap (CAS) update to the Job Store:
UPDATE jobs SET state = 'RUNNING', lease_owner = 'worker_node_42', lease_expires_at = NOW() + INTERVAL '30 seconds', version = version + 1 WHERE job_id = 'job_9982401' AND version = 1; - Heartbeats: For long-running tasks, workers periodically extend their lease (
lease_expires_at) whileversionremains constant for the active claim cycle. - Fencing Protection: If a worker crashes or experiences a long GC pause, its lease expires. A background Reaper Service scans for expired running tasks and resets them to
RETRY_WAITwhile incrementingversion. If the original worker finishes late and attempts to record its result, the CAS write fails due to aversionmismatch.
Failure Recovery Scenarios
- Scheduler Node Crash: The etcd cluster detects the heart-beat loss and reassigns the scheduler’s timing-wheel shards to surviving scheduler nodes. The new nodes load the current bucket from the durable Time Index.
- Duplicate Executions: The system guarantees at-least-once execution. Downstream job logic must implement idempotency (e.g., using database unique constraints or idempotency keys).
6. Migration Blueprint (Zero Downtime)
Migration Flow:
Phase 1: Dual Writes
API ---> Postgres (Primary)
---> Sharded NoSQL / Time Index (Shadow)
Phase 2: Shard-by-Shard Cutover
API ---> Sharded NoSQL / Time Index (Primary)
|-- (Read by New Schedulers for Shards 0..X)
Postgres -- (Read by Old Schedulers for Remaining Shards)
Phase 3: Full Cutover & Archive
API ---> Sharded NoSQL / Time Index
Postgres DB ---> Decommissioned / Retained for Long-Term Auditing
- Dual-Write Phase: Modify the API layer to write incoming tasks to both the original relational database and the new Partitioned Job Store/Time Index.
- Incremental Shard Migration: Assign a percentage of logical shards to the new scheduler timing-wheel infrastructure. Monitor dispatch timeliness and error rates.
- Data Backfill: Run a backfill job to copy pre-existing scheduled jobs from the relational table into the new distributed time index.
- Final Cutover: Shift 100% of traffic to the new system and transition the legacy database into an archive store for historical logging.