Module 5: Async Processing
Task Queues
Background job queues for emails, image processing, and fan-out work — retries, backoff, visibility timeouts, idempotency, and DLQs.
If a user action triggers slow work, put it on a queue and return quickly. That is how you send thousands of emails or process uploads without timing out HTTP.
What you will learn
- Design a producer/consumer job pipeline with a thin request path
- Explain visibility timeouts, retries, backoff, and DLQs
- Keep handlers idempotent under at-least-once delivery
- Scale workers and reason about queue depth under spikes
- Separate critical jobs from bulk/noisy workloads
Why task queues exist
- HTTP requests should finish fast. Slow or bursty work belongs on workers that scale on their own.
- Protect p99 — do not block on SMTP, thumbnails, or PDF renders
- Absorb spikes — enqueue during peaks; drain when capacity returns
- Retry safely — transient failures leave the user request unaffected
- Fan-out — one API action can spawn many independent jobs
- Cost — lag, duplicates, and ops for workers/queues
Core pattern
- Producer enqueues; consumers pull and ACK. Keep the payload small and explicit.
- API validates input, writes needed DB state, enqueues job {type, payload, attempts}
- Return 202/queued (or success with “processing”) to the client
- Workers pull jobs, process, ACK success or schedule retry
- Scale workers horizontally with queue depth / lag
- Store large blobs in object storage; put only IDs/URLs in the job
Good jobs vs bad jobs
- Not everything belongs on a queue. Pick work that is slow, flaky, or bursty.
- Good: email/SMS, image/video transcode, webhooks, report generation, search indexing
- Good: fan-out notifications, periodic cleanup, data import batches
- Bad: work the user must wait on for the next screen with no polling/push story
- Bad: tiny sync DB reads that finish in milliseconds
- If the UI needs the result, add job status polling, websockets, or email when done
Visibility timeout & leases
- While a worker runs a job, others should not steal it — but crashes must not lose it forever.
- Visibility timeout / lease hides the job until ACK or timeout
- If the worker dies, the job reappears for another worker
- Timeout must exceed typical processing time (with margin)
- Long jobs should heartbeat/extend the lease
- Too-short timeout ⇒ duplicate concurrent processors; too-long ⇒ slow recovery
Retries, backoff, and DLQ
- Transient failures deserve retries. Poison payloads deserve isolation.
- Retry timeouts and 5xx from dependencies; do not blindly retry permanent 400s
- Exponential backoff (+ jitter) to avoid retry storms
- Cap attempts (e.g. 5–10); then send to a dead-letter queue
- Alert on DLQ depth; provide a replay tool for ops
- Record last error on the job for debugging
Idempotency
- At-least-once delivery is the default. Double processing must be safe.
- Use a job id / idempotency key stored when side effects commit
- Email: dedupe by (template, user, campaign id)
- Payments/webhooks: store provider event ids before acting
- Prefer “upsert” and conditional writes over blind inserts
- ACK only after the side effect is durably recorded
Priorities & queue isolation
- One shared queue lets bulk exports starve password-reset emails.
- Separate queues by criticality (high / default / bulk)
- Dedicated worker pools per queue so noisy jobs cannot block urgent ones
- Optional delay queues / scheduled jobs for future sends
- Rate-limit outbound calls (SMTP, third-party APIs) inside workers
- Fairness matters as much as total throughput
Scaling & queue depth
- Workers and partitions are your knobs. Depth and age are your SLOs.
- Autoscale workers on depth, age of oldest job, or lag
- Estimate spike: enqueue rate × processing time ⇒ needed concurrency
- Watch poison jobs inflating depth without progress
- Batch where safe (multi-recipient email) without breaking per-user order needs
- Backpressure: shed or reject new bulk jobs when depth exceeds budget
Task queues vs brokers / events
- Same family of async tools; different intent on the whiteboard.
- Task queue — “do this job” commands with retries until done
- Event stream — “this happened” facts for many subscribers
- You often enqueue a task in response to an event (OrderPaid → SendReceiptJob)
- Do not rebuild a full event bus when a simple job queue solves the API timeout
- Pick the thinner tool that matches the problem
Common mistakes
- These designs look fine until production traffic hits.
- Sending email synchronously inside the request handler
- Non-idempotent workers under visibility-timeout redelivery
- No DLQ — one bad payload blocks forever or retries infinitely
- Giant payloads in the queue instead of object-storage references
- Single queue for urgent and bulk work
Interview framing
- Use this order when background work appears in a design.
- Show the thin API: validate → persist → enqueue → respond
- Name job type, payload fields, and idempotency key
- Cover lease/visibility, retry/backoff, DLQ + alert
- Split critical vs bulk queues if needed
- State how the user learns completion (poll, push, email)
Quick revision checklist
- Separate “accept request” from “do heavy work”.
- Estimate queue depth under spike.
- Always make workers idempotent.
- Mention visibility timeout / leases.
- Add DLQ + alerting for poison jobs.
- Isolate urgent queues from bulk work.
FAQs
Sync email send in the API?
Avoid it for bulk or slow SMTP. Enqueue and show a queued/processing state to the user.
What is a visibility timeout?
A lease period where a retrieved job is hidden from other workers. If the worker fails to ACK in time, the job becomes visible again for retry.
How many times should a job retry?
Enough for transient blips (often a handful with exponential backoff), then DLQ. Infinite retries turn poison messages into permanent load.
How do I stop duplicate emails?
Treat delivery as at-least-once. Persist an idempotency key for that send and skip if already completed successfully.
Should job payloads include large files?
No. Store files in object storage and put the object key/URL in the job. Keeps the queue fast and messages small.
Task queue or Kafka?
Use a task queue for command-style unit-of-work jobs with ACK/retry. Use a log/stream when you need replayable events and many independent consumers.
Learner’s Task
- Practice out loud for 8–10 minutes. Design background jobs for one user action.
- Pick an action (signup or video upload) and list which steps stay sync vs become jobs.
- Define one job payload (fields + idempotency key) and the API response the user gets immediately.
- Explain visibility timeout, retry/backoff, and DLQ for that job.
- Estimate workers needed for a 10× spike using enqueue rate × processing time.
- Write a 4-sentence closing: thin API, job design, reliability knobs, and how completion is surfaced.