FullStack AI Hub
Studio
System Design · 04. Communication
11 min
11 steps
Beginner

Message Queues

Buffer traffic spikes with async queues, apply backpressure cleanly, deduplicate retries, and isolate poison pills in dead-letter queues.

System Design04. CommunicationLesson 2 of 4
11 minBeginner11 steps

Message Queues

Buffer traffic spikes with async queues, apply backpressure cleanly, deduplicate retries, and isolate poison pills in dead-letter queues.

ORDER BURST
2,400/s
CHECKOUT P95
2,900 ms
504 TIMEOUTS
48%
INVOICE SVC
100%
blocking HTTP2,400 orders/sCheckout API90%blocked threadsInvoice &Email100%100% SATURATED1,200/s ceiling drops half of orders!
enqueued job
worker ACK / commit
burst / redelivery
poison pill / shed
In This LessonStep 1 of 11
What You Will Master
  • ✓Decouple bursty producers from slow downstream services with queues and competing consumers
  • ✓Protect memory and critical flows using bounded queue capacities, backpressure, and priority lanes
  • ✓Handle at-least-once redeliveries and visibility timeouts safely with idempotency keys
  • ✓Quarantine poison pills in a Dead-Letter Queue (DLQ) and guarantee atomic publishing via Transactional Outbox

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Competing ConsumersParallelizing slow emails, video transcodes, webhooksStrict global FIFO ordering is lost across parallel workers
Bounded BackpressurePreventing broker OOM crashes during sustained floodsCallers must handle 429/503 retries or shed low-priority work
Idempotency KeysPayments, order creation, inventory deductions on retryRequires dedup key storage (Redis/DB unique index) + TTL
DLQ + Outbox PatternZero lost events and zero infinite poison-pill crash loopsNeeds DLQ alerting/replay tooling and an outbox relay worker

Step-by-Step Architectural Breakdown (11 Steps)

Full architectural walkthrough transcript and state transitions for Message Queues.

STEP 01 · PROBLEMJump to step →

Synchronous checkout melts during a flash sale

When a shopper clicks **Buy**, your Checkout API calls the **Email & Invoice Service** synchronously over HTTP before returning 200 OK. Normally at 400 orders/s everything works.

At noon a flash sale hits **2,400 orders/s**. Because generating PDF invoices takes 400 ms, the Invoice Service saturates at **100%**, threads pile up in Checkout API, and **paying customers see 504 timeouts**.

watch:Synchronous chaining multiplies failure domains: a slow non-critical email renderer should never break checkout.

Tight CouplingSynchronous BottleneckCascading Timeout
STEP 02 · SOLUTIONJump to step →

Decouple with an async Message Queue

We place a durable **Message Queue** (SQS / RabbitMQ) between Checkout API and the Invoice Worker. Checkout validates payment, appends a tiny `OrderCreated` JSON job in **4 ms**, and returns `202 Accepted` immediately.

The queue acts as a **shock absorber**: even when producers burst at 2,400/s, workers pull jobs steadily at their own pace without crashing—**peak shaving** in action.

good:Users do not need their PDF receipt in 50 ms—moving side-effects behind a queue slashes checkout P95 by 20×.

Async DecouplingPeak ShavingProducer / Consumer
STEP 03 · TECHNIQUEJump to step →

Scale drain speed with Competing Consumers

If a flash sale lasts 30 minutes, one worker cannot drain the backlog fast enough. Adding **Competing Consumers** (Worker 1, Worker 2, Worker 3) lets multiple stateless processes pull independent messages in parallel.

Autoscaling simply watches **Queue Depth / Oldest Message Age**: when backlog grows, spin up more workers; when the queue empties, scale back down.

idea:Competing consumers maximize throughput, but parallel execution means Message #2 may finish before Message #1—use partition keys if per-user ordering matters.

Competing ConsumersQueue-Depth AutoscalingParallel Drain
STEP 04 · TECHNIQUEJump to step →

Bounded queues & Backpressure prevent OOM

A common mistake is creating an **unbounded queue**. If producers outrun workers for hours, an unbounded broker fills RAM/disk until the entire cluster crashes with OOM—losing **every** buffered job.

Instead, enforce a **bounded queue capacity**. Once depth hits its high-water mark, the broker pushes **Backpressure** upstream: Ingest API returns `429 / 503 Retry-After` fast so the pipeline stays alive and drains steadily.

watch:Fail fast at the edge with 503 + Retry-After rather than letting an unbounded queue eat all memory and collapse the whole platform.

Bounded QueueBackpressureFast Load Shedding
STEP 05 · TRADE-OFFJump to step →

