Queues & streams
medium 30 minA message queue stores work between the program that asks for it and the program that does it.
Video lesson · Chapter 1 of 5
A message survives its producer
Message queue
1:16Reel

Theory
Read or listen first. About 1 min.
What it is
A message queue holds work that one program has sent and another has not yet done. The sender does not wait for the receiver. A log or stream is a close relative: it keeps messages in order for a while, and several readers can each go through them at their own pace.
Both put a buffer between programs, so that each can run, fail and grow on its own.
Why it exists
Some work does not have to finish before you answer the user: sending an email, resizing a picture, counting a click. Putting it in a queue makes the answer faster and survives a slow or broken receiver.
A queue also absorbs bursts. The cost is delay, and new questions: what if a message arrives twice, in the wrong order, or can never be processed? The requirements on this page answer those questions one at a time.
A short history
1993
IBM releases MQSeries, a widely used commercial message queue.
2003
Work that becomes the open AMQP standard begins at JPMorgan Chase.
2006
Amazon SQS becomes generally available, a queue as a cloud service.
2007
RabbitMQ is released, an open-source broker that speaks AMQP.
2011
LinkedIn open-sources Kafka, a partitioned, replicated log built for very large streams of events.
Words to know
- Producer and consumer
- The program that sends, and the one that receives.
- Acknowledgement
- The consumer's word that the work is done and the message can go.
- Visibility timeout
- How long a received message stays hidden from other consumers.
- Dead letter queue
- Where messages go after failing too often.
- At least once
- Never lost, but may arrive twice.
- Idempotent
- Doing it twice has the same effect as once.
- Partition
- One ordered part of a stream.
- Offset
- A reader's position in a partition.
- Consumer group
- Readers that share the partitions.
How it works
Step through the idea, or press Play.
Produce. The producer sends a message, and the queue stores it before it confirms
Understand it
Start here
The washing-up rack
Think of the evening after a big dinner. Nobody who brings a dirty plate waits until it is clean. They put it on the rack and leave. Whoever washes takes the next plate when their hands are free.
The rack is the queue, the card is the visibility timeout, and the red box needs somebody who looks inside it.
Why
What a queue gives you
A synchronous call ties your speed and availability to every service that you call. A broker in the middle lets the producer continue as soon as the message is stored. The pattern is explained in asynchronous communication; this page is about what the queue itself has to do.
Asynchronous
The producer does not block while the work runs.
Buffering
Messages are stored for a time until somebody can take them.
Load levelling
A peak becomes a longer line instead of errors.
Decoupling
Services deploy, scale and fail independently.
Reliability
A message stays until the work is confirmed, if you set it up that way.
Ordering
Messages of one key can be handled in order, if the queue supports it.
The life of a message
Seven steps from send to gone
Receive hides, acknowledge removes
- 1
The producer sends
A message is a payload plus metadata: an id, a time, perhaps a key and a type.
- 2
The queue stores it
It is written to disk, and normally to other machines, before the queue confirms.
- 3
The consumer asks
It polls, or the broker pushes when the consumer has room.
- 4
The queue delivers
The message is hidden for the visibility timeout. Each delivery gets its own receipt.
- 5
The consumer works
Business logic runs. A long job asks for more time before the timeout ends.
- 6
The consumer acknowledges
It sends the receipt of this delivery.
- 7
The queue removes it
No acknowledgement means that the message becomes visible again.
A queue service and the parts around it
Requirements 1
What the queue must do
Functional requirements
| Area | The queue must |
|---|---|
| Produce | Accept a payload and metadata, accept batches, return a message id, define how data is serialised |
| Consume | Poll or push, serve many consumers, hide received messages, filter if needed |
| Manage messages | Remove after acknowledgement, retry after failure, set aside in a dead letter queue, expire after a time to live |
| Manage queues | Create and delete, report depth and age, purge, configure retention |
A small API
| Operation | Call | Notes |
|---|---|---|
| Send | POST /queues/{name}/messages | Returns an id after the message is stored |
| Receive | POST /queues/{name}/receive | Changes state, so it is not a GET. Takes a maximum and a wait time |
| Acknowledge | DELETE /queues/{name}/messages/{receipt} | The receipt belongs to one delivery |
| Extend | PUT /queues/{name}/messages/{receipt}/visibility | More time for a long job |
Requirements 2
What the queue must promise
Non-functional requirements, with example targets
| Quality | Example target | What it means here |
|---|---|---|
| Availability | 99.99% | Sending works even while a machine is down |
| Durability | 11 nines | A message that was confirmed to the producer is not lost |
| Latency | under 10 ms p99 | Fast send and receive, not counting the wait in line |
| Throughput | 100,000 a second | Large volumes, normally by adding partitions |
| Scalability | Horizontal | More traffic means more machines, not a new design |
| Ordering | FIFO or by key | Order inside a stated scope, never only the word ordered |
Delivery
Once, at least once, at most once
Three delivery guarantees
| Guarantee | How | Good | Bad |
|---|---|---|---|
| At most once | Acknowledge before the work, or do not retry | Fastest and simplest | Messages can be lost |
| At least once | Acknowledge after the work, retry until then | No loss | Duplicates happen |
| Exactly-once effect | At least once, plus an idempotent consumer or one transaction | Each message counts once | More work and more state |
Where does the crash fall?
A network timeout cannot tell you whether the other side did the work. That is why true end-to-end exactly-once delivery cannot be promised across independent systems, and why most real systems choose at-least-once delivery with idempotent handling: unique request ids, unique constraints or upserts, in the same transaction as the effect. Some brokers do offer more inside their own boundary, for example deduplication of a repeated send or transactions between two topics of one broker.
Failure
Timeouts, retries and dead letters
The states of one message
Do
- Set the visibility timeout well above the normal work time, and extend it for long jobs
- Make consumers idempotent
- Configure a dead letter queue with an alert
- Monitor depth and the age of the oldest message
- Send, receive and acknowledge in batches
Do not
- Assume order without checking its scope
- Take work without acknowledging it afterwards
- Put large files in a message; store the file and send a link
- Ignore failed messages
- Send a message and then block until the answer comes back
How long until a poison message is set aside?
Patterns
Four ways to connect senders and receivers
Point to point
One queue. Each message is handled by one consumer. Good for distributing tasks.
Publish and subscribe
A topic. Every subscriber gets each message. Good for telling others that something happened.
Fan-out
An exchange copies a message into several queues, one for each processing path.
Competing consumers
Several workers read the same queue, so more workers mean more throughput.
Fan-out, then competing consumers
Pub-sub has a page of its own. Note that fan-out plus competing consumers gives you both at once: every purpose sees each message, and every purpose can have many workers.
Sizing
How many workers, and how long is the line?
Suppose a photo site gets 864,000 uploads a day. That is 10 a second on average, and 30 a second at a 3x peak. One resize job takes 0.5 seconds. These are assumptions for the example.
Workers for the peak
Or accept a line for a while
Queue or stream
Point-to-point queues and append-only streams
Messaging systems fall broadly into two models: task queues, and event streams built on a log.
Stream on a log (for example Kafka)
- Messages are appended to a log and stay after they were read.
- Consumer groups read the same log, each at its own pace.
- Readers keep an offset, so they can replay.
- Order holds inside one partition.
Work queue (for example SQS, RabbitMQ queues)
- A message is removed after it is acknowledged.
- Competing workers share the messages.
- A new service cannot replay what is gone.
- Keeping order with many consumers is difficult.
Which one do I need?
Three well-known products
| Amazon SQS | RabbitMQ | Apache Kafka | |
|---|---|---|---|
| Type | Managed queue | Message broker | Event streaming platform |
| Order | FIFO queues, by message group | Per queue; redelivery can change it | Per partition |
| Kept for | 4 days by default, 14 at most | Queues: until acknowledged or expired. Streams: a size or age limit | 7 days by default, configurable |
| Good for | Simple decoupling, serverless, no servers to run | Routing, several protocols, priorities, request and reply | Event sourcing, stream processing, replay, high volume |
Inside a stream 1
Commit log, replicas and the high watermark
Brokers for large streams avoid random disk writes. Each partition is an append-only series of segment files. Sequential writing suits both disks and the operating system's page cache and read-ahead. Log-based queues explains the files, indexes and cleanup.
Path of an appended message
hash(key) % num_partitions. Followers pull from the leader. With all in-sync replicas required, the ack waits for them.Three ideas that make it durable
- 1
In-sync replicas (ISR)
The leader plus the followers that keep up within a time limit. A follower that hangs or is too slow leaves the set.
- 2
High watermark
The point up to which every in-sync replica has the log. Consumers do not read past it, so they never see a message that a failover could take back.
- 3
Leader election
If a leader fails, the cluster's controller promotes an in-sync replica. A lagging one is chosen only if unclean election is allowed, at the price of losing messages.
Inside a stream 2
Consumer groups share partitions
A consumer group combines two things: inside the group the work is shared, and different groups each see everything. Members join under one group id. If a member leaves or joins, the partitions are assigned again: a rebalance.
import zlibclass Topic: def __init__(self, partitions): self.parts = [[] for _ in range(partitions)] self.offsets = {} # (group, partition) -> next offset def produce(self, key, value): p = zlib.crc32(key.encode()) % len(self.parts) # stable, unlike hash() self.parts[p].append(value) return p, len(self.parts[p]) - 1 def consume(self, group, p, limit=10): start = self.offsets.get((group, p), 0) return list(enumerate(self.parts[p]))[start:start + limit] def commit(self, group, p, offset): self.offsets[(group, p)] = offset + 1 # after processing: at least oncet = Topic(2)p, _ = t.produce("user-101", "order 1 created")t.produce("user-101", "order 1 paid") # same key, same partitionfor offset, value in t.consume("fraud", p): print("fraud reads", offset, value) t.commit("fraud", p, offset)print("fraud, next poll:", t.consume("fraud", p))print("analytics still has", len(t.consume("analytics", p)))When to commit the offset
- 1
At most once
Commit before processing. A crash in the middle skips the message.
- 2
At least once
Commit after processing. A crash, or a lost commit, processes it again.
- 3
Idempotent processing
Duplicates come from retries and rebalances, so the effect must be safe to repeat.
Summary
The whole topic in one minute.
Queues and logs let programs work at different speeds. A queue hands each message to one worker and forgets it after the acknowledgement. A log keeps messages so that several readers can use them.
Receive hides, acknowledge removes, silence brings the message back. Expect duplicates and make handling idempotent. Order holds within a partition or message group, not across them. Watch the age of the oldest message: it tells you whether consumers keep up.
- A queue stores, hides, waits for an acknowledgement and removes. Silence brings the message back.
- State requirements with a scope: order by what, durable after which confirmation, delivered how often.
- At-least-once delivery plus idempotent consumers is the normal choice.
- Queues remove messages after the acknowledgement; streams keep them and let readers hold offsets.
- Size workers from peak rate times work time, and alert on the age of the oldest message.