Build a Task Scheduler That Grows from Startup to 100x Scale
System DesignModel answerLast updated
Design a job scheduling system supporting one-time and recurring tasks, retries, and observability, then evolve it to handle 100x traffic growth.
You're building a task scheduling platform that lets users and services schedule work to run at specific times or on recurring intervals.
Your system must support:
- One-time tasks (fire once at a specific timestamp) and recurring tasks (cron-style expressions with timezone support)
- Execution guarantees: tasks should fire within a few seconds of their scheduled time and persist durably once accepted
- Retry logic for tasks that fail, with configurable backoff policies
- Cancellation and modification of scheduled tasks before they run
- State tracking through the task lifecycle: waiting, dispatched, executing, completed, failed
- Operational visibility so engineers can monitor execution health and debug failures
Your challenge has two phases:
Phase 1: Design the initial architecture for a small company handling roughly 1 million scheduled tasks with about 50 executions per second on average, spiking to 500/second at peak times (think top-of-the-hour cron clustering).
Phase 2: Explain how you would evolve this design to support 100x growth: 100 million tasks, 5,000 executions/second average, 50,000/second peak.
Address these dimensions:
- API surface and core entities
- Data schema and how you model task definitions versus individual firings
- Execution mechanism: how tasks get picked up and run safely
- Correctness concerns: preventing duplicate runs, handling retries, achieving idempotency
- Fault tolerance: what happens when scheduler nodes, workers, or the database fail
- Observability: what metrics and logs operators need
- The migration path from phase 1 to phase 2, including which bottlenecks emerge and how you address them
Be concrete about technology choices, query patterns, and the trade-offs you're making at each scale tier.
Hints
Hint 1
Separate the task definition from each individual execution—they have different lifecycles and access patterns
Hint 2
Use database-level primitives like SELECT FOR UPDATE SKIP LOCKED to claim work without contention in the initial design
Hint 3
Consider how at-least-once delivery differs from exactly-once, and where idempotency keys fit into your execution model
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Task Scheduler Design
Clarifying Scope and Constraints
Start by nailing down what "scheduling" means here and what guarantees we can realistically provide.
Functional scope:
- One-time tasks fire at a specific UTC timestamp; recurring tasks use cron syntax with timezone awareness
- Task payload is either an HTTP webhook or a message identifier pointing to handler logic
- Support backoff-based retries, manual cancellation, schedule updates, and execution history
- Expose task status and recent execution attempts through the API
Delivery semantics: At-least-once execution is the target. Exactly-once is impossible end-to-end because we can't control whether a webhook receiver processes a request twice if our confirmation is lost. State this assumption early.
Timing precision: Tasks fire within 1–5 seconds of schedule. Sub-second precision requires specialized infrastructure and isn't the goal here.
Scale checkpoints:
| Metric | Phase 1 (startup) | Phase 2 (100x) |
|---|---|---|
| Total scheduled tasks | ~1M | ~100M |
| Avg execution rate | 50/sec | 5,000/sec |
| Peak execution rate | 500/sec | 50,000/sec |
| Daily execution records | ~5M | ~500M |
The peak matters more than average. Cron users cluster jobs at hour boundaries (0 * * * *), creating thundering-herd scenarios.
API Design
POST /tasks
Body: {name, payload, target_url, schedule: {run_at | cron, timezone},
retry_config: {max_attempts, base_backoff_ms}, idempotency_key}
Returns: {task_id, next_fire_time}
GET /tasks/{id}
Returns: task details + recent 10 execution attempts
PATCH /tasks/{id}
Body: {schedule} or {status: "paused"}
Updates the schedule or pauses future fires
DELETE /tasks/{id}
Cancels and removes the task
GET /tasks/{id}/history?status=failed&limit=50
Returns paginated execution records
POST /history/{execution_id}/retry
Operator endpoint to manually retry a failed execution
The idempotency_key on task creation prevents accidental duplicates when clients retry the POST request.
Data Model
The critical design decision: separate the task definition from each execution event.
Tasks table (definitions):
tasks(
task_id UUID PRIMARY KEY,
owner_id,
name,
payload JSONB,
target_url,
cron_expr,
timezone,
retry_config JSONB,
status ENUM('active','paused','deleted'),
next_fire_time TIMESTAMPTZ,
version INT, -- optimistic locking
created_at TIMESTAMPTZ
)
INDEX on (status, next_fire_time) for due-task queries
Executions table (individual firings):
executions(
execution_id UUID PRIMARY KEY,
task_id UUID REFERENCES tasks,
fire_time TIMESTAMPTZ, -- when this execution was scheduled to run
state ENUM('pending','running','succeeded','failed','cancelled'),
attempt_number INT,
owner_worker_id,
lease_expiry TIMESTAMPTZ,
fence_token BIGINT, -- incremented on each claim
error_message TEXT,
started_at TIMESTAMPTZ,
completed_at TIMESTAMPTZ,
UNIQUE(task_id, fire_time) -- only one execution per scheduled time
)
INDEX on (state, fire_time) for "what's due now" queries
INDEX on (task_id, fire_time DESC) for history views
The UNIQUE(task_id, fire_time) constraint prevents double-scheduling the same firing.
State flow: pending → running → succeeded|failed, with failed → pending on retry.
Phase 1: Postgres-Centric Architecture
Components:
- API service (stateless, multiple replicas) handling HTTP requests
- Scheduler workers (stateless, 3–5 replicas) that poll for due work and execute it
- PostgreSQL (primary + synchronous replica for HA)
How tasks fire:
When a task is created or completes, compute its next fire time using the cron library and insert a pending execution row atomically with updating tasks.next_fire_time.
Every second, scheduler workers run this query:
UPDATE executions
SET state = 'running',
owner_worker_id = $my_id,
lease_expiry = now() + interval '2 minutes',
fence_token = fence_token + 1,
attempt_number = attempt_number + 1,
started_at = now()
WHERE execution_id IN (
SELECT execution_id
FROM executions
WHERE state = 'pending' AND fire_time <= now()
ORDER BY fire_time
LIMIT 100
FOR UPDATE SKIP LOCKED
)
RETURNING *;
SKIP LOCKED is the key: multiple workers poll concurrently without blocking each other or double-claiming rows. Each worker claims up to 100 tasks, executes them (HTTP POST to target_url), then marks them succeeded or failed.
At 500 tasks/sec peak, a single Postgres primary handles this comfortably. This design is simple, transactional, and debuggable with plain SQL.
Safe Execution: Leases and Fencing
Lease-based ownership:
A worker "owns" an execution only until lease_expiry. If execution takes longer than 2 minutes, the worker heartbeats every 30 seconds to extend the lease.
Reaper process:
Every 10 seconds, a background thread finds running executions with expired leases and resets them to pending (or failed if attempt_number exceeds max_attempts).
Fencing tokens: A worker that pauses (long GC, network partition) may wake up after losing its lease. Every state update is conditional:
UPDATE executions
SET state = 'succeeded', completed_at = now()
WHERE execution_id = $id AND fence_token = $expected_token;
If zero rows update, the worker lost ownership and discards its result. Pass fence_token as X-Fence-Token to the target webhook so receivers can reject stale requests.
Resource isolation: Enforce per-task timeouts. Use separate thread pools or process sandboxing to prevent one bad task from starving others.
Handling Retries, Duplicates, and Idempotency
At-least-once means duplicates happen. A worker can complete the webhook and crash before recording success. The reaper will retry it.
Mitigation:
Send Idempotency-Key: {execution_id} with every webhook. This key is stable across retries of the same firing, so the receiver can deduplicate. This turns "at-least-once" into "effectively once."
Retry backoff:
On failure, requeue: fire_time = now() + min(cap, base * 2^attempt) + jitter. Jitter prevents synchronized storms. After exhausting retries, mark failed and alert operators via the dead-letter query endpoint.
Error classification: Timeouts and 5xx are retryable. 4xx validation errors are permanent—fail immediately.
Cancellation:
Update tasks.status = 'deleted' and remove any pending executions in a transaction guarded by tasks.version (optimistic lock). An already-running execution may complete; we can't recall an in-flight HTTP request.
Fault Tolerance
| Failure Scenario | System Behavior |
|---|---|
| Worker crashes during execution | Lease expires; reaper requeues it. Idempotency key prevents duplicate side effects. |
| Scheduler worker crashes | Stateless—other replicas keep polling. No leader election needed. |
| Database primary fails | Fail over to synchronous replica. Brief scheduling pause (seconds), then catch up. |
| Multi-hour outage | Apply per-task misfire policy: run once now (default), run all missed, or skip. |
| Clock skew | Always use database now() as the single time source, not worker local clocks. |
Observability
Metrics (exposed via Prometheus):
- Executions per second by state (
succeeded,failed,retrying) - P50, P99 latency from scheduled time to actual start
- Retry rate and dead-letter queue depth
- Lease expiry events (worker health signal)
- Per-task-type execution counts for noisy-neighbor detection
Logs:
Structured JSON logs per execution with task_id, execution_id, attempt_number, duration_ms, status_code, error.
Alerting:
- Dead-letter queue depth > threshold
- Lease expiry rate spike (worker overload or crashes)
- Execution lag P99 > 10 seconds
Phase 2: Scaling to 100x (50k/sec Peak)
Bottlenecks that emerge:
- Single Postgres primary can't sustain 50k small transactions/sec
- Hot index contention on
(state, fire_time) - Executions table grows to billions of rows; retention becomes expensive
- Cross-region latency for global users
Architectural evolution:
1. Separate Dispatch from Execution
Introduce a durable message queue (Kafka, AWS SQS) between schedulers and workers.
- Scheduler nodes poll Postgres for due tasks and publish messages to the queue, marking executions
dispatched. - Worker nodes consume from the queue, execute, and update Postgres with results.
- This decouples read load (finding due work) from write load (recording results) and lets each scale independently.
2. Shard the Database
Partition tasks and executions by task_id hash across 10–20 Postgres shards. Each shard handles 5M–10M tasks.
- Scheduler nodes are assigned shard ranges; each polls its assigned shards.
- Single-task operations (GET /tasks/{id}, update) route to one shard via consistent hashing.
- Cross-shard queries (list all tasks for a user) require scatter-gather or a secondary index in Elasticsearch.
3. Time-Based Bucketing
Partition the hot (state, fire_time) index by time buckets (e.g., hourly). Schedulers only scan the current and next bucket, ignoring old data.
Create child tables:
executions_pending_2026_11_06_14
executions_pending_2026_11_06_15
...
A cron job creates buckets ahead of time. This dramatically reduces index size and contention.
4. Separate Hot and Cold Storage
Archive completed executions older than 7 days to object storage (S3) as Parquet files, keeping only a summary row in Postgres. Operators query cold data through a data warehouse (BigQuery, Redshift) for historical analysis.
This keeps the hot execution table under 50M rows even at 500M daily executions.
5. Introduce a Coordination Layer
Use etcd or Consul for:
- Shard assignment to scheduler nodes with leader election per shard
- Distributed rate limiting (per-tenant caps)
- Configuration updates without restarts
6. Regional Deployment
Deploy scheduler + worker clusters in multiple AWS regions. Tasks are geo-pinned based on owner_id to minimize latency. Use Aurora Global Database or CockroachDB for multi-region Postgres with low replication lag.
Trade-Offs and Design Choices
Why Postgres in phase 1?
Transactional guarantees, SKIP LOCKED for lock-free claiming, and operational simplicity. Avoid premature complexity.
Why not a distributed scheduler like Temporal or Celery Beat? Those are great, but the question asks you to design it. Showing you understand the internals demonstrates deeper systems thinking.
Why at-least-once instead of exactly-once? Network failures make exactly-once impossible without distributed transactions (2PC) across the scheduler and every webhook receiver. At-least-once with idempotency keys is the pragmatic industry standard.
Why separate tasks and executions? Task definitions are long-lived metadata; executions are ephemeral events. Mixing them creates write contention and bloat. Separation enables independent retention policies and indexing strategies.
This design balances simplicity for early scale with clear evolution paths to handle growth, grounded in real-world constraints and operational realities.