Message Queue — System Design

A message queue is a line of messages between a producer (which puts work in) and a consumer, or worker (which does the work). The queue separates the two…

A restaurant cashier doesn't wait for the fried rice to be ready. The cashier pins the order slip on the rail and serves the next customer right away. A cook takes the slip, cooks, then crosses it out. If the cook faints before crossing it out, the slip is still on the rail, and another cook will cook it again.

In software, that rail of slips is called a message queue: a line of messages between two parts of a system. One part puts work in, the other part takes it and does it later, and neither waits for the other.

Producer, queue, consumer

In the restaurant picture, the cashier is the producer, the slip is a message, the rail is the queue, the cook is a consumer, and crossing out the slip is the ack.

What goes on a queue is work that may finish later. When a user signs up, checking the email format and saving the user's data to the database must finish in that request, because the user needs to know the result. The welcome email can be sent through a queue: the user doesn't need to wait for the email to go out before continuing.

Why a queue: decoupling and absorbing spikes

The main problem a queue solves is decoupling (separating the two parts): the producer doesn't have to wait for the consumer to finish. The Lab's example model: at 10:00, the ticket war, 40 buyers pay at once. TicketTune's API has 8 API workers, which are the processes that serve requests. They are not the same as the workers that take messages from the queue. With no queue, each request holds one API worker for 505 ms. So the 40 requests run in 5 rounds of 8:

No queue With a queue
The payment request makes the e-ticket inside the request: 5 + 500 ms puts a job on the queue: 5 ms
40 buyers at once 5 rounds x 505 ms: the 40th buyer waits 2,525 ms all answered in 5 ms
E-tickets ready with the response 2 workers x 2 a second: done in 10 s
The email fails the buyer sees a 500 error (a server error) after paying the job is quietly retried
Every worker is down (there is no separate worker) the API stays at 5 ms, jobs pile up safely on the queue

The spike of 40 orders is "absorbed" by the queue, and the workers work through it at a speed they can handle. If the workers are slow or down for a while, the messages wait safely.

Ack, visibility timeout and at-least-once

When a worker takes a message, the queue doesn't delete it right away. It only hides it for the visibility timeout, the time the worker has to finish it (10 s in the Lab; Amazon SQS defaults to 30 s). If the worker acks before that time has passed, the message is deleted. If not, the queue assumes the worker died and shows the message again for another worker.

This is what happens in the Lab when a worker dies after sending the e-ticket for order #1141, but before the ack:

Second What happens
1 a worker takes #1141, sends e-ticket number 1, then dies before the ack
1 to 11 #1141 is hidden, waiting for the visibility timeout to end
11 the timeout ends, #1141 appears again, another worker sends e-ticket number 2

The e-ticket is sent again. The message isn't lost, but it can be processed more than once. This guarantee is called at-least-once delivery: every message is surely processed, at least once. Most queues give this guarantee, because promising "exactly once" over a network that can break at any moment is very hard.

The consumer must be idempotent

Since a message can arrive twice, the consumer must be idempotent: processing the same message twice ends the same as processing it once. The way to do it: before working, first check whether the work for that orderId is already done. This code adds that check to the handle function, which is called for each job:

const IDEMPOTENT = true;
const eTickets = new Map(); // orderId -> how many e-tickets were sent

function handle(job) {
  if (IDEMPOTENT && eTickets.has(job.orderId)) {
    console.log('#' + job.orderId + ' already has its e-ticket, skip');
    return; // still acked, but nothing is sent again
  }
  sendETicket(job); // build the PDF, send the email, record it in eTickets
}

Without this check, a message that arrives twice means two e-tickets, two emails, or worse, a balance charged twice. The pattern is covered in depth in the Idempotency Design lesson.

Retries and the dead letter queue

When the work fails (an exception, an error from the code), the message goes back on the queue and is tried again. But some messages always fail, like order #1142 with the invalid email tono@. A message like that is a poison message. Retried forever, it uses a worker's time forever.

So retries get a limit. In the Lab, a message is tried at most 3 times, at seconds 1, 3 and 5: after a failure, it waits 2 seconds and is tried again. After the third try fails, it is moved to the dead letter queue (DLQ): a separate queue for messages that keep failing. The other messages keep flowing, and the ones in the DLQ wait for a human to look at them. In Amazon SQS the limit is maxReceiveCount, in Laravel php artisan queue:work --tries=3 (failures land in the failed_jobs table), in BullMQ the attempts option.

