0% completed
Message Queue
On This Page
What a Message Queue Is
The Flash Sale With a Queue
The Queue Must Be Durable
Taking, Acknowledging, and Redelivering
Messages That Fail Every Time
Depth and Age: Watching the Queue
Many Workers and Message Order
Two Kinds of Queue
When to Use a Message Queue
Check Yourself
Summary
At 10:00 AM, the store opened a sale it had announced for weeks: 10,000 signed editions of a bestselling novel, plus 30 percent off everything else for one hour. On a normal day, the store receives about 200 orders per second. One second after 10:00, the rate passed 5,000 orders per second, and it stayed there for two minutes.
The order pipeline was the one from the Request-Response lesson. Checkout called inventory, payment, the orders database, and fulfillment while the buyer waited. Together, those services can complete about 400 orders per second.
The limit is 400 and not 800 because heavy load slows the payment and database calls. Each order then holds a checkout thread for about 500 ms, and 200 threads finish 200 ÷ 0.5 = 400 orders per second. Above that rate, every checkout thread was soon busy, and new requests waited until they timed out.
In two minutes, about 600,000 orders arrived (5,000 × 120), and the pipeline completed at most 48,000 (400 × 120). The other 552,000 attempts, 92 percent, ended in an error or a spinner that never stopped. Adding servers could not help in time. New servers take about two minutes to start, and the whole spike lasted only two minutes.
The store did not need a faster pipeline. It needed a place to keep each order until the pipeline could process it. This lesson covers that place: how a message queue works, what it promises about delivery, how to watch it, and when to use it.
What a Message Queue Is
A message queue is a list that holds tasks until a program is ready to take them. One program adds a message to the end of the list, and another program removes messages from the front. The program that adds messages is the producer, and the program that takes them is the consumer. The server that stores the list between them is the broker. RabbitMQ, Amazon SQS, and Kafka are common brokers.
The name describes both parts. A message is a small record of work to do, like "process order 1042 for $40," plus extra fields like a message ID and a trace ID that helps with debugging. A queue is a line in which items wait their turn.
The key idea is that the producer does not wait for the consumer. It hands the message to the broker, the broker confirms that the message is stored, and the producer continues. This is called asynchronous communication: the work happens later, at a time the consumer chooses.
Applied to the store, the API becomes the producer. It checks the request, writes one message, "process order 1042," to the queue, and answers the buyer in about 10 ms. The consumers are workers, copies of one program that run on many servers. They take orders from the queue and run the old pipeline: inventory, payment, the database, and fulfillment. When a worker finishes, the store emails the buyer the final confirmation.
The Flash Sale With a Queue
The queue changes what happens when orders arrive faster than the pipeline can process them. Orders that cannot be processed yet wait in the queue as a backlog, the messages stored but not yet taken. Nobody receives an error.
The chart replays the flash sale with the queue in place. From 10:00 to 10:02, 5,000 orders arrive each second and the workers process 400. The backlog grows by 4,600 per second and reaches 552,000 orders at 10:02. Every one of those buyers has already seen "Order received."
The backlog also gives the team time to add workers. Without a queue, new servers needed two minutes to start, and by then the spike was over and its orders were lost. With a queue, the orders wait for the new servers.
By 10:02, the store runs enough workers to process 1,200 orders per second. That is the limit, because the payment provider accepts at most 1,200 charges per second from the store.
The right half of the chart shows the result. Traffic returns to 200 orders per second, the workers process 1,200, and the backlog shrinks by 1,000 per second. It reaches zero after 552 seconds, at about 10:11. The last order of the spike waits behind 552,000 others, which takes 552,000 ÷ 1,200 = 460 seconds, a little under eight minutes.
This is the trade the queue makes. The buyer gets a fast answer, and the work is allowed to finish later. The words "Order received" also mean something new. "Order received" says that the store has the order, not that the card was charged. A buyer who ordered a signed edition after the 10,000th one was taken receives an email that says it sold out and that the card was not charged.
The Queue Must Be Durable
The team's first idea was a list in each API server's memory, which needs no new system. That list exists only while the server runs. If a server with 30,000 orders in memory restarts during a deployment, those orders are gone, and their buyers have already been told "Order received."
A durable queue writes each message to disk before it confirms, and it usually copies the message to two or three broker servers. The API answers the buyer only after the broker confirms the write. So once the buyer sees "Order received," the order exists on more than one disk.
Taking, Acknowledging, and Redelivering
A message is deleted only after the work is done, not when a worker takes it. The broker follows three steps. When a worker takes a message, the broker hides it from other workers for a fixed time, called the visibility timeout, for example 30 seconds. When the worker finishes, it sends an acknowledgment, a short note that says "done," and the broker deletes the message. If no acknowledgment arrives before the timeout ends, the broker makes the message visible again, and another worker takes it.
The diagram follows order 1042 through a crash. Worker A charges the buyer $40, and then its server stops before it can acknowledge. Thirty seconds later, the queue gives the same order to Worker B. Worker B has no way to know that the card was already charged, so it sends the same charge again.
This behavior is called at-least-once delivery: every message is processed one or more times, and it is never lost. Most queues promise this, because the broker cannot tell a worker that crashed from a worker that is slow. Deleting messages on delivery would lose order 1042 instead, and losing an order is worse than repeating one.
A repeat is safe only if the consumer is idempotent, which means processing the same message twice has the same effect as processing it once. In the diagram, Worker B's charge carries the order ID as its idempotency key. The payment service has seen key 1042 before, so it returns the first result and does not charge again. The Idempotency lesson covers how to build these checks.
Messages That Fail Every Time
Redelivery fixes temporary failures, like a worker crash or a payment timeout. Some messages, however, fail on every attempt. During the sale, one order arrived with a postal code that the fulfillment code could not read. Each attempt threw an error, and the order came back 30 seconds later. A message that no consumer can ever process is called a poison message.
Without a limit, a poison message returns forever and uses a worker on every attempt. The fix is a maximum number of attempts, for example five.
After the fifth failure, the broker moves the message to a separate queue, called a dead-letter queue, and an alert tells an engineer. The engineer repairs the address, and the order goes back into the main queue. The Dead Letter Queue lesson covers this process in detail.
Depth and Age: Watching the Queue
With a queue in place, a slow pipeline makes orders wait instead of fail. Two numbers measure that waiting.
Queue depth is the number of messages waiting. At 10:02 during the sale, the depth was 552,000. A growing depth means producers are faster than consumers.
Backlog age is the age of the oldest unprocessed message. At 10:02, the oldest waiting order had arrived at about 10:00:10, so the backlog age was about 110 seconds. Age measures what the buyer experiences: how long the slowest order has waited for its confirmation.
The store uses both numbers to decide when to add workers. It adds workers when the depth is more than one minute of work, which is 24,000 orders at 400 per second. During the sale, the depth passed that limit about five seconds after 10:00.
Age grows only one second per second, so it reacts later. However, it shows directly whether buyers wait too long. The store also adds workers when the oldest message is more than 60 seconds old, and it alerts an engineer at 5 minutes. An age that keeps growing means the workers are too few, or they are stuck.
Many Workers and Message Order
Many workers take messages from the same queue, and each message goes to exactly one of them. This arrangement is called competing consumers. To process faster, the store adds workers, and no producer needs to change.
Competing consumers have one cost: they do not keep messages in order. Two messages that enter the queue one after the other can go to two different workers. A slow worker can finish the first after a fast worker finishes the second. Redelivery also changes the order, because a message that failed returns 30 seconds later, behind messages that arrived after it.
Usually the processing sequence does not matter, because each order is independent. It matters when two messages describe the same thing, like a charge and a refund for one order. For that case, the queue is split into lanes called partitions, and every message for one customer goes to the same partition, chosen by customer ID. One worker processes each partition, in order. The Partitioned Consumption lesson explains how this works.
Two Kinds of Queue
Brokers handle a processed message in one of two ways, and that choice decides what else the queue can do.
The top panel shows a classic queue, the kind used so far in this lesson. A worker takes message 5 and acknowledges it, and the broker deletes it. RabbitMQ and Amazon SQS work this way.
The bottom panel shows a log, an append-only list in which new messages are only added at the end and nothing is changed. Kafka works this way. Messages stay for a fixed time, called retention, here seven days, whether or not anyone has read them. Each consumer keeps its own position in the log, called an offset. Fulfillment has read up to position 8, and analytics has read up to position 3.
Because the messages stay, a consumer can move its position back and read them again, which is called replay. If a bug in analytics produced wrong totals yesterday, the team fixes the code and replays the last day. The distance between the newest message and a consumer's position is called consumer lag. In the diagram, fulfillment is 1 message behind and analytics is 6 behind. Lag is the log's version of queue depth.
| Classic queue | Log | |
|---|---|---|
| After processing | The message is deleted | The message stays until retention ends |
| Who reads a message | One worker | Every consumer, each at its own position |
| Reading again | Not possible | Move the offset back and replay |
| Order | Not kept across workers | Kept within each partition |
| Examples | RabbitMQ, Amazon SQS | Kafka |
| Fits | Independent jobs, like sending one email | A history of facts that several readers use |
The store's order pipeline works with either kind. A log fits better when more than one team needs the same orders, which is where the next lesson begins.
When to Use a Message Queue
The module's question applies here too: does the caller need the answer before it can continue? A queue fits when the answer is no. The caller needs to know only that the work is stored, and the result can arrive later.
| Connection | Does the caller need the answer to continue? | Pattern |
|---|---|---|
| Phone to API: accept the order | Yes, but only "received" | Request-response, then a queue |
| API to the order workers: process the order | No, the buyer gets an email later | Message queue |
| Checkout to fulfillment: schedule shipping | No, the buyer never sees a shipping plan | Message queue |
| Checkout to email: send a receipt | No, a receipt can arrive a minute later | Message queue |
| Product page to price service: show the price | Yes, the page cannot show without it | Request-response |
A queue is a poor fit in three cases. If a person waits on the screen for the result, like a search or a login, the queue adds delay with no benefit. If the producer needs a value from the result to continue, it must wait anyway. And if several teams need the same fact, a single classic queue gives each message to only one of them, which the Publish-Subscribe lesson addresses next.
Check Yourself
Q1. For the next sale, the team expects 6,000 orders per second for one minute. Workers process 1,200 orders per second from the start, and normal traffic after the spike is 200 per second. How deep is the queue at the end of the spike, and when is it empty again?
<details> <summary>Show answer</summary>During the spike, the backlog grows by 6,000 minus 1,200 = 4,800 orders per second, so after 60 seconds it holds 288,000 orders. After the spike, it shrinks by 1,200 minus 200 = 1,000 per second, so it is empty after 288 seconds, a little under five minutes. The last order of the spike waits behind 288,000 others, which takes 288,000 ÷ 1,200 = 240 seconds.
</details>Q2. A worker charges a buyer's card for order 5518, and then its server stops before it sends the acknowledgment. What happens to the order, and what prevents a second charge?
<details> <summary>Show answer</summary>The broker receives no acknowledgment, so when the 30-second visibility timeout ends, it makes the message visible again, and another worker takes it. This is at-least-once delivery working as designed: the order is not lost. The second worker sends the charge with the order ID as its idempotency key, so the payment service returns the first result instead of charging again.
</details>Q3 (incident). During the sale, a buyer placed an order and canceled it 40 seconds later. The charge message failed once on a payment timeout and returned to the queue 30 seconds later. Meanwhile, another worker took the refund message, found no charge, and acknowledged it. Only then did the charge run. The buyer paid for a canceled order. What went wrong, and what should change?
<details> <summary>Show answer</summary>The refund was processed before its charge. With competing consumers, the two messages went to different workers, and the redelivery put the charge behind the refund. The fix is to partition the queue by customer ID, so one worker processes all of this buyer's messages in the order they arrived. The refund handler should also never acknowledge a refund for a charge it cannot find. It should fail, so the message is retried later.
</details>💡 In the interview: When a step does not need to finish before you answer the user, say so and put a queue in front of it. A strong answer sounds like this: "The API validates the order, writes it to a durable queue, and returns 'received' in milliseconds. Workers process orders at a steady rate, so a spike becomes backlog instead of errors. Delivery is at least once, so every consumer is idempotent on the order ID. After five failed attempts, a message goes to a dead-letter queue. We add workers based on backlog age." Expect a follow-up about ordering. Answer that competing consumers do not keep order, and partition by the key whose order matters, like the customer ID.
Summary
| <span style="white-space:nowrap">Problem</span> | During a flash sale, orders rose from 200 to 5,000 per second for two minutes, but the synchronous pipeline completed only 400 per second. Of about 600,000 orders, 552,000 attempts, or 92 percent, ended in an error or a spinner that never stopped. |
| <span style="white-space:nowrap">Mechanism</span> | The API, as producer, writes each order to a durable queue on the broker and answers the buyer in about 10 ms. Workers take messages, and the broker deletes one only after an acknowledgment, or offers it again when the visibility timeout ends. The 552,000-order backlog was empty by about 10:11. |
| <span style="white-space:nowrap">Costs</span> | Delivery is at-least-once, so every consumer must be idempotent, and a poison message goes to a dead-letter queue after five attempts. Competing consumers do not keep messages in order, so related messages need partitions by customer ID. "Order received" no longer means the card was charged. |
| <span style="white-space:nowrap">When to skip</span> | Skip it when a person waits on the screen for the result, like a search or a login, or when the producer needs a value from the result to continue (use request-response). When several teams need the same fact, a classic queue gives each message to only one of them (use publish-subscribe). |
| <span style="white-space:nowrap">30-second answer</span> | The API validates the order, writes it to a durable queue, and tells the buyer within milliseconds that the order is received. Workers process orders at a steady rate, so a spike becomes backlog instead of errors. Every consumer is idempotent on the order ID, a message goes to a dead-letter queue after five failed attempts, and we add workers based on backlog age. |
Flashcards Review
What is a message queue?
Reading Progress
0%
On This Page
What a Message Queue Is
The Flash Sale With a Queue
The Queue Must Be Durable
Taking, Acknowledging, and Redelivering
Messages That Fail Every Time
Depth and Age: Watching the Queue
Many Workers and Message Order
Two Kinds of Queue
When to Use a Message Queue
Check Yourself
Summary