System design concepts · Doing Things Later

Background Jobs, Schedulers and Workflow Engines

Half of every real product runs when nobody is watching: emails, invoices, video encodes, data clean-ups, retries. This chapter is about doing that work reliably.

What you'll be able to explain
  • Classify background work and choose the right execution model
  • Design a job system with claiming, leases, retries and dead letters
  • Make jobs idempotent so retries and duplicates are harmless
  • Run scheduled (cron) work exactly when it should, even with many servers
  • Orchestrate multi-step workflows with durable state and compensation

Kinds of background work

Not all "later" work is alike. Naming the kind tells you the tool.

Kind Example Trigger Typical tool
Fire-and-forget task Send a welcome email An event or API call Task queue (SQS, RabbitMQ, Redis-based queues)
Heavy processing Transcode a video, generate a PDF Upload completed Queue + autoscaled workers
Scheduled (cron) Nightly invoices, hourly clean-up The clock Scheduler + queue
Delayed Remind the user in 24 h if the cart is still full An event plus a delay Delayed queue or scheduler
Long-running workflow Order → pay → pack → ship → deliver, over days An event; many steps Workflow engine (Temporal, Step Functions)
Bulk / batch Re-index 200M products An operator Batch framework, chunked jobs
Analogy

A restaurant kitchen is a job system. Orders go on the rail (the queue), cooks grab tickets (workers claim jobs), the head chef notices if a ticket has been sitting too long (lease timeout), and a burnt dish is remade rather than served (retry). Some dishes need many stations in order (a workflow).

The anatomy of a job system

SERVICEAPI / producersQUEUE / LOGJob queueready jobsWORKERSchedulercron + delaysWORKERWorker poolautoscaledDATABASEJob storestatus, attemptsQUEUE / LOGDead-letter queueEXTERNALEmail, storage, APIsenqueuedue jobsclaim (lease)do the workstatus / resultgave up after N tries
A general-purpose job system. The API only enqueues; workers do the work and record the outcome.

Each job record needs, at minimum:

Field Why
job_id Identity; also the idempotency key for side effects
type, payload What to do, with what (keep payloads small; reference big data by ID)
status queued → running → succeeded / failed / dead
attempts, max_attempts Retry budget
run_at Not before this time (delays, back-off)
lease_until, worker_id Who holds it and until when
priority, queue Isolation and ordering of urgency

Claiming: two workers must not run the same job

When ten workers poll for work, two of them may grab the same job. Three common ways to claim safely:

  1. Broker visibility timeout (SQS, many queues): receiving a message hides it from others for N seconds. If the worker doesn't delete it in time, it reappears.
  2. Database row lock: SELECT … FOR UPDATE SKIP LOCKED LIMIT 10 lets many workers pull different rows from a jobs table without blocking each other. Simple and surprisingly scalable to thousands of jobs per second.
  3. Partitioned ownership: each worker owns a set of partitions (Kafka consumer groups), so jobs for a key go to exactly one worker.

Leases and heartbeats

A claim is a lease, not ownership forever. The worker must finish, or extend the lease with heartbeats, before it expires. If it crashes, the lease lapses and another worker picks the job up.

Common trap

A lease that expires while the original worker is merely slow (a long GC pause, a slow network call) means two workers now run the same job. Leases make this rare, not impossible. That's why every job must be idempotent, and why critical side effects should check a fencing token or a status guard ("only ship if status is still PACKED").

Idempotency: making "again" harmless

With retries, timeouts and redelivery, every job will eventually run twice. Design for it:

  • Natural idempotency: "set status to SHIPPED" is safe to repeat; "add ₹100" is not.
  • Idempotency keys: pass job_id to the payment or email provider so it drops duplicates.
  • Dedup table: record (job_id, step) when a side effect is done; check before doing it again, ideally in the same transaction as the effect.
  • Conditional writes: UPDATE orders SET status='SHIPPED' WHERE id=? AND status='PACKED'; the second run changes nothing.