Course contents

07. Messaging and Event-Driven Systems Lesson 2 of 10

Message Queues

Move slow work onto a queue: see bursts absorbed, crashed workers redelivered, duplicates from at-least-once delivery, and dead letter queues.

15 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A queue lets the producer answer immediately while consumers do the work later, at their own pace.
  • Queues smooth bursts; a sustained gap between arrivals and processing still grows the backlog.
  • Consumers acknowledge after processing; unacknowledged messages come back after the visibility timeout.
  • That makes delivery at-least-once: duplicates happen, so consumers must be idempotent.
  • Cap redeliveries and move poison messages to a dead letter queue that someone monitors.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A message queue is a buffer between programs. A producer puts a message on the queue ("send the confirmation for order 123") and moves on. One or more consumers (workers) take messages off the queue, do the work, and acknowledge each message when they are done, which removes it for good. Amazon SQS, RabbitMQ, Azure Service Bus and many job frameworks work this way.

Why it exists

When one service calls another synchronously, the caller waits for all the callee's work and fails when the callee fails. That is fine for work the user needs right now, and wasteful for work that can happen a moment later: sending emails, resizing images, generating invoices, calling slow third parties. A queue takes that work out of the request path. The producer stays fast and available even when consumers are slow, busy or down, and consumers can be scaled independently.

How it works

Publish. The producer sends a message and gets a quick confirmation that the queue stored it. From then on the queue is responsible for it.

Consume and acknowledge. A consumer receives a message. The queue does not delete it yet; it hides it for a visibility timeout. If the consumer finishes and acknowledges in time, the message is deleted. If the consumer crashes, or takes longer than the timeout, the message becomes visible again and is delivered to another consumer.

At-least-once delivery. Acknowledging after processing means a message is never lost because a worker died, but it can be processed more than once: a worker might finish the work and crash before its acknowledgement arrives, or a slow worker might still be running when the message is redelivered. Duplicates are a normal outcome, not a bug in the queue. Consumers must be idempotent: processing the same message twice has the same effect as once (record processed message or business ids, use upserts, pass idempotency keys to payment providers).

Retries and dead letters. A message that fails is delivered again. To stop a "poison" message that can never succeed from being retried forever, the queue counts deliveries; after a maximum it moves the message to a dead letter queue (DLQ) for inspection and repair.

Backlog. If messages arrive faster than consumers process them, the backlog grows. During a short burst that is the point: the queue holds the peak and consumers catch up afterwards. If the gap persists, messages get older and older until the queue's limit is reached.

When to use it

  • Work the caller does not need to finish before it answers: notifications, media processing, reports, syncing to other systems.
  • Smoothing spiky traffic so consumers can be sized for the average rather than the peak.
  • Isolating a request path from a slow or unreliable dependency.
  • Distributing work across a pool of workers that can scale with the backlog.

When not to

  • When the user needs the result in the response (a login check, the page they asked for).
  • When strict ordering across all messages is required and you cannot partition by key.
  • For simple, fast, reliable calls where a queue only adds latency, infrastructure and eventual consistency.

Trade-offs

Choice You gain You pay
Queue instead of a synchronous call Fast, available producer; independent scaling Eventual completion, duplicates, harder debugging
Long visibility timeout Fewer duplicates from slow work Slower recovery after a consumer crash
Short visibility timeout Fast redelivery after crashes Duplicates whenever work runs long
High max deliveries Survives longer transient outages Poison messages occupy workers longer
Many parallel consumers Throughput No global ordering

Alternatives

  • Synchronous calls with timeouts, retries and a circuit breaker: simpler when the caller needs the answer.
  • Publish/subscribe: one event delivered to many independent subscribers, instead of one task to one worker.
  • Event streaming (Kafka, Kinesis): an ordered, replayable log consumed by offset; consumers track their position rather than acknowledging individual messages.
  • A jobs table polled by workers: fine at small scale and transactional with your data, but polling and locking get costly.

