Build a Scalable Task Execution System
System DesignModel answerLast updated
Design a fault-tolerant background task scheduler supporting one-time and recurring jobs with at-least-once guarantees at scale.
You're building a background task execution platform that lets clients schedule work to run at specific times or on repeating schedules.
Requirements
Your system must handle:
Task Types:
- Tasks that run once at a given timestamp
- Tasks that repeat on a schedule (similar to cron expressions like "daily at 3 AM" or "every Monday")
Core Functionality:
- Clients can submit new tasks, cancel existing ones, and query execution history
- Every task must execute at least once (duplicate runs are acceptable if they're idempotent)
- Support task priorities—higher priority work should be picked up first when multiple tasks are ready
- Recover gracefully when execution nodes fail mid-task
Scale & Availability:
- Handle around 100,000 task executions per minute
- Keep submission and query latency under 100ms
- Eliminate single points of failure
What to provide
- Architecture overview: main components and how they communicate
- Data model: schemas for storing task definitions and execution records
- Scheduling mechanism: how tasks become ready and get dispatched to workers
- Failure handling: strategies for retries, dead-letter processing, and preventing lost work
Focus on the distributed systems aspects—assume task handlers are pre-registered functions identified by name.
Hints
Hint 1
Separate the task definition from individual execution attempts—they have different lifecycles and access patterns
Hint 2
Use database-level concurrency primitives like SELECT FOR UPDATE SKIP LOCKED or optimistic locking to safely claim ready tasks
Hint 3
A timing wheel or sorted set can reduce polling load, but keep the database as the source of truth for durability
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarify Scale and Semantics
Capacity: 100K executions/minute averages to ~1,700/second, but cron tasks cluster at minute and hour boundaries. Design for 10–20× burst capacity, meaning 20–30K dispatches/second for short windows.
Storage: Assume 50 million active task definitions and ~144 million execution records per day. At ~300 bytes each, that's 45 GB daily; archive or TTL execution history after 30 days.
Semantics:
- At-least-once delivery means handlers must be idempotent
- Priority ordering applies only among tasks already due; it doesn't let tasks run early
- Out of scope: the execution runtime itself—we assume workers invoke registered handlers by name with a JSON payload
API Design
POST /tasks
Body: {handler, payload, priority, schedule: {run_at | cron_expr, timezone},
max_retries, timeout_sec, idempotency_key}
→ {task_id}
GET /tasks/{task_id}
→ definition, next_run_time, recent execution history
DELETE /tasks/{task_id}
→ soft-deletes and cancels pending runs
The idempotency key prevents duplicate task creation when clients retry submissions.
Data Model
Split task definitions from individual execution attempts—they evolve independently and have different query patterns.
tasks table (sharded by task_id)
| Column | Notes |
|---|---|
| task_id (PK) | UUID |
| owner_id | Indexed for "list my tasks" |
| handler, payload | What to execute |
| schedule_type | ONE_TIME or RECURRING |
| run_at / cron_expr, timezone | When to fire |
| priority | 0=high, 1=normal, 2=low |
| max_retries, timeout_sec | |
| state | ACTIVE / PAUSED / DELETED |
| version | Optimistic lock for updates |
executions table (partitioned by shard_id)
| Column | Notes |
|---|---|
| execution_id (PK) | |
| task_id, scheduled_at | UNIQUE constraint prevents duplicate fires |
| shard_id, priority | Hash-based partitioning |
| status | PENDING → CLAIMED → RUNNING → DONE/FAILED/DEAD |
| attempt | Incremented on retries; acts as fencing token |
| lease_owner, lease_expires_at | For heartbeat-based leases |
| started_at, finished_at, error_msg |
Hot index: (shard_id, status, scheduled_at, priority) for efficient claiming queries.
Use a distributed SQL database (sharded Postgres, CockroachDB, Spanner) for transactional conditional updates. Pure KV stores require rebuilding locking and consistency yourself.
State transitions:
- PENDING → CLAIMED when a dispatcher selects it
- CLAIMED → RUNNING when a worker acknowledges and starts work
- RUNNING → DONE (success), FAILED (retriable error), or DEAD (exhausted retries)
Every transition is conditional (WHERE status = X AND attempt = Y) to prevent lost updates.
Architecture
Clients → API Layer (stateless) → Task DB
↑
Dispatcher Fleet ---------+ (each owns shards via lease)
↓
Priority Queues (Kafka/SQS: high, normal, low)
↓
Worker Fleet ----results--→ Execution DB
↑
Lease Monitor (reaper)
Flow:
- API service creates the task and its first PENDING execution in one transaction
- Dispatchers scan their assigned shards for due executions and push them to priority queues
- Workers pull from queues, execute handlers, heartbeat during work, and write results
- A reaper process finds expired leases and re-enqueues stalled executions
All components scale horizontally. Shard ownership is coordinated via etcd/ZooKeeper leases.
Scheduling Mechanism (Deep Dive)
Shard assignment: Partition executions into N logical shards (e.g., 1024). Each dispatcher acquires a subset of shard leases from etcd. When a dispatcher crashes, its leases expire and others take over—eliminating coordinator bottlenecks.
Claiming ready tasks: Every ~500ms per shard, run:
UPDATE executions SET status='CLAIMED', lease_owner=:dispatcher_id,
lease_expires_at = now() + 60s, attempt = attempt + 1
WHERE execution_id IN (
SELECT execution_id FROM executions
WHERE shard_id = :shard AND status='PENDING' AND scheduled_at <= now()
ORDER BY priority, scheduled_at
LIMIT 500
FOR UPDATE SKIP LOCKED
)
RETURNING *;
SKIP LOCKED prevents two dispatchers from claiming the same row during brief overlap after failover. On systems without row locks, use optimistic locking with a version column.
Recurring tasks: In the same transaction, insert the next execution with scheduled_at = compute_next_cron_time(...). The unique constraint on (task_id, scheduled_at) makes this idempotent. Computing only one occurrence ahead keeps table size bounded.
Why database + queue instead of queue-only? Most message queues handle arbitrary future delays poorly (SQS caps at 15 minutes). The database is the durable, queryable source of truth; queues provide buffering and priority fan-out.
Optimization: Maintain a timing wheel or Redis sorted set caching the next few minutes of executions. It reduces dispatch latency, and because the DB remains authoritative, cache loss is harmless.
Priority handling: Use separate queue topics per priority level. Workers consume with weighted ratios (e.g., 70% high, 20% normal, 10% low) to avoid starvation.
Failure Handling and Retries
Lease-based execution:
- Worker transitions execution to RUNNING with conditional update checking
attempt - While running, worker extends
lease_expires_ateverytimeout/3via heartbeat - If worker crashes, heartbeats stop
Reaper process: Scans every few seconds for status IN ('CLAIMED','RUNNING') AND lease_expires_at < now(). For each expired lease:
- Increment
attempt - If attempts < max_retries: reset to PENDING with exponential backoff on
scheduled_at - Otherwise: mark DEAD, publish to dead-letter queue, alert
Fencing tokens: The attempt column acts as a fencing token. Workers include it in their result write: UPDATE ... WHERE execution_id = ? AND attempt = ?. A slow worker that lost its lease cannot overwrite a newer attempt's result.
Idempotency: Because at-least-once semantics allow duplicates, handlers must be idempotent. The unique constraint on (task_id, scheduled_at) prevents the system from creating duplicate executions for the same fire time.
Common Mistakes
- Single poller/dispatcher: Becomes a bottleneck and single point of failure. Use shard-based partitioning.
- Queue as source of truth: Loses queryability and makes debugging hard. Database should own state.
- Missing fencing: Without attempt tokens, a zombie worker can corrupt results after its lease expires.
- No backoff on retries: Transient errors (downstream service down) cause thundering herd. Use exponential backoff.
- Unbounded execution history: Grows indefinitely. Archive or TTL old records.
Complexity and Trade-offs
Throughput: Each dispatcher shard handles ~20–30 claims/sec in bursts. With 10 dispatchers × 100 shards each, capacity is 20–30K/sec.
Latency: Dispatch skew (scheduled time vs. actual start) is poll_interval/2 on average, around 250ms at p50 and 1–2 seconds at p99 with 500ms polling.
Consistency: Strong consistency for claiming via database transactions. Exactly-once semantics would require distributed transactions into the handler's side effects—expensive and often impossible. At-least-once with idempotent handlers is the pragmatic choice.
Alternative: For simpler cases (<1K tasks/sec, single datacenter), a centralized timing wheel in Redis with Lua scripts can replace the dispatcher fleet. Beyond that scale, you need sharding and the architecture above.