Kafka, RabbitMQ and friends

The two best-known queue programs are RabbitMQ and Kafka. In this table, a broker is a middleman for messages, retention is how long messages are kept, and replay means reading old messages again:

RabbitMQ Kafka
What it is a message broker an append-only log of events
After processing the message is deleted after the ack the message stays, by retention (7 days, say)
Replay classic queues: no; RabbitMQ Streams (since 3.9): yes yes, a consumer can reread from any position
Right for classic task queues, complex routing very high-volume event streaming

The RabbitMQ column describes classic queues. Since version 3.9, RabbitMQ also has Streams: an append-only log whose messages are not deleted when read, and a consumer can start from any offset (a position in the log) or point in time. If you already use RabbitMQ and need replay, Streams are enough. Kafka still leads for very high-volume events.

Other choices: Amazon SQS (managed by the cloud, no servers to run), and Redis with BullMQ (simple, handy if you already have Redis).

⚠️ Why e-tickets go out twice, or not at all

TL;DR: A message queue is a line of messages between a producer (which puts work in) and a consumer, or worker (which does the work). The queue separates the two (decoupling): the producer puts a message in and continues right away, and the consumer does the work when it can. In the model of the ticket app TicketTune, the API answers 40 buyers in 5 ms and the queue absorbs the spike. With no queue, the 40th buyer waits 2,525 ms. Only send work that may finish later through a queue, such as e-ticket emails or welcome emails. A message a worker takes is hidden for the visibility timeout (the time it has to finish). Without an ack (the message saying the work is done), it appears again. So delivery is at-least-once (at least once, maybe more), and the consumer must be idempotent: processing the same message twice ends the same as once. Failing messages are retried up to a limit, then moved to a dead letter queue, a separate queue for messages that keep failing. Point-to-point is for tasks (one message, one worker), pub/sub for events (news that something happened), which go to every subscriber (a consumer that signed up for them). A RabbitMQ queue deletes a message after the ack and is strong at routing (sending messages to the right place); RabbitMQ Streams can be replayed (read again). Kafka keeps a log of events that can be replayed, at very high throughput (messages a second).

⚡ The producer drops it, the consumer does it

Guess first: at 10:00, 40 buyers pay at once. The API has 8 processes that serve requests, and each request makes its own e-ticket: 5 ms + 500 ms. How long does the 40th buyer wait?

2,525 ms: the 40 requests run 8 at a time, so 5 rounds x 505 ms. With a queue, the payment request only puts a job (a message that holds work) on the queue (5 ms), so all 40 buyers are answered in 5 ms.

Meaning: A message queue is a line of messages between a producer (which puts work in) and a consumer (which does the work). The queue separates the two (decoupling): the producer puts a message on the queue and continues, the consumer does the work when it can. The queue absorbs the spike of orders.

⚡ Without an ack, the message comes back

Meaning: A message a worker (consumer) takes is only hidden for the visibility timeout, the time the worker has to finish it. If the worker dies before the ack (the message saying the work is done), the message appears again for another worker. So delivery is at-least-once: every message is processed at least once, maybe more.

⚡ The consumer must be idempotent

Write:

const IDEMPOTENT = true;
const eTickets = new Map(); // orderId -> how many e-tickets were sent

function handle(job) {
  if (IDEMPOTENT && eTickets.has(job.orderId)) {
    console.log('#' + job.orderId + ' already has its e-ticket, skip');
    return; // still acked, but nothing is sent again
  }
  sendETicket(job); // build the PDF, send the email, record it in eTickets
}

Meaning: An idempotent consumer stays correct even when the same message arrives twice. handle is called for each job (a message that holds work), and eTickets records the orders that already got an e-ticket. If that orderId is already in the record, the function stops without sending anything, but the message is still acked. The buyer still has one e-ticket.

⚡ Retries have a limit

Meaning: A message that always fails is called a poison message, for example order #1142 with the invalid email tono@. It is tried at most 3 times, then moved to the dead letter queue, a separate queue for messages that keep failing. The other messages keep flowing.

What you will learn