Distributed messaging queue
hard 32 minA distributed messaging queue spreads messages over many machines.
Video lesson · Chapter 1 of 5
Follow a ticket into the warehouse
Partitions, leaders and followers in 80 seconds
1:20Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A distributed messaging queue is a queue that runs on several machines, called brokers. A topic is cut into partitions, and each partition is an ordered log on one broker, with copies on others.
Producers send to the partition that a key points to. Consumers work in groups and share the partitions. A small metadata service remembers where everything is.
Why it exists
One machine has a fixed disk, network card and processor, and it can fail. If all messages of a company go through it, its limit is everybody's limit, and its failure is everybody's failure.
Cutting the topic gives more room: every partition adds an independent line of work. Copying the partitions gives safety. Both are ideas you know from databases, under the names sharding and replication. What is special here is the simple data structure, a log, which makes both cheap.
A short history
2004
Amazon offers a beta of its Simple Queue Service, a queue that runs on many machines behind one address. General availability follows in 2006.
2011
LinkedIn open-sources Kafka and describes its partitioned log and consumer groups in a paper at the NetDB workshop.
2025
Apache Kafka 4.0 is the first major release that runs entirely without ZooKeeper. The brokers' own controllers keep the metadata (KRaft).
Words to know
- Broker
- A server that stores partitions and answers producers and consumers.
- Partition
- An ordered part of a topic, and the unit of parallel work.
- Leader and follower
- The replica that takes writes, and the ones that copy it.
- ISR
- In-sync replicas: the copies that keep up with the leader.
- High watermark
- The point that all in-sync replicas have reached. Consumers read up to here.
- Controller
- The part that assigns partitions and elects leaders.
- Consumer group
- Consumers that share the partitions of a topic.
- Lag
- How far a group is behind the end of the log.
How it works
Step through the idea, or press Play.
Route. The key picks a partition, and the metadata says which broker leads it
Understand it
Start here
Boats at several piers
Think of a harbour where cargo boats are unloaded. With one pier the boats wait behind each other. With three piers three boats unload at the same time, if somebody decides which boat goes where.
Piers are partitions, boards are replicas, and porters are the members of one consumer group.
Parts
Four kinds of parts
Brokers
Servers that store messages and serve producers and consumers.
Partitions
Pieces of a topic. They are the reason why work can run in parallel.
Replicas
Copies of a partition on other brokers, for the day a broker fails.
Metadata service
Knows topics, partitions, leaders and members. ZooKeeper, etcd or the cluster's own controllers.
What a queue has to do and promise, such as sending, acknowledging, retries and dead letters, is on the page queues and streams. Here we look at how many machines do it together.
Architecture
From producer to consumer
The parts and the two paths
The data flow
- 1
Send
The producer sends a message to the frontend through a load balancer.
- 2
Look up
The frontend asks the metadata service for the leader of the partition, and caches the answer.
- 3
Route
The message goes to the broker that leads this partition.
- 4
Append and copy
The leader appends to its commit log, and followers copy it.
- 5
Poll and commit
A consumer polls the partition and commits its offset after the work.
Smart clients (Kafka)
- The client library fetches the metadata and talks to the leader itself
- One hop less, no proxy fleet
- Each language needs a full client
A frontend in between (SQS style)
- One address, simple HTTP clients
- A place for authentication, limits and encryption
- One more hop and one more fleet to run
One message, end to end
Partitioning
Which partition?
Choosing a partition
The key decides
How many partitions?
| Question | Example | Result |
|---|---|---|
| How much must one topic take at peak? | 60 MB/s | The target |
| What can one consumer process? | 5 MB/s | 60 / 5 = 12 partitions |
| What can one partition write? | 10 MB/s in your own test | 60 / 10 = 6 partitions |
| Take the larger | 12 and 6 | 12 partitions |
Storage
A commit log on each broker
A partition is a commit log: messages are only ever added at the end, and each gets the next number, its offset. Writing in sequence is fast, and reading in order is simple. With messages 0 to 7 stored, the oldest is offset 0 and the log end offset is 8, the number that the next message will get.
Files of one partition
| File | Holds | Example |
|---|---|---|
| Sealed segment | Older messages, never written again | starts at offset 0 |
| Sealed segment | The next part | starts at offset 10,485,760 |
| Active segment | The newest part: the only one that takes writes | starts at offset 20,971,520 |
| Offset index | Offset to position in the file | 1000 is at byte 32768 |
| Time index | Time to offset | a time stamp leads to 1000 |
How indexes, retention and compaction work is the subject of log-based message queues.
Replication
One leader, several followers
Partition 0 on three brokers
In the ISR
- The leader, and followers that keep up
- Can be elected leader without loss
acks=allwaits for them
Out of the ISR
- Has not caught up within a time limit: slow network or disk, or down
- Not elected, unless unclean election is allowed
acks=alldoes not wait for it
In Kafka the limit is a time, replica.lag.time.max.ms, 30 seconds by default. A limit counted in messages would be worse: a burst would make healthy followers look slow.
What the producer waits for
| Setting | Waits for | Lost when | Use |
|---|---|---|---|
acks=0 | Nothing | Any failure on the way | Samples that may be lost |
acks=1 | The leader's own write | The leader fails before a follower has copied | Logs, if a small loss is fine |
acks=all | All in-sync replicas | All of them are lost together | Orders, payments; Kafka's default |
acks=all alone is not enough: if only the leader is in sync, all means one. min.insync.replicas=2 refuses such writes.How many brokers may be down?
Failure
When a leader dies
- 1
Detect
The broker's heartbeats stop, and after a timeout the controller treats it as gone.
- 2
Elect
For each partition that it led, the controller picks a live in-sync replica.
- 3
Tell
The new leader gets a higher epoch, a term number. Requests with the old number are refused, so an old leader that wakes up cannot write.
- 4
Refresh
Producers and consumers get an error, fetch new metadata and retry with the new leader.
- 5
Catch up
The old broker returns as a follower, cuts off what was never confirmed, copies, and joins the ISR again.
Who may become leader?
Consumers
Groups share partitions
Each partition is assigned to exactly one member of a consumer group. A group called order-processors with two members and four partitions gives partitions 0 and 1 to the first and 2 and 3 to the second.
A third consumer joins six partitions
| Member | Before | After |
|---|---|---|
| C1 | P0, P1, P2 | P0, P1 |
| C2 | P3, P4, P5 | P2, P3 |
| C3 | not there | P4, P5 |
A rebalance
Consumers
Offsets and lag
A committed offset says where to continue. In Kafka it is the offset of the last finished message plus one. If messages 0 to 4 are finished, 5 is committed. A consumer that has read up to 7 and crashes starts again at 5, so 5 to 7 are handled twice. Handlers must be idempotent.
Lag
Do
- Choose the key for the order that you need
- Three replicas, two required in sync
- Alert when the ISR shrinks
acks=allfor critical data- Idempotent producers and consumers
Do not
- One partition for a high load
- Ignoring lag
- A retention shorter than your longest outage
- Skipping offset commits
- Adding consumers without counting partitions
Numbers
Size a small cluster
Assume 1.728 billion events a day of 1 KB. On average that is 20,000 a second, or 20 MB/s; the 3x peak is 60 MB/s. Three copies and seven days of retention are required.
Disk and network
Summary
The whole topic in one minute.
A distributed queue partitions for scale, replicates for durability and elects a new leader when a machine fails. Order holds inside a partition, so the key decides what stays in order.
A write is safe when enough in-sync replicas have it, and it becomes readable at the high watermark. Consumers in a group share the partitions, commit offsets after the work, and see some messages twice after a rebalance. The number of partitions is the ceiling of a consumer group and is awkward to change later.
- Partitions give scale, replicas give safety, the metadata service gives one answer to who leads what.
- The key picks the partition, and order holds only inside it.
- acks=all with two of three replicas in sync survives one lost broker.
- Only an in-sync replica may lead, unless you accept losing messages.
- A consumer group cannot use more members than partitions, and rebalances repeat some work.