Message Queues and Streams
How queues and logs move work between services, what delivery guarantees mean, how ordering and consumer groups work, and what interviewers ask about them.
On this page
A message broker is a service that stores messages written by one part of a system until another part reads them. The writer is called the producer and the reader is called the consumer. Brokers move slow or unreliable work out of the request path, absorb bursts of traffic, and let several services react to the same event without the producer knowing about them. They come in two kinds, queues and logs, which behave differently once a message has been read.
Without a broker, the request handler does all the work itself. If a signup endpoint calls an email provider before it responds, a slow provider makes every signup slow,. With a broker, the endpoint writes a "send welcome email" message and responds immediately, and if the provider is down, the messages wait until it recovers.
Where a broker sits
request and replyasynchronous message
Queues and logs
Message queue
A queue, such as RabbitMQ or Amazon SQS, delivers each message to one consumer and deletes it once that consumer acknowledges it. Several workers on one queue share the messages, and a message that is not acknowledged is given to another worker. A queue does not promise strict order once several workers share it, because a message that is redelivered after a failure arrives later than the ones behind it.
Choose a queue when each message is a job that one worker should do once, such as sending an email or resizing an image. The limits are that a processed message is gone, so you cannot replay it after fixing a bug, and a second kind of consumer, such as analytics, needs its own queue that receives a copy of every message. The producer or the broker's fan-out feature has to put that copy there.
Log
A log, such as Kafka or Amazon Kinesis, appends messages to an ordered file and keeps them for a fixed time or size, whether or not anyone has read them. Consumers do not remove messages. Each consumer group stores an offset, its position in the log, and reads forward from it. Moving the offset back makes the group read old messages again.
Choose a log when several services need the same events, or when you may need to reprocess history, for example after fixing a consumer bug. A log has no per-message acknowledgement. The consumer commits an offset, which means that everything before that point is done.
Delivery guarantees
A consumer has to do the work and tell the broker it is finished. A crash can happen between those two steps, and the order in which you do them decides what the crash costs.
At most once
The consumer acknowledges first and then does the work. If it crashes after the acknowledgement, the broker never sends the message again, so the work is lost. Use it only where losing a message is acceptable, such as debug metrics.
At least once
The consumer does the work first and acknowledges afterwards. If it crashes before acknowledging, the broker sends the message again and the work runs twice. Nothing is lost, but duplicates happen, so every consumer has to cope with them. This is the right default for nearly all systems.
Exactly once
No broker can guarantee that a consumer's effect on the outside world happens exactly once, because the consumer can crash after sending an email and before acknowledging. What systems provide is exactly-once effect: at-least-once delivery combined with a consumer that handles duplicates safely, as described under idempotent consumers below. Some brokers offer an exactly-once mode, but only for consumers that read from the broker and write back to it.
Acknowledgements, visibility timeouts, retries and dead letters
In a queue, the broker keeps a message after delivering it but hides it from other consumers for a period called the visibility timeout. If no acknowledgement arrives before the timeout ends, the broker assumes the consumer failed and makes the message visible again. The timeout must be longer than the slowest normal processing time, because otherwise a healthy but slow consumer has its message handed to someone else, which creates a duplicate without any crash. A log has no visibility timeout, because the consumer commits its offset after finishing a batch.
When processing fails, the message is left unacknowledged and is retried. The delay between retries should grow with each attempt, with a random offset added, because an overloaded downstream service needs time to recover. A message that fails every time is a poison message, such as one with data the code can never process. After a fixed number of attempts it is moved to a dead-letter queue, a separate queue that holds failed messages for inspection. An alert on the size of that queue shows that something needs fixing, and after the fix the messages can be replayed. Without the limit, one bad message is retried forever.
- emails sent
- 0
1The API stores job 81 in the queue and responds without waiting for the email.
- emails sent
- 0
2Worker 1 receives job 81. The queue hides it from other workers for 30 seconds, which is the visibility timeout.
- emails sent
- 1
3Worker 1 sends the email and passes
job-81as an idempotency key, which this provider accepts.- emails sent
- 1
4Worker 1 crashes before it acknowledges the job. The queue cannot tell a crash from a slow worker, so the job stays.
- emails sent
- 1
5After 30 seconds job 81 becomes visible again and goes to Worker 2. This is the duplicate that at-least-once delivery allows.
- emails sent
- 1
6Worker 2 sends with the same key. The provider has already seen
job-81and sends nothing. Worker 2 acknowledges, and the queue deletes the job.- emails sent
- 1
- attempts on 97
- 5
7Job 97 has a malformed address and fails on every attempt. After 5 attempts it moves to the dead-letter queue and an alert fires.
Partitions, ordering and consumer groups
Partitions and the partition key
One consumer cannot read a busy log fast enough, so a log is divided into partitions, each an ordered sequence of its own. Messages are ordered only within a partition. The producer picks the partition by hashing a partition key attached to the message, so all messages with the same key go to the same partition and stay in order. If the key is the order id, the "created", "paid" and "shipped" events of one order are read in that sequence.
The key must therefore be whatever has to stay in order, and it also decides how evenly the load spreads. If one customer produces half the traffic and the key is the customer id, that traffic lands on one partition and one consumer.
Consumer groups
A consumer group is a set of consumers that share the reading of a topic. Within a group, each partition is read by exactly one consumer at a time, so a topic with 8 partitions keeps at most 8 consumers of one group busy, and extra consumers wait idle as standbys. Scaling further needs more partitions. Adding partitions later changes which partition each key hashes to, which can break per-key order during the change. When a consumer joins, leaves or crashes, the group rebalances, which means the partitions are reassigned among the remaining consumers. Reading pauses briefly during a rebalance, and the new owner of a partition continues from the last committed offset, so messages handled after that offset are processed again.
Publish and subscribe fan-out
Consumer groups are independent: each receives every message and keeps its own offset. This is how publish/subscribe works on a log. The email service and the analytics service form separate groups on one topic. A queue needs one queue per subscriber for the same effect.
Backpressure and consumer lag
A broker absorbs a short burst, but if consumers are slower than producers on average, the backlog grows without limit. Consumer lag is how many messages, or how many seconds of messages, a consumer is behind the newest one, and a steadily rising lag means the consumers cannot keep up. There are two responses, often combined.
- Add consumers. This helps only up to the partition count of a log, and does nothing if the bottleneck is a database or external service that the consumers call.
- Apply backpressure, which means making producers slow down. If the queue has a size limit, publishing fails or blocks when it is full, and the API can return 429 or 503 so that clients retry later.
Idempotent consumers and the outbox pattern
Idempotent consumers
Because delivery is at least once, a consumer must produce the same result whether it handles a message once or twice. One way is to use an operation that is safe to repeat, such as setting a field to a value instead of adding to it. Another is to pass the message id to the downstream service as an idempotency key, as the tracer does. A third is to keep a table of processed message ids and check it before working. The check and the work must happen in one database transaction, with a unique constraint on the message id, or a crash between them lets the duplicate through. See idempotency and retries.
Publishing reliably with the outbox pattern
A service often has to update its database and publish a message about the change. These are two systems, so a crash after the commit and before the publish leaves a change that nobody hears about, while publishing first can announce a change that then fails to commit. The outbox pattern fixes this. The service writes the change and a row describing the message to an outbox table in one transaction, so both exist or neither does. A separate relay reads new outbox rows, publishes them and marks them as sent. If the relay crashes between publishing and marking, it publishes the row again, so publishing is at least once and consumers still need to be idempotent.
In the interview
Bring in a broker when work is slow, is not needed for the response, arrives in bursts, or has to reach several systems. Pick a queue for jobs that one worker handles once and a log when several consumers need the same events or replay matters. Then state the delivery guarantee and what it costs, for example "delivery is at least once, so the consumer dedupes by event id".
Questions to expect:
- "Can you guarantee exactly-once delivery?" Not across a network to an external system, because a consumer can crash after doing the work and before acknowledging. What I can build is exactly-once effect, which is at-least-once delivery plus a consumer that detects duplicates with an idempotency key or a unique constraint on the message id.
- "How do you keep messages in order?" Order holds only within a partition, so I choose a partition key that groups the messages that must stay in order, such as the order id. Messages with different keys can be processed in any order, which is what lets consumers run in parallel.
- "When would you pick a queue and when a log?" A queue fits jobs that one worker should do once and that nobody needs to read again, such as sending emails. A log fits events that several services consume independently, or that you may need to replay after a bug fix or to build a new consumer from history. The cost of a log is that parallelism is limited by the partition count and that a failing message blocks its partition.
- "What do you do with a message that always fails?" I limit the attempts, increase the delay between them, and then move the message to a dead-letter queue and alert on its size. Someone fixes the cause and replays it.
- "The consumers are falling behind. What do you do?" I check consumer lag to confirm the trend and then look at where consumers spend their time. If they are limited by CPU, I add consumers up to the partition count. If a downstream database is the limit, more consumers make it worse, so I slow the producers or bound the queue.
After checkout we send a confirmation email and update analytics. Where does that happen?
Not in the checkout request. Checkout publishes an OrderPlaced event to a log, keyed by order id. Email and analytics are separate consumer groups, so a slow email provider delays neither analytics nor checkout.
Can a customer get two emails?
With at-least-once delivery, yes, unless I prevent it. The email worker passes the event id to the provider as an idempotency key, so a redelivered event sends nothing.
What if checkout saves the order and then crashes before publishing?
That would lose the event, so checkout writes the order and an outbox row in one transaction, and a relay publishes the outbox rows.
A consumer acknowledges a message and then processes it, and it crashes between the two steps. What happens to the message?
A topic has 8 partitions and a consumer group has 12 consumers. How many consumers are doing work?
A service must update its database and publish an event without ever losing the event. Which approach does that?
What to practise next
Read idempotency and retries to see how consumers handle duplicates, and then Design a Notification System, which uses a queue throughout.