Course contents · Lesson 9 of 19

What Is a Message Queue? Why Systems Wait in Line

Scaling and Capacity · Lesson 9 of 19 · 10 min Engineer

You tap "Place order" in a shop app and the confirmation appears in a second, yet the receipt email arrives a minute later. The shop did not send it while you waited: it left a note for another program, and the note waited in line. So what is a message queue, and why do reliable systems make work wait? This lesson covers the parts, the guarantees and what SREs watch.

Producers, queues and consumers

A message is a small piece of data that describes one job, such as {"order": 1234, "task": "send receipt"}. A producer is the program that sends messages, like the waiter. A queue holds them in line until they are taken, like the rail. A consumer, or worker, takes a message and does the job, like a cook.

The queue lives on a message broker, a server that stores messages, usually on disk or on several servers so a crash does not lose them, and hands them out. Producers talk only to the broker, never to workers, so neither side needs to know whether the other is running.

This makes the work asynchronous, as with the replicas in lesson 7: the producer gets a quick "received", and the work happens afterwards. Order is often kept only roughly: standard queues in Amazon SQS, the hosted queue service of Amazon Web Services (AWS), promise only best-effort ordering.

Why queues help: decoupling, spikes and retries

The first gain is decoupling: separating two services so that one can be slow, busy or down without stopping the other. If the email service fails for ten minutes, orders still go through and the receipts go out once it recovers.

In the timeline's top lane, the client, the app or browser making the request, waits for the whole job. In the bottom lane the server only adds a message and replies at once with 202 Accepted, the HTTP status for "received, not finished yet". Notice who is left waiting.

Timeline with illustrative times for a photo resize that takes 6 seconds. In a direct, synchronous call, the client waits for the reply for all 6 seconds while the server resizes the photo, and the reply comes at 6 seconds. In a queued job, the server replies 202 Accepted at once and the client is free to carry on; the message waits its turn in the queue briefly, then a worker resizes the photo and is done at about 6.6 seconds. The client's wait drops from 6 seconds to a fraction of a second, while the job still takes 6 seconds
With a queue, the client waits for a receipt, not for the job.

The second gain is absorbing spikes, short bursts of traffic well above normal. Without a queue, a burst that outruns the workers becomes slow or failed requests; with one, the line simply grows. You can then add workers, scaling out as in lesson 7, using queue depth, the number of messages waiting, as the signal.

In the illustrative chart, notice that depth keeps climbing for two minutes after workers are added, while they boot, and that every order is still processed.

Illustrative line chart of an order queue over 30 minutes. Before minute 5 almost nothing waits. A traffic spike from minute 5 to 17 brings orders faster than 2 workers can handle, so messages waiting climb steadily. At minute 11, 4 more workers are added, 6 in total, but depth keeps rising to a peak of about 5,000 at minute 13, when the new workers are running. It then drains in about 8 minutes, to almost zero by minute 21, because 6 workers outpace arrivals. A note says nothing is lost: every order waits its turn and is processed later
A queue turns a spike into a delay you can see and drain, not errors.

Draining time is the messages waiting divided by how many more per second workers finish than arrive: illustratively, 5,000 waiting with workers 10 per second ahead takes 500 seconds, about 8 minutes.

The third gain is retries, trying a failed job again: a message stays queued until a worker confirms it is done, so if a worker crashes, another gets the job.

At least once: why workers must be idempotent

A delivery guarantee is a queue's promise about how many times each message reaches a worker. Most queues promise at-least-once delivery: every message is delivered, but now and then more than once. That includes SQS standard queues and, when workers confirm each job, RabbitMQ, a popular open-source broker.

Duplicates come from a gap: a worker finishes the job, then crashes, or is too slow, before telling the queue. The queue cannot tell "done but not confirmed" from "never done", so it plays safe and delivers the message again. Some systems offer stronger modes, with limits, but most designs expect duplicates.

So workers should be idempotent: handling a message twice gives the same result as handling it once. Setting an order's status to "shipped" is idempotent: doing it again changes nothing. Charging a card or adding 10 points to a balance is not: a duplicate does it twice.