Failure modes

  • Growing backlog: consumers cannot keep up; message age rises until users notice (emails hours late) or the queue fills. Alert on the age of the oldest message, not only the count.
  • Duplicates: crashes, network retries and short visibility timeouts all cause redelivery. Non-idempotent consumers send two emails or charge twice.
  • Poison messages: a malformed message fails every time; without a delivery limit it is retried forever.
  • Ignored DLQ: messages pile up in the dead letter queue and nobody looks. A growing DLQ is an incident.
  • Lost messages on the producer side: the database commit succeeds but the publish fails (or the reverse). The transactional outbox pattern fixes this.
  • Out-of-order processing: parallel consumers and redeliveries reorder messages.

In production

Keep messages small (ids rather than whole objects) and versioned. Make every consumer idempotent. Set the visibility timeout above the slowest normal processing time and extend it for long jobs. Cap deliveries, attach a DLQ, and alert on DLQ size and on the oldest message's age. Scale consumers on backlog. Use the transactional outbox when a message must be published if and only if a database change commits.

Common misconceptions

  • "A queue adds capacity." It buffers. Throughput is still set by the consumers.
  • "The queue guarantees exactly-once processing." Delivery is at-least-once; exactly-once effects come from idempotent consumers.
  • "Messages are processed in order." Not with several consumers or redeliveries, unless you partition by key and process each partition sequentially.
  • "Once it's on the queue, it's handled." It is stored. Whether it ever succeeds depends on retries, the DLQ and someone watching it.

Interview angle

Use a queue whenever a design has slow or non-essential side effects, and say why: latency, isolation, burst absorption. Then expect questions on delivery guarantees (at-least-once and idempotency), visibility timeouts and acknowledgement, retries and dead letters, ordering, backpressure when consumers fall behind, and how producers publish reliably (outbox). Quantifying the backlog ("40 msgs/s in, 26 out, so it grows by 14/s; we autoscale workers on queue age") stands out.

Model assumptions

