Design a Task Execution Platform with Timing Guarantees
System DesignModel answerLast updated
Build a distributed system to run scheduled and recurring tasks at scale with latency SLAs and full execution traceability.
Task Execution Platform Design
You are building a platform that executes user-submitted tasks either once at a specified time or repeatedly on a cron-like schedule. The platform must handle high throughput while guaranteeing that tasks begin running close to their scheduled time.
What the System Must Do
Core Capabilities:
- Accept one-time tasks with a target execution time
- Support recurring tasks using cron expressions (e.g., "every hour at :15")
- Route tasks to a pool of execution nodes that report outcomes
- Retry failed tasks with increasing delays between attempts
Performance and Reliability:
- Throughput: Process at least 10,000 task submissions per minute
- Timing SLA: Begin execution within 5 seconds of the scheduled moment for 99% of tasks
- Durability: Guarantee every task runs at least once, even if nodes fail mid-execution
- Traceability: Maintain a queryable history of every state change for compliance and troubleshooting
Additional Context:
- Execution nodes are ephemeral and may restart or terminate at any time
- Many recurring tasks fire at round clock times (top of the hour, start of the minute), creating bursty load
- Tasks may take seconds to hours to complete
What You Should Cover
- API contracts for submitting tasks and querying execution history
- Data schema for persisting task definitions, execution state, and audit trails
- Architecture showing how tasks move from scheduled to running, including:
- How the system identifies which tasks are ready to run
- How execution nodes claim work without collisions
- How the system detects and recovers from node failures
- SLA enforcement: How you measure and alert on timing violations
Explain your trade-offs and justify key choices.
Hints
Hint 1
Consider how you'll efficiently find tasks due in the next few seconds without scanning the entire database
Hint 2
Think about what happens when a worker crashes mid-execution—how do you prevent the task from being lost or running twice simultaneously?
Hint 3
Cron schedules create thundering-herd problems at round clock boundaries; address burst handling in your design
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Task Execution Platform: Model Answer
1. Scope and Capacity Planning
Begin by translating requirements into concrete numbers to guide architecture decisions.
Load profile:
- Average: 10,000 tasks/min ≈ 167 tasks/sec
- Burst: Cron jobs cluster at
:00boundaries. Expect 10–30× spikes, so plan for 2,000–5,000 tasks/sec peak ingestion - Daily volume: ~14M executions
- Audit events: Each execution produces 4–8 state transitions (pending → ready → executing → completed/failed/retrying). That's ~80M events/day, roughly 20–30 GB/day of logs before compression
SLA: "Within 5 seconds" means the gap between scheduled_time and actual_start_time must be ≤ 5s for 99% of executions. This is a dispatch latency requirement, not a completion deadline.
Semantics: At-least-once execution. Tasks must be idempotent, and we provide an execution ID that downstream systems can use for deduplication.
Out of scope: Cross-region active-active, task dependencies (DAGs), sub-second precision.
2. API Design
Task Management:
POST /tasks
{ name, payload_url, schedule: { type: "once", run_at: ISO8601 }
| { type: "cron", expression, timezone },
retry: { max_attempts, initial_backoff_ms, max_backoff_ms },
timeout_sec, sla_dispatch_sec, priority }
→ 201 { task_id }
GET /tasks/{task_id}
DELETE /tasks/{task_id} # stops future runs
POST /tasks/{task_id}/enable | /disable
GET /tasks/{task_id}/runs?start=&end=&status=
GET /runs/{run_id}/timeline # audit log: state transitions with timestamps
Internal Worker API:
POST /internal/claim → { run_id, lease_token, expires_at, payload_url }
POST /internal/runs/{id}/heartbeat { lease_token }
POST /internal/runs/{id}/finish { lease_token, outcome: "success"|"failure", details }
The lease_token acts as a fencing token to prevent stale workers from completing an execution that was reassigned.
3. Data Model
tasks (definitions; relatively static)
task_id, owner, schedule_type, cron_expr, tz, payload_url, retry_policy, timeout_sec, sla_dispatch_sec, enabled
runs (the hot operational table)
run_id, task_id, scheduled_for, time_bucket (scheduled_for truncated to minute), partition_key (hash mod 256), state, attempt, next_run_at, owner_node, lease_token, lease_expires, started_at, finished_at- Primary index:
(time_bucket, partition_key, scheduled_for)to enable efficient range scans for "tasks due soon in my partition" - State flow:
PENDING → READY → EXECUTING → COMPLETED | FAILED → (RETRY_PENDING → READY …) | EXHAUSTED
run_events (append-only audit log)
run_id, seq, timestamp, prev_state, new_state, node_id, attempt, note
Use a strongly consistent datastore for tasks and runs (PostgreSQL with partitioning, CockroachDB, or DynamoDB with conditional writes). Stream events to Kafka, then archive to object storage for compliance queries.
4. Architecture
Clients → API Gateway → Task Service → Tasks DB
Runs DB ← range scans
↑
Dispatcher Nodes (hold partition leases via etcd/Consul)
│ poll every second, publish due tasks
↓
Ready Queue (Kafka/SQS, partitioned by priority)
↓
Worker Fleet (autoscaled on queue depth) ← heartbeat/finish → Runs DB
↓ all state changes
Event Stream (Kafka) → Archive + Metrics + SLA Monitor
Reaper: recovers expired leases
Finding Tasks Ready to Run
The time-bucketed partition scan approach:
- Runs are partitioned by
(time_bucket, partition_key). Each bucket represents one minute. - Dispatcher nodes acquire leases on subsets of the 256 partitions (via etcd). If a dispatcher crashes, its leases expire and other nodes pick them up.
- Every second, each dispatcher scans its partitions:
SELECT * FROM runs WHERE time_bucket IN (current_minute, next_minute) AND partition_key IN my_partitions AND state = PENDING AND scheduled_for <= now + 10s - Matching rows are loaded into an in-memory min-heap keyed by
scheduled_for. When each timer fires, the dispatcher updates the row toREADY(conditional on still beingPENDING) and publishes to the ready queue. - The 10-second look-ahead window absorbs database read latency and ensures tasks enter the queue with time to spare under the 5s SLA.
Recurring tasks: When occurrence N is dispatched, the dispatcher atomically inserts occurrence N+1 (next cron fire time) in the same transaction. Only the immediate-next occurrence exists in the database, keeping storage bounded.
Claiming and Executing Without Duplicates
Workers pull messages from the ready queue. Because queues can duplicate (SQS visibility timeout, Kafka rebalance), the database is the source of truth. A worker claims with a compare-and-swap:
UPDATE runs
SET state = 'EXECUTING', owner_node = :worker_id,
lease_token = lease_token + 1, lease_expires = now() + :timeout, started_at = now()
WHERE run_id = :id AND state = 'READY'
RETURNING lease_token, payload_url;
- If zero rows updated, another worker claimed it; drop the message.
- Workers send periodic heartbeats to extend
lease_expires. - The reaper (a background process) queries
state = EXECUTING AND lease_expires < now(). It transitions expired runs back toREADY(incrementingattempt) and republishes them. - The
lease_tokenfences stale workers: if a zombie worker tries to finish an execution after its lease expired and the run was reassigned, the token won't match and the update is rejected.
This guarantees at-least-once execution with no concurrent duplicates.
Retries with Exponential Backoff
On failure (or lease expiration), compute:
next_delay = min(max_backoff, initial_backoff * 2^attempt) + random_jitter
next_run_at = now + next_delay
Set state = RETRY_PENDING, scheduled_for = next_run_at, and update time_bucket. The retry re-enters the normal dispatch path. After max_attempts, transition to EXHAUSTED and alert the task owner.
5. SLA Monitoring and Alerting
Metrics:
- Compute
dispatch_lag = started_at - scheduled_forfor every run. Emit as a histogram by tenant, priority, and partition. Track p50, p99, and compliance rate (% under 5s).
Proactive detection:
- An SLA monitor queries every 10 seconds:
SELECT run_id FROM runs WHERE state IN ('PENDING', 'READY') AND scheduled_for < now() - sla_dispatch_sec. These tasks are late right now. - Emit
SLA_VIOLATIONevents to the audit log and alert when violation rate exceeds a threshold (e.g., >0.5% over 5 min) or any critical-priority task misses.
Leading indicators (alert before SLA breaks):
- Ready queue lag (depth × age)
- Dispatcher scan duration crossing 1s
- Partition imbalance (one dispatcher holding too many leases)
- Worker claim failure rate (contention signal)
6. Trade-offs and Alternatives
| Choice | Why | Alternative |
|---|---|---|
| Time-bucketed partitions | O(tasks in next minute) not O(all tasks); natural horizontal scale | Sorted set in Redis (single-node bottleneck at 5k/s); delay queue per minute (complex watermark management) |
| CAS for claiming | Strong consistency, no duplicate execution | Optimistic locking with version field (same outcome, slightly less clear semantics) |
| Lease + reaper | Tolerates worker crashes, bounded recovery time | Two-phase commit (overkill, slower); idempotent completion only (allows duplicate execution during lease recovery) |
| Kafka for ready queue | Ordering, replay, natural backpressure | SQS (simpler ops, but 15min max delay complicates retries); direct worker poll (no buffering under burst) |
| Separate dispatcher and worker | Independent scaling; dispatchers are stateless CPU-bound, workers are I/O-bound and potentially GPU/memory-heavy | Combined node (works at smaller scale, harder to tune autoscaling) |
Common mistakes to avoid:
- Polling the entire
runstable every second (doesn't scale past 100k active tasks) - Using queue message visibility timeout as the only execution guard (leads to duplicates on redelivery)
- Materializing all future occurrences of a recurring task upfront (unbounded storage; a bug can create millions of rows)
- Relying solely on post-completion metrics for SLA monitoring (you learn about the miss too late to act)
7. Scaling Beyond the Initial Design
- Multi-region: Run dispatchers in each region with a global task registry. Route executions to the region closest to task data.
- Priority and fairness: Use separate Kafka topics per priority tier. Apply per-tenant rate limits at ingestion and worker claim time.
- Task dependencies: Add a DAG scheduler layer that waits for upstream completions before marking downstream tasks
PENDING. - Cost optimization: Archive cold run history (>30 days) to S3/GCS. Use reserved or spot instances for the worker fleet with graceful drain on termination.