Notes
All notes

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 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:

# 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:

\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

QQuestionSelf-check

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.