The simulation is a simplified model, not a benchmark. A confirmation takes about 300 ms to send (lognormal, cv 0.3; cv 1.5 in the duplicates step). The synchronous Email Service has 8 workers and room for 10 waiting calls. With the queue, two workers with 4 slots each consume messages round robin; a worker holds a slot for each unacknowledged message until it is acknowledged or its visibility timeout expires. The visibility timeout is 2 s (1 s in the duplicates step), and after 3 deliveries a message moves to the dead letter queue. A failed send is simply not acknowledged. Orders succeed as soon as the message is stored. Message accounting: each message ends in one outcome, counted once: delivered (first successful acknowledgement), dead-lettered (moved to a dead letter queue after its last delivery) or dropped (it ran out of deliveries with no dead letter queue connected, or a subscription was full or down when its copy arrived). Redelivered (a delivery that came back after its timeout) and duplicates (a message processed again after it had already been processed) are not outcomes: they count extra deliveries of messages that are counted once above. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. The shopper waits for the email

    When a shopper places an order, the Orders API saves it and then calls the Email Service to send the confirmation, waiting for the answer before replying.

    Rendering the PDF and talking to the email provider takes about 300 ms. The shopper waits for all of it, even though nobody needs the email to be sent before the order page loads.

    Scene: Shoppers call the Orders API, which calls the Email Service and waits for it. Requests take over 300 ms and all succeed.

    Key idea: In a synchronous call, the caller’s latency includes all the work of everything it calls.

  2. 2. A sale doubles the orders

    A flash sale brings 40 orders per second. The Email Service can send about 26 per second. Its small waiting line fills and it starts rejecting calls.

    Because the API waits for the email, orders fail too: the shopper sees an error for an order that could have been saved. A slow, non-essential step has become a hard dependency.

    Scene: At 40 orders per second the Email Service is saturated and rejects calls, so many orders fail and latency rises.

    Key idea: Synchronous coupling lets the slowest component set the capacity and the availability of the whole request.

  3. 3. Put a queue in between

    The API now puts a message on a queue ("send confirmation for order 123") and replies at once. Separate workers take messages off the queue and send the emails at their own pace.

    Orders are fast again and none fail. But two workers can only send about 26 emails per second, so at 40 orders per second the backlog grows: emails go out later and later. A queue absorbs bursts; it does not add capacity.

    Scene: The Orders API puts a message on the Email Queue and answers immediately. Workers 1 and 2 are fully busy; the queue’s backlog grows because messages arrive faster than they are processed.

    Key idea: A queue decouples the producer from the consumer in time: the producer is fast, the work happens later.

  4. 4. Absorbing a burst

    Normally there are about 10 orders per second, comfortably below what the workers can send. Half a second in, a 2-second burst of 50 orders per second arrives.

    The queue fills up during the burst and drains afterwards. Shoppers never notice; emails are delayed by a few seconds at most. That is what queues are best at: smoothing peaks so consumers can be sized for the average, not the peak.

    Scene: A burst of 50 orders per second fills the queue to dozens of messages; when the burst ends the workers drain it. No order fails.

    Key idea: Size consumers for average load plus headroom; let the queue hold the peaks. Watch the queue depth and the age of the oldest message.

  5. 5. A worker dies mid-message

    One second in, Worker 1 crashes while it is sending emails. Those messages are not lost: a worker must acknowledge a message after finishing it, and until then the queue only hides it.

    After the 2-second visibility timeout the queue makes the unacknowledged messages visible again and Worker 2 picks them up. If Worker 1 had actually sent an email just before dying, that customer now gets it twice.

    Scene: Worker 1 goes offline. Its unacknowledged messages reappear on the queue after the visibility timeout and Worker 2 processes them.

    Key idea: Acknowledge after processing, not before. Unacknowledged messages come back: at-least-once delivery.

  6. 6. Slow work, delivered twice

    Worker 1 is back. To recover faster from crashes, someone lowered the visibility timeout to 1 second. Then the email provider gets erratic: most sends still take about 300 ms, but a few take seconds. Those exceed the timeout, so the queue assumes the worker died and delivers the message again.

    Both copies get processed: the customer receives duplicate emails. Queues like this guarantee *at least once*, never *exactly once*. The consumer has to be idempotent, for example by recording the order id it already sent and skipping repeats.

    Scene: Some sends take longer than the visibility timeout. The queue redelivers those messages while the first attempt is still running, and both attempts complete: duplicates.

    Key idea: Duplicates are normal with at-least-once delivery. Make consumers idempotent and set the visibility timeout above the slowest normal processing time.

  7. 7. Messages that keep failing

    Send times and the 2-second timeout are back to normal, but the email provider now rejects half of all sends. A failed send is not acknowledged, so the message comes back after the visibility timeout and is tried again. Meanwhile it holds a worker slot, so the backlog grows.

    Retrying forever would clog the queue. After 3 deliveries the queue moves the message to a dead letter queue (DLQ), where it waits for a person or a repair job instead of blocking everything else. An alert on DLQ size tells you something is wrong.

    Scene: Half of all sends fail. Failed messages are redelivered; those that fail three times move to the Dead Letters queue, which slowly fills.

    Key idea: Cap redeliveries and park failing messages in a dead letter queue. Monitor it; a growing DLQ is an incident.

  8. 8. What a queue gives you, and costs

    The provider is healthy again. A queue lets the API answer fast, survive slow or failed consumers, and smooth bursts. In exchange you get eventual processing, duplicates to handle, ordering that is not guaranteed across consumers, and a backlog to monitor.

    Keep payloads small (an order id, not the whole order), make consumers idempotent, alert on queue age and DLQ size, and only use a queue for work the caller does not need to finish before it answers.

    Scene: The API publishes to the Email Queue, two workers consume it and failed messages would go to the Dead Letters queue. Everything is healthy.

    Key idea: Use a queue when the work can happen later. Design every consumer for at-least-once delivery.