AlgoViz

Distributed messaging queue

hard 32 min

A distributed messaging queue spreads messages over many machines.

Video lesson · Chapter 1 of 5

Follow a ticket into the warehouse

0:00 / 3:39

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

  1. 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.

  2. 2011

    LinkedIn open-sources Kafka and describes its partitioned log and consumer groups in a paper at the NetDB workshop.

  3. 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.

Step 1 of 3

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.

Three piers, and a list on every board
Pier12345One pier

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

Producers reach a frontend service through a load balancer. The frontend asks the metadata service which broker leads the partition and sends the message there. Three brokers lead two partitions each. Consumers fetch from the brokers.
Pink is the write path, blue the read path. Each broker leads two of the six partitions. Copies on other brokers are left out here.

The data flow

  1. 1

    Send

    The producer sends a message to the frontend through a load balancer.

  2. 2

    Look up

    The frontend asks the metadata service for the leader of the partition, and caches the answer.

  3. 3

    Route

    The message goes to the broker that leads this partition.

  4. 4

    Append and copy

    The leader appends to its commit log, and followers copy it.

  5. 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

Followers pull. Their next fetch, from 101, tells the leader that they have 100.

Partitioning

Which partition?

Choosing a partition

Sticky batches fill one partition for a while before they move on, which makes larger and fewer requests.

The key decides

p=hash(key) mod N14 mod 6=2,14 mod 8=6p = \mathrm{hash}(key) \bmod N \qquad 14 \bmod 6 = 2,\quad 14 \bmod 8 = 6
If NN grows from 6 to 8, the key with hash 14 moves from partition 2 to 6. New messages of that key no longer follow the old ones, so order breaks at that moment.

How many partitions?

QuestionExampleResult
How much must one topic take at peak?60 MB/sThe target
What can one consumer process?5 MB/s60 / 5 = 12 partitions
What can one partition write?10 MB/s in your own test60 / 10 = 6 partitions
Take the larger12 and 612 partitions
All rates are assumptions: measure yours. Start with some room, because adding partitions later moves keys. There is no universal default; Kafka's own setting creates 1.

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

FileHoldsExample
Sealed segmentOlder messages, never written againstarts at offset 0
Sealed segmentThe next partstarts at offset 10,485,760
Active segmentThe newest part: the only one that takes writesstarts at offset 20,971,520
Offset indexOffset to position in the file1000 is at byte 32768
Time indexTime to offseta time stamp leads to 1000
A segment file is named after its first offset. Old segments can be deleted as whole files.

How indexes, retention and compaction work is the subject of log-based message queues.

Replication

One leader, several followers

Partition 0 on three brokers

A producer writes offset 100 to broker 1, which is the leader of partition 0. Broker 2 has copied up to 100. Broker 3 has copied up to 99 and is fetching 100. A consumer reads from the leader up to the high watermark.
Broker 3 is one message behind but still in sync. Offset 100 is readable when broker 3 has it, too.

In the ISR

  • The leader, and followers that keep up
  • Can be elected leader without loss
  • acks=all waits 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=all does 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

SettingWaits forLost whenUse
acks=0NothingAny failure on the waySamples that may be lost
acks=1The leader's own writeThe leader fails before a follower has copiedLogs, if a small loss is fine
acks=allAll in-sync replicasAll of them are lost togetherOrders, 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?

fwrite=R−m=3−2=1fdata=m−1=1f_{\text{write}} = R - m = 3 - 2 = 1 \qquad f_{\text{data}} = m - 1 = 1
With R=3R = 3 replicas and m=2m = 2 required in sync, writing continues with one replica down, and a confirmed message survives the loss of any one machine that has it.

Failure

When a leader dies

  1. 1

    Detect

    The broker's heartbeats stop, and after a timeout the controller treats it as gone.

  2. 2

    Elect

    For each partition that it led, the controller picks a live in-sync replica.

  3. 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. 4

    Refresh

    Producers and consumers get an error, fetch new metadata and retry with the new leader.

  5. 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?

Consistency or availability, for one partition. Kafka waits by default.

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

MemberBeforeAfter
C1P0, P1, P2P0, P1
C2P3, P4, P5P2, P3
C3not thereP4, P5
Three partitions changed hands: P2, P4 and P5. A sticky assignment would move only two, for example P2 and P5 to C3.

A rebalance

If the first member cannot commit before it gives up, the new one repeats some messages.

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

lag=∑p(log endp−committedp)(10−5)+(20−18)=7\text{lag} = \sum_{p} (\text{log end}_p - \text{committed}_p) \qquad (10 - 5) + (20 - 18) = 7
Seven messages behind on two partitions. Also measure the lag in seconds: it is easier to judge.

Do

  • Choose the key for the order that you need
  • Three replicas, two required in sync
  • Alert when the ISR shrinks
  • acks=all for 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

20 MBs×86,400×7×3≈36.3 TB60×3=180 MBs written at peak20\ \tfrac{\text{MB}}{\text{s}} \times 86{,}400 \times 7 \times 3 \approx 36.3\ \text{TB} \qquad 60 \times 3 = 180\ \tfrac{\text{MB}}{\text{s}}\ \text{written at peak}
On six brokers that is about 6 TB and 30 MB/s of writes for each, before consumers read anything. Keep room for the load of a broker that fails.

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.

Sources