The usual fix is an idempotency key, a unique ID carried in each message, such as the order number. The worker skips any message whose key is already marked done. Ideally it marks the key in the same database transaction as the result, a group of changes saved together or not at all, so a crash cannot save one without the other.

When jobs fail: acks, backoff and dead letters

An acknowledgement, or ack, is the worker telling the queue that a job is finished; only then is the message deleted. Until then it is hidden from other workers but kept, like a ticket a cook sets aside and bins only when the dish goes out. In RabbitMQ, if the worker's connection drops first, the message is redelivered. In SQS, it reappears after the visibility timeout, 30 seconds by default.

So ack only after the work: a worker that acks on receipt and then crashes loses the job for good, which is called at-most-once delivery.

Many failures are brief, such as a database restarting, so retrying usually works. Retrying instantly tends to fail again and loads a struggling service, so retries use exponential backoff: each wait is longer than the last, such as 1, 2, 4, then 8 seconds. Jitter, the random spread from lesson 8, stops workers retrying in step. Depending on the queue, the growing wait is a setting or comes from the worker's code.

A poison message, such as a malformed order, never succeeds, so it would be retried forever, wasting workers and, in strictly ordered queues, blocking everything behind it. So after a set number of tries it moves to a dead-letter queue (DLQ), a separate queue where failed messages wait for a person to inspect, fix and send back. SQS sets the limit with maxReceiveCount; RabbitMQ routes such messages through a dead-letter exchange.

In the flowchart, notice that the dead-letter queue is not a bin: nothing is silently lost.

Flowchart. A producer sends a job to a queue, which holds messages in line. A worker takes one job at a time and asks: did the job work? Yes leads to an ack, and the queue deletes the message. No leads to a second question: has it failed 5 times? Not yet leads to retry later, waiting 1, 2 and then 4 seconds, and a dashed arrow puts the message back in the queue. Yes moves it to the dead-letter queue, where it is kept aside, not lost, and a human is alerted to inspect it, fix the cause and resend it. A footer gives example settings: up to 5 tries, each wait doubling, and ack only after the job is done
Retries absorb brief failures, and the dead-letter queue catches the message that would fail forever.

What SREs watch: queue depth and message age

Rising queue depth means messages arrive faster than workers finish them. A short rise in a spike is normal; depth that keeps rising for many minutes means the workers cannot catch up.

Message age, how long the oldest waiting message has been queued, is closer to what users feel. It is the freshness of lesson 5 applied to a queue: a receipt waiting 20 minutes is late, whatever the depth. Teams often alert when the oldest message passes an age their SLO allows, and when anything lands in the dead-letter queue.

SQS reports both in Amazon CloudWatch, AWS's monitoring service, as ApproximateNumberOfMessagesVisible and ApproximateAgeOfOldestMessage. RabbitMQ's management UI shows each queue's messages ready and unacknowledged. In both, each message goes to one worker and is deleted after its ack.

Apache Kafka is related but different. It is a log: messages are appended to the end and kept for a set retention period, read or not. Each group of consumers tracks its own position, called an offset, so many groups can read the same messages. There you watch consumer lag: how far a group's offset is behind the newest message.

Check yourself

A receipt worker acks each message on receipt, then sends the email. What happens if it crashes mid-job, and what should change?

That email is never sent, because the queue deleted the message at the ack. Acking after sending means a crash leads to redelivery, not a lost job.

Some customers are charged twice for one order, though the worker charges once per message. What is the likely cause, and the fix?

At-least-once delivery handed the same message over twice, perhaps after a worker crashed before its ack. Checking the order's idempotency key before charging makes the duplicate harmless.

Queue A holds 50,000 messages, the oldest 4 seconds old. Queue B holds 200, the oldest 30 minutes old. Which worries you more, and why?

Queue B: its users are already 30 minutes late, so its workers are stuck, down or retrying a poison message. Queue A is busy but keeping up, since nothing waits long.

Go deeper