Background Jobs (System Design #6)
A user signs up. Your endpoint writes the row, then synchronously sends a welcome email, generates a thumbnail, updates the search index, and calls the analytics API. Each takes 200 ms, and any one of them can be down. Signup now takes a second, fails when the mail provider hiccups, and holds a database transaction open the whole time.
The fix is older than the cloud: do the slow, non-essential parts later. This chapter covers background jobs — the pattern that takes work off the request path, absorbs traffic spikes, and lets failures retry instead of fail the user.
The core idea
The request path should do the minimum to satisfy the user and return. Everything else — emails, thumbnails, indexing, notifications, report generation — becomes a job that runs asynchronously.
\[ \text{response time} = \text{essential work} + \text{enqueue}, \qquad \text{deferred work} \to \text{workers} \]
This gives three benefits at once: latency (the user waits only for essential work), availability (a dead email service no longer breaks signup — the job retries), and elasticity (traffic spikes become queue depth, drained at the workers’ pace).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.6cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=gray!10] (req) at (-4.4,0) {request};
\node[b, fill=green!12] (app) at (-2.3,0) {app};
\node[b, fill=yellow!22] (q) at (0,0) {queue};
\node[b, fill=orange!16] (w1) at (2.4,0.8) {worker};
\node[b, fill=orange!16] (w2) at (2.4,-0.8) {worker};
\draw[a] (req) -- (app); \draw[a] (app) -- node[above, font=\scriptsize] {enqueue} (q);
\draw[a] (q) -- (w1); \draw[a] (q) -- (w2);
\node[font=\rmfamily\small, text=black!60] at (-2.3,-0.8) {returns in ms};
\end{tikzpicture}
Event-driven vs schedule-driven
Two triggers for background work:
- Event-driven — a job enqueues the moment something happens. “On
user.created, send the email.” Low latency, naturally reactive; the challenge is ordering and duplicate delivery. - Schedule-driven — a job runs on a clock: every minute, every night at 02:00. “Recompute trending topics hourly.” Decoupled from user actions, easy to batch; the challenge is not overlapping runs and handling missed windows.
| Event-driven | Schedule-driven | |
|---|---|---|
| Trigger | a domain event | a timer/cron |
| Latency | seconds | bounded by interval |
| Batching | per-event | natural |
| Examples | welcome email, thumbnail, webhook | nightly digest, cleanup, report |
| Risk | duplicates, ordering | overlap, missed runs |
Many systems use both: events for user-facing immediacy, schedules for batching and maintenance. Rate limiting and cleanup are almost always scheduled; notifications and indexing are usually event-driven.
How work gets done: queues and workers
The job goes onto a durable queue; a pool of workers pulls and processes it. The queue provides buffering (spikes become depth), retries (failed jobs return), and decoupling (producer and consumer scale independently). Chapter 13 covers queue mechanics in depth; here the important parts are:
- Acknowledge after success. If the worker crashes mid-job, the message must return to the queue, which means delivery is at-least-once.
- Idempotency is mandatory. Because at-least-once means a job can run twice (a redelivery, a retry), every job must be safe to repeat. Use a unique job key and a processed-set, or make the operation naturally idempotent (Chapter 14).
- Dead-letter queue (DLQ). After N failures, move the job aside for inspection instead of poisoning the queue forever.
- Visibility timeout. If a worker does not finish within a window, the message becomes visible again for another worker — usually right, occasionally causing duplicate work (hence idempotency).
# event-driven job with idempotency and retry
def handle_user_created(msg, store, mailer):
key = f"welcome:{msg['user_id']}"
if store.seen(key): # duplicate delivery? skip
return
try:
mailer.send_welcome(msg["email"])
store.mark_seen(key) # only after success
except Exception:
raise # let the queue retry, then DLQ
Returning results to the user
If work is deferred, how does the user learn the outcome? Three patterns:
- Polling. The API returns
202 Acceptedwith ajob_id; the client pollsGET /jobs/{id}untildone/failed. Simple, works everywhere, but chatty. - Webhooks / callbacks. The worker calls back a URL when done. Efficient, but the client must expose an endpoint, verify signatures, and handle retries.
- Long polling / server-sent events / WebSockets. The server pushes the result when ready. Best UX, more infrastructure.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.8cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=gray!10] (c) at (-3.6,0) {client};
\node[b, fill=green!12] (api) at (-1.2,0) {API};
\node[b, fill=yellow!22] (job) at (1.2,0) {job store};
\node[b, fill=orange!16] (w) at (3.6,0) {worker};
\draw[a] (c) -- node[above, font=\scriptsize] {submit} (api);
\draw[a] (api) -- node[above, font=\scriptsize] {job\_id} (job);
\draw[a] (job) -- (w);
\draw[a, dashed] (w) to[bend left=28] node[below, font=\scriptsize] {status/result} (job);
\end{tikzpicture}
Sizing the system
Little’s Law sizes the worker pool: with arrival rate \(\lambda\) jobs/second and average processing time \(W\) seconds, you need \(L = \lambda W\) workers just to keep up, plus slack. And the queue depth itself tells you whether you are under-provisioned: a steadily growing queue is an outage in slow motion.
def workers_needed(lambda_per_s, w_seconds, headroom=1.5):
return max(1, round(lambda_per_s * w_seconds * headroom))
print(workers_needed(50, 2)) # 50 jobs/s, 2s each -> 150 workers
print(workers_needed(0.01, 30)) # nightly-heavy work -> 1 worker, batch it
Also decide the overflow policy: when the queue grows unboundedly, do you drop low-priority jobs, shed load (return 429), or scale workers (with a cost ceiling)? Every queue needs an answer; “grow forever” is not one.
Pitfalls
- Non-idempotent jobs. At-least-once delivery will run a job twice; a duplicate email is annoying, a duplicate charge is a lawsuit. Make writes idempotent.
- No retry ceiling / no DLQ. A permanently failing job retries forever, burning resources and drowning real work in logs.
- Silent failure. Deferred work means no user sees the error. Without monitoring and alerting on queue depth and DLQ size, jobs die unnoticed.
- Unbounded queue as a safety valve. A very deep queue turns a spike into hours of stale work. Cap depth and prioritize.
- Doing essential work in the background. If the user must see it to proceed, it belongs on the request path. Background is for deferrable work.
Why must background jobs be idempotent? When would you choose schedule-driven over event-driven work?
ASolution
Because queues deliver at-least-once (retries, visibility timeouts), a job can run more than once, so repeating it must be safe. Schedule-driven suits work that is periodic or batchable — nightly reports, cleanups, digests — where event-triggering would be wasteful or unnecessary.
Next: DNS and CDNs (System Design #7) — the first hop every user takes, and how bytes get close to them.