Priority queues: isolate checkout from analytics

If password resets, checkout receipts, and millions of clickstream analytics events all share **one FIFO queue**, a marketing analytics burst delays password resets by 20 minutes (**head-of-line blocking**).

Splitting into **Dedicated Priority Queues** (`High: Checkout`, `Low: Analytics`) with separate worker pools guarantees critical user flows stay sub-second even when low-priority queues back up.

good:Separate queues per traffic class (critical vs bulk) is far simpler and safer than complex in-queue priority heaps.

Head-of-Line BlockingPriority QueuesBulkhead Isolation
STEP 06 · TECHNIQUEJump to step →

Delivery guarantees: ACK after work finishes

If a broker deletes a message the moment it hands it to a worker (**At-Most-Once**), any worker crash permanently loses the order. Production queues default to **At-Least-Once delivery**.

The broker hides the message temporarily while the worker runs, and only deletes it after receiving an explicit **ACK**. If the worker crashes before ACKing, the message reappears for another worker.

idea:True “Exactly-Once” delivery across a network is impossible by itself—real systems achieve effectively-once by combining At-Least-Once + Idempotent Consumers.

At-Least-Once DeliveryExplicit ACKRedelivery
STEP 07 · PROBLEMJump to step →

Visibility timeout expiry causes duplicate work

When Worker A leases a payment job, the broker starts a **30-second Visibility Timeout**. If Worker A suffers a slow GC pause or network hiccup taking **35 seconds**, the broker assumes Worker A died.

At second 30, the broker hands the **exact same message** to Worker B! Both workers now charge the customer’s credit card—**a double-charge bug**.

watch:Never rely solely on tuning visibility timeouts to prevent duplicates—network stalls will ALWAYS occasionally outlive any timeout.

Visibility TimeoutLease ExpiryDuplicate Execution
STEP 08 · SOLUTIONJump to step →

Make retries safe with Idempotency Keys

Every order message carries a deterministic **Idempotency Key** (e.g., `charge:order_88412`). Before charging the card, each worker atomically checks an **Idempotency Store** (Redis `SET NX` or Postgres `UNIQUE` constraint).

When Worker B receives a duplicate retry, the Idempotency Store flags it as **already processed**—Worker B skips the charge, ACKs the message, and guarantees **effectively-once** billing.

good:Idempotency turns messy network retries into a complete non-event—every critical queue consumer should be idempotent by design.

Idempotency KeySET NX DeduplicationEffectively-Once Processing
STEP 09 · SOLUTIONJump to step →

Isolate Poison Pills with a Dead-Letter Queue

One malformed JSON message (a **Poison Pill**) crashes every worker that tries to parse it. Under infinite retries, it gets re-queued thousands of times—burning 100% of your worker fleet and blocking healthy orders.

Configure a **maxReceiveCount = 3** redrive policy: after 3 failed attempts, the broker moves the poison pill into a separate **Dead-Letter Queue (DLQ)** for engineer inspection and alerting while main traffic sails on untouched.

good:Always attach a CloudWatch/Prometheus alert to DLQ depth > 0—a Dead-Letter Queue nobody monitors is just a silent black hole.

Poison PillDead-Letter Queue (DLQ)Max Receive Count
STEP 10 · TECHNIQUEJump to step →

Zero lost events with the Transactional Outbox

Consider this subtle dual-write bug: Checkout commits an order to Postgres, then crashes **1 millisecond later** before publishing `OrderCreated` to the Message Queue. Now the customer paid, yet no shipping event was ever sent!

The **Transactional Outbox** solves dual-write races: write the Order row AND an `outbox_events` row inside the **exact same ACID DB transaction**. A background **Outbox Relay** tails that table and publishes reliably to the queue.

idea:Either both the order and its outbox event commit together, or neither does—eliminating dual-write inconsistency without slow 2-Phase Commit.

Dual-Write ProblemTransactional OutboxCDC / Outbox Relay
STEP 11 · RECAPJump to step →

Resilient async queue pipeline blueprint

Production async pipelines combine five interlocking safeguards: **Transactional Outbox** (no lost events), **Bounded Queue** (no OOM), **Competing Consumers** (parallel scale), **Idempotency Keys** (safe retries), and **Dead-Letter Queues** (poison-pill isolation).

Trigger a flash-sale burst while killing Worker 1 below to see the complete resilient pipeline absorb chaos without losing a single order.

good:Decouple spikes with bounded queues, design every consumer to be idempotent, and always route repeated failures to a monitored DLQ.

Async Pipeline BlueprintOutbox + IdempotencyDLQ Isolation

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.