Build a Delayed-Task Platform with a Fast Status Cache
System DesignModel answerLast updated
Design a distributed platform that runs delayed and immediate background tasks with retries and durable state, plus a cache that serves task status in under 10 ms at 10k requests/second.
Build a Delayed-Task Platform with a Fast Status Cache
You are asked to design a backend service that lets clients submit units of work to be executed asynchronously, either right away or at a later time. The service must track each task through its lifecycle and let clients find out what happened to it. A cache in front of the task metadata must keep status lookups fast even when load is heavy.
Functional requirements
- Clients can submit a task for immediate execution or with a delay or a target start time.
- Each task moves through the durable states
PENDING,PROCESSING,COMPLETEDandFAILED. - Failed attempts are retried automatically using exponential backoff.
- Clients can poll for status or be notified when it changes.
Non-functional requirements
- The system must sustain about 10,000 requests per second overall.
- Running the same task twice must not cause duplicate side effects (idempotency).
- Status reads must complete in under 10 ms.
- The service must be highly available and tolerate node and zone failures.
What to cover in your answer
- API design: Public endpoints for submitting tasks and checking status, plus the interface that internal workers use to claim and report on work.
- Data model: A storage schema, and how you make state transitions safe when several actors race.
- Caching strategy: The cache design, including eviction, write-through versus write-behind consistency, and how you handle hot keys, for example thousands of workers or clients reading the same task's status.
- Architecture: The main components (queues, workers, scheduler, cache, durable store) and how they fit together, including failure handling.
State your assumptions about traffic mix and delivery semantics, and discuss the trade-offs behind your main choices.
Hints
Hint 1
Split the 10k req/s into submits, status reads and state-change writes. Reads usually dominate, and each task causes several writes as it moves through its states.
Hint 2
Assume at-least-once delivery and make the handlers safe to repeat. Think about conditional (compare-and-set) updates, lease tokens that fence out stale workers, and idempotency keys on submission.
Hint 3
Message brokers rarely support delays natively, so consider keeping future-dated tasks in the database or a sorted structure and having a scheduler release them when due.
Hint 4
For the cache, ask what happens if a cache write is lost or arrives out of order. Versioned writes and a change-data-capture repair path help. For hot keys, consider request coalescing, local in-process caches with short TTLs, and long-polling or push instead of tight polling.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scale and semantics
Turn "10k req/s" into a workload and confirm it with the interviewer:
- Submits: about 2k/s.
- Status reads: about 8k/s, many from polling clients.
- State writes: each task goes through 3-4 transitions, so about 6-8k writes/s.
- Storage: 2k/s is roughly 170M tasks/day. At about 1 KB of metadata each that is about 170 GB/day, or about 2.5 TB with 14-day retention. The store therefore needs partitioning and time-based expiry.
- Latency: a p99 under 10 ms means the read path cannot depend on a database round trip.
- Semantics: at-least-once delivery combined with idempotent execution. Exactly-once is not achievable end to end, so say this up front.
2. API design
Public
POST /v1/tasks Header: Idempotency-Key
body: {type, payload, run_at | delay_ms, priority, max_attempts, callback_url}
-> 202 {task_id, state: "PENDING"}
GET /v1/tasks/{id} -> {state, attempt, version, result_ref, error, updated_at}
GET /v1/tasks/{id}?wait=30s -> long-poll, returns when version changes
POST /v1/tasks/{id}:cancel
Notifications go through webhooks or a per-tenant pub/sub topic. Long-polling replaces tight client polling loops.
Internal worker interface
Claim(task_id, worker_id) -> {lease_token, expires_at} | CONFLICT
Heartbeat(task_id, lease_token)
Complete(task_id, lease_token, result_ref)
Fail(task_id, lease_token, error, retryable)
The lease token acts as a fencing token. A worker whose lease expired cannot overwrite newer state.
3. Data model and safe transitions
Use a horizontally scalable store with conditional writes (DynamoDB, Cassandra with lightweight transactions, or sharded Postgres), partitioned by task_id.
tasks(task_id PK, tenant_id, type, payload_ref, idempotency_key,
state, priority, run_at, attempt, max_attempts,
lease_owner, lease_expires_at, version,
result_ref, last_error, created_at, updated_at)
unique (tenant_id, idempotency_key)
index (shard_bucket, state, run_at) -- used by the scheduler
State machine:
PENDING -> PROCESSINGon claim.PROCESSING -> COMPLETEDon success.PROCESSING -> PENDINGon a retryable failure or lease expiry, withrun_atpushed out by the backoff.PROCESSING -> FAILEDwhen attempts run out or the error is non-retryable. The task is also sent to a dead-letter queue.COMPLETEDandFAILEDare terminal.
Every transition is one compare-and-set:
UPDATE tasks SET state='PROCESSING', lease_owner=:w,
lease_expires_at=now()+30s, attempt=attempt+1, version=version+1
WHERE task_id=:id AND state='PENDING' AND run_at<=now();
If zero rows change, another worker won and this one drops the message quietly. Completion requires lease_owner=:w AND version=:v. Only the lease holder can write, losers fail fast, and no distributed lock is needed.
Backoff with jitter: run_at = now + min(cap, base * 2^attempt) * rand(0.5, 1). Jitter prevents synchronized retry waves after a downstream outage.
Idempotent side effects: pass task_id + attempt-independent key to downstream calls, or record an "effect applied" marker in the same transaction as the state change.
4. Architecture
- Stateless API tier behind a load balancer. It validates input, dedupes through the unique idempotency constraint, and writes the task row and an outbox row in one transaction.
- Outbox relay / CDC publishes immediate tasks to Kafka, partitioned by
task_idwith separate topics per priority. This closes the "DB committed but publish failed" gap. - Sharded scheduler. Kafka has no delay support, so future tasks and retries stay in the database. Each scheduler owns some shard buckets, polls every 100-500 ms for
PENDING AND run_at<=now, and publishes due tasks. It also sweeps expired leases back toPENDING. A Redis sorted set keyed byrun_atis an option for finer timing, with the database remaining authoritative. - Workers consume from Kafka, claim through the CAS, run the work, heartbeat on long tasks, then complete or fail. Offsets are committed only after the state write.
- Notifier reads state-change events and fires webhooks with its own retries.
- DLQ and admin tooling for inspection and replay.
Deploy across three zones with replicated storage and Kafka (replication factor 3, min.insync.replicas=2). Losing a worker only delays its tasks until the lease expires.
5. Caching strategy
What to cache: a small status record {state, attempt, version, updated_at, result_ref} under task:{id}. Large results stay in blob storage.
Consistency: write-through with versioning, not write-behind.
- Write-behind can lose acknowledged transitions if the cache dies, which is unacceptable for a durable state machine.
- Commit the CAS to the database first, then update the cache. A small Lua script applies the write only if the new
versionis higher, so a late stale update cannot regressCOMPLETEDback toPROCESSING. - A CDC consumer also refreshes the cache from the change stream, repairing any missed write within seconds.
- On a miss, use read-through with single-flight coalescing so N concurrent misses cause one database read.
Eviction and TTL
- Use
allkeys-lruor LFU. The hot working set (about the last hour, roughly 7M tasks at ~200 B) is only about 1.5 GB, so memory is cheap. - Terminal states are immutable and get long TTLs. Active tasks get short TTLs with random jitter to avoid synchronized expiry.
- Briefly negative-cache unknown IDs to blunt miss storms from bad IDs.
Hot keys
- Add a small in-process cache on API nodes with a 100-500 ms TTL for non-terminal tasks and a long TTL for terminal ones.
- Replicate very hot keys across several cache shards (
task:{id}#k, random k) and read from a random one. - Use long-polling or pub/sub push so thousands of watchers do not hammer one key. Fan out a single state-change event rather than letting each watcher poll.
- Rate-limit per caller and per task.
6. Failure modes and trade-offs
- Cache down: fall back to the database with rate limiting and circuit breakers. Reads degrade but remain correct.
- Worker crash: the lease expires and the sweeper requeues the task. This is why handlers must be idempotent.
- Duplicate delivery: the CAS makes the second claim fail.
- Scheduler failover: ownership of shard buckets is lease-based, and the CAS makes double-publishing harmless.
- Poison tasks: capped attempts and a DLQ stop infinite retry loops.
- Trade-off: short caching gives lower latency but briefly stale status. Terminal states are always correct, and clients that need strong consistency can pass a
consistent=trueflag that bypasses the cache.
Common mistakes
- Claiming exactly-once delivery instead of at-least-once plus idempotency.
- Using write-behind for authoritative state.
- Relying on a distributed lock rather than conditional writes and fencing tokens.
- Retrying without jitter or a cap.
- Forgetting the outbox, which leaves a gap between database commit and queue publish.
- Ignoring hot keys and letting clients poll in tight loops.