Build a Retry-Safe Background Job Service for Heavy Tasks
System DesignModel answerLast updated
Design an HTTP service that accepts long-running jobs, returns immediately, deduplicates client retries, and survives worker crashes without repeating side effects.
Design a Background Job Service
Your team needs a service that lets clients start heavy, slow operations over HTTP, for example shrinking very large images or building big reports. The work takes anywhere from a few seconds to several minutes, so the caller cannot wait on the request.
What the service must do
- Submit:
POST /jobsaccepts a task and responds right away with202 Acceptedand ajob_id. - Check progress:
GET /jobs/{job_id}returns the current state (pending,processing,completed, orfailed) and, once finished, the result. - Safe retries: Clients on flaky networks may send the same submission several times. Regardless of how many arrive, exactly one job must be created and run.
Operating constraints
- Peak load is around 1,000 requests per second.
- Individual jobs run from seconds to minutes.
- Worker crashes and service restarts must not lose jobs or corrupt state.
What to cover in your answer
- The API contract and the data model.
- The path of one request from submission to its final status update.
- The exact mechanism that guarantees idempotency.
- How worker failures and retries are handled without duplicating side effects.
- Your storage choices for job metadata, status changes, and results.
Be explicit about sizing assumptions and the trade-offs behind your choices.
Hints
Hint 1
Break the 1,000 RPS into submissions versus status polls, then use jobs per second times average duration to estimate how many jobs run concurrently.
Hint 2
Exactly-once delivery is not realistic. Aim for at-least-once delivery combined with processing that is safe to repeat, and let a database uniqueness constraint decide which duplicate submission wins.
Hint 3
Think about two failure windows: saving the job but failing to enqueue it, and a worker that stalls and later wakes up after another worker took over. Look at the outbox pattern, leases with heartbeats, and fencing tokens.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Sizing first
- Traffic mix: 1,000 RPS is mostly polling. Assume roughly 200 submissions/s and 800 status reads/s.
- Volume: 200 jobs/s is about 17M jobs/day. At ~1 KB of metadata each, that is ~17 GB/day. Large inputs and outputs live in object storage, not the database.
- Concurrency: Little's law with a 30 s average job gives 200 x 30 = ~6,000 jobs in flight. The worker fleet must be horizontal and autoscale on queue depth.
- Semantics: Target exactly-once effect = at-least-once delivery + idempotent processing.
- Key retention: Keep idempotency keys for about 24 hours to outlast client retry windows.
2. API contract
POST /jobs requires an Idempotency-Key header plus auth. The body carries type, params, and an input_uri. Response: 202 Accepted, a Location: /jobs/{id} header, and {job_id, status: "pending"}.
| Situation | Behavior |
|---|---|
| Same key, same payload | Return the original job_id (optionally flag it as a replay) |
| Same key, different payload | 422: this is a client bug, never ignore it silently |
| Same key, first request still running | Return the existing job; the unique index makes this safe |
GET /jobs/{id} returns status, result_uri, error, attempts, and timestamps. Offer an optional webhook and a Retry-After header to reduce polling.
3. Data model
A jobs table holds: job_id (PK), tenant_id, idempotency_key, request_hash (SHA-256 of the canonical body), type, params, status, attempt, lease_owner, lease_expires, result_uri, error, and timestamps. Add UNIQUE (tenant_id, idempotency_key). Scoping by tenant prevents two customers with the same generated key from colliding.
An outbox table (id, job_id, payload, published) supports reliable enqueueing.
4. Submission flow and idempotency
- Validate the request and hash the canonical body.
- In one transaction,
INSERT ... ON CONFLICT (tenant_id, idempotency_key) DO NOTHING RETURNING job_id. - If a row was inserted, add an outbox row in the same transaction, commit, and return
202. - If there was a conflict, read the existing row. Matching hash: return its
job_id. Different hash:422. - An outbox relay (a poller or CDC such as Debezium) publishes to the queue and marks rows published.
The unique index is the guarantee. Concurrent retries race on the insert; the database admits exactly one and the others read the winner. A Redis check-then-set is not enough: it has a check/insert race and is not durable.
The outbox closes the dual-write gap. Without it, "committed but publish failed" strands a job in pending, and "published but rolled back" creates a phantom job. The relay may publish a message twice, which is acceptable because workers are idempotent.
5. Workers, failures, and retries
Assume every message can arrive more than once.
- Claim atomically:
UPDATE jobs SET status='processing', attempt=attempt+1, lease_owner=?, lease_expires=now()+2min WHERE job_id=? AND (status='pending' OR (status='processing' AND lease_expires < now())) RETURNING attempt. Zero rows means someone else owns it or it is done, so ack and drop. - Heartbeat: extend the lease every ~30 s while working.
- Idempotent side effects: write outputs to a deterministic key such as
results/{job_id}/output.pngso a retry overwrites rather than duplicates. Passjob_idas the idempotency key to any external call (payments, email). - Fenced completion:
UPDATE ... SET status='completed', result_uri=? WHERE job_id=? AND attempt=? AND status='processing'. The attempt number is a fencing token, so a zombie worker whose lease was taken over cannot overwrite the new owner's result. - Ack after commit: acknowledge the message only once the database write succeeds.
- Error handling: transient errors (timeouts, throttling) return the job to
pendingwith exponential backoff and jitter. Permanent errors (bad input) go straight tofailed. After N attempts (e.g. 5), markfailedand send to a dead-letter queue.
If a worker dies, its lease expires, and either a redelivered message or a periodic reaper lets another worker reclaim the job.
6. Storage
- Metadata: Postgres, partitioned daily by
created_at. With ~200 inserts/s and ~4 status updates per job, load is about 1,000 writes/s, well within one tuned primary. Shard bytenant_idif growth reaches 10x. DynamoDB with conditional writes and TTL is an equally valid alternative. - Reads: serve
GETfrom replicas, tolerating a second or two of lag. If a just-created job is missing, fall back to the primary to avoid a confusing 404. - Cache: Redis with write-through on status changes and a short TTL absorbs aggressive polling.
- Blobs: S3/GCS for inputs and results; the database stores only URIs.
7. Trade-offs
- SQS vs Kafka: SQS gives visibility timeouts and a DLQ out of the box, which suits independent jobs. Kafka offers replay and ordering, but one slow job blocks its partition, so you need a separate lease mechanism or parallel consumers.
- Outbox polling vs CDC: polling is simple but adds latency and load; CDC is faster but adds operational complexity.
- Lease length: short leases recover quickly but risk false takeovers; long leases are stable but slow recovery. Heartbeats let you keep leases short.
Common mistakes
- Relying on Redis alone for deduplication.
- Enqueueing after commit without an outbox.
- Acking the message before the result is durably stored.
- Letting a stale worker write final state without a fencing check.
- Ignoring payload mismatches on a reused key.
- Writing results to random paths, so retries create duplicates.