Queues & Asynchronous Work
Decouple slow work from HTTP requests with queues vs pub/sub, at-least-once delivery, idempotency keys, exponential backoff retries, and dead-letter queues.
TL;DR
Use a queue to move slow or failure-prone work (emails, webhooks, video encoding) out of the HTTP request path. Because brokers deliver at least once, workers must be idempotent, retry transient errors with exponential backoff + jitter, and route poison messages to a Dead-Letter Queue (DLQ).
Intent
Understand when to use a queue versus pub/sub, how at-least-once delivery shapes worker design, and how retries and DLQs keep poison messages from stalling your pipeline.
Problem
Sending an email, generating a PDF, or calling a flaky third-party webhook inside an HTTP POST handler ties up request threads, exposes users to 30-second timeouts, and loses the job completely if the server restarts mid-request.
Solution
1. Queue vs Pub/Sub
- Work Queue (point-to-point): Multiple workers compete to pull messages; each message is processed by one worker. Use this for background jobs and load leveling.
- Pub/Sub (fan-out): A publisher emits an event (
order.paid) and every independent subscriber (billing, analytics, email) receives its own copy.
2. At-least-once delivery & idempotency
Network acks can be lost: a worker may finish charging a card or writing a row, then crash before sending ACK to the broker. The broker assumes the job failed and redelivers it. To make retries safe:
- Attach a deterministic idempotency key (e.g.,
invoice:1042:send-email) to every message. - Record processed keys in a database unique constraint or atomic store before/with the side effect so duplicates become no-ops.
3. Retries with backoff and Dead-Letter Queues (DLQ)
- Transient failures (downstream
503, rate limit): NACK or let visibility timeout expire, then retry with exponential backoff + jitter (2s,4s,8s+ random ms) so you don't DDoS a recovering dependency. - Poison messages (malformed JSON, deleted user ID, bug): Retrying forever wastes worker capacity. After
max_retries(for example 3–5 attempts), the broker moves the message to a DLQ, where engineers can alert, inspect, fix the bug, and replay.
Real-world analogy
▶ Flow: watch it work
Async Job Lifecycle: API → Queue → Worker → Retry → DLQ
Press Start or tap any step dot to trace the path.
▸All steps (5)
Code
Minimal idempotent worker handler showing duplicate detection and throwing on transient errors so the broker schedules a retry:
// Idempotent queue consumer (not run)
interface JobMessage {
idempotencyKey: string;
userId: string;
}
export async function handleWelcomeEmail(
msg: JobMessage,
seenKeys: Set<string>,
sendEmail: (userId: string) => Promise<void>,
): Promise<'ack' | 'skip'> {
if (seenKeys.has(msg.idempotencyKey)) {
return 'skip'; // Already processed; ACK safely without side effects
}
await sendEmail(msg.userId); // Throws on 5xx -> broker retries with backoff
seenKeys.add(msg.idempotencyKey); // In production, store atomically in DB
return 'ack';
}When you DON'T need this
- Static sites or synchronous CRUD: A static site (like this one) or a fast
< 50 msdatabase write doesn't need a message broker—returning200 OKsynchronously is simpler and easier to debug. - Strict immediate response required: If the user is waiting on the screen for the exact result (e.g., login or search), a queue just adds latency and polling complexity.
- Cost / complexity trade-off: Adding a queue introduces eventual consistency, a broker to operate (or pay per-million-messages for SQS/Cloudflare Queues), DLQ monitoring, and harder end-to-end tracing. Use it only when decoupling latency or surviving downstream outages is worth that operational cost.
When to use / when to avoid
- Slow tasks (> 500 ms) like email, PDF/image processing, or webhook delivery.
- Traffic spikes where you need to buffer writes instead of overwhelming your database.
- Fast synchronous reads/writes where the caller needs the result immediately.
- Before you have idempotency keys—non-idempotent retries will corrupt data.
How to implement
Design messages with an idempotency key
Include a stable key (e.g., orderId + action) so duplicate deliveries are safe.
Configure backoff and max_retries
Set exponential backoff with jitter and cap retries (e.g., 3–5 attempts) before moving messages to a DLQ.
Alert on DLQ depth
A growing DLQ means a bug or broken integration—monitor its count and build a safe replay script.
Pros / Cons
- Keeps HTTP APIs fast and resilient to slow or flaky third-party dependencies.
- Smooths traffic bursts (load leveling) without over-provisioning databases.
- Eventual consistency: UI must handle 202 Accepted / pending states.
- At-least-once delivery requires idempotency and DLQ replay tooling.
Relations
Check yourself
Check Yourself
1. Why must queue workers be idempotent under at-least-once delivery?
2. What happens if you configure a queue with infinite retries and no Dead-Letter Queue (DLQ)?
Sources
Related Notes
Caching Strategies & Redis
Compare cache-aside, write-through, and write-behind caching, handle TTLs, stampedes, Redis RDB/AOF persistence, and degrade gracefully when the cache is down.
The C4 Model: Context, Container, Component, Code
Visualize software architecture at four zoom levels—System Context, Containers, Components, and Code—applied to Mengty Learns itself.