AlgoViz

Log-based message queues

medium 30 min

A log-based queue appends messages to a file and keeps them after they were read.

Video lesson · Chapter 1 of 5

A notebook whose pages stay numbered

0:00 / 4:09

The log that remembers, in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A log is a list that grows only at the end. Every entry gets the next number, its offset, and is never changed. A log-based message queue stores messages in such a log.

Reading does not remove anything. A consumer keeps one number, the offset of the next message. Two consumers are two numbers, and replaying the past means setting the number back.

Why it exists

A traditional work queue removes a message after it was acknowledged. That is right for tasks. It is wrong for facts, such as an order that was placed: next month somebody builds a new service that needs the same facts, and they are gone.

A log keeps them for a time, or keeps the latest value of each key for ever. It also suits the hardware: adding at the end and reading in sequence is what disks and the operating system do best.

A short history

  1. 1991

    Rosenblum and Ousterhout describe a log-structured file system: the whole disk is written as one log. Their Sprite system ran one in 1992.

  2. 1992

    ARIES, a recovery method from IBM, is published. Databases write their changes to a log first. Replaying it rebuilds the state after a crash.

  3. 2011

    LinkedIn open-sources Kafka, which makes such a log a service that many programs can read.

  4. 2021

    RabbitMQ 3.9 introduces streams, a log that consumers read without removing messages, beside its classic queues.

Words to know

Offset
The number of a message in its partition. It never changes.
Log end offset
The number that the next message will get.
Segment
One file of the log. Only the newest, active one is written.
Sparse index
A small table with some of the offsets and their positions in the file.
Retention
Deleting old segments by age or size.
Compaction
Keeping the latest message of each key.
Tombstone
A message with a key and no value. It says that the key is deleted.
Replay
Reading again from an earlier offset.

How it works

Step through the idea, or press Play.

Step 1 of 3

Append. A message goes to the end of the active segment and gets the next offset

Understand it

Start here

A comic strip along the corridor

Think of a long comic strip, pinned picture by picture along the corridor of a school. Asha adds one picture after another. Everyone reads at their own speed and leaves a coloured bookmark under the next picture. Nobody takes a picture away after reading it.

One strip, many bookmarks
012345Add at the end

The strip is a partition, the number under a picture is its offset, and a bookmark belongs to the reader.

The idea

What changes against a work queue

Work queueLog-based queue
After the message is handledIt is removedIt stays until retention or compaction
Who remembers progressThe broker, for each messageOne offset for each group and partition
ReplayNot possibleSet the offset back
Several purposesA copy in a queue for eachOne copy, several groups
OrderCan change when messages are redeliveredFixed inside a partition
Retry or delay of one messageBuilt inYou build it, for example with a retry topic
Good forDelivering tasksStreams of events, audit, reprocessing
What a work queue does in detail is on the page queues and streams.

Key benefits

  • Replay

    Read again from any offset that is still kept.

  • Ordering

    Strict inside a partition.

  • Throughput

    Sequential writes, batches and few copies in memory.

  • Durability

    On disk and, with replicas, on several machines.

  • Decoupling

    Producers do not know their readers.

  • Scalability

    More partitions on more brokers.

One log, three independent readers

An order service appends to one log on a broker. Three groups read it independently: shipping at offset 6, analytics at offset 3, and a new search indexer at offset 0.
The log is stored once for all three. A group is just a name and a number for each partition.

Structure 1

Offsets

Suppose msg-0 to msg-7 are stored. The log start offset is 0 and the log end offset is 8. A message is never changed and never moves. The log grows only at the end, and shrinks only at the beginning, when old segments go.

Append and read

Analytics was behind and caught up with one larger batch. Shipping did not notice.

Positions

stored=end−start=8−0=8lag=end−position=8−3=5\text{stored} = \text{end} - \text{start} = 8 - 0 = 8 \qquad \text{lag} = \text{end} - \text{position} = 8 - 3 = 5
The first formula holds as long as compaction has not removed offsets in between.

Structure 2

Segment files

One endless file would be hard to clean. So a partition is a directory with a series of files, each named after its first offset. Only the last one, the active segment, takes writes. A full one is sealed and a new one begins.

An example with 512 MB segments

First offset in the nameOffsetsSizeState
00 to 999512 MBSealed
10001000 to 1999512 MBSealed
20002000 to 2458234 MBActive
The real names are padded to 20 digits and end in .log. Kafka's default segment size is 1 GiB. A segment also rolls after a time.

Partition 0 on one broker

Inside one broker, partition 0 has three segment files on disk: two sealed and one active. The producer appends to the active segment. Now and then an entry is added to the index files. A cleaner deletes or compacts the sealed ones.
Writes touch only the active segment. The cleaner touches only sealed ones.

Structure 3

Finding an offset

The .index file maps some offsets to byte positions. The .timeindex file maps some times to offsets, for a question like: where was the log at midnight? Both are sparse: Kafka adds an entry about every 4,096 bytes of messages, so the files stay small.

Read offset 2150

  1. 1

    Pick the segment

    The largest first offset that is not above 2150 is 2000. Binary search over the names.

  2. 2

    Ask the index

    Entries: 2000 at byte 0, 2100 at byte 8192, 2200 at byte 16384. The last one that is not above 2150 is 2100.

  3. 3

    Scan

    Start at byte 8192 and read forward past 50 messages to 2150.

Cost of a lookup

O(log⁡S)+O(log⁡I)+a short scanO(\log S) + O(\log I) + \text{a short scan}
SS segments, II index entries in one segment. After that, reading continues in sequence and needs no index.

The time index

Time stampTime (UTC)Offset
17040672001 January 2024, 00:000
170407080001:00100
170407440002:00200
Start reading at 01:30? Look up the last entry before it, offset 100, and scan forward by time.

Cluster

Where the log lives

A topic has several partitions, each with a leader and followers on different brokers. Brokers store the logs, answer produce and fetch requests and copy from leaders. The cluster's controller assigns leaders; since Kafka 4.0 that works without ZooKeeper (KRaft). How copies, in-sync replicas and failover work is on the page distributed messaging queue.

A topic with typical settings

SettingExampleMeaning
partitions12Parallel lines of work
replication.factor3Copies of each partition
min.insync.replicas2Copies needed for a confirmed write with acks=all
retention.ms6048000007 days, which is also the default
retention.bytes10737418241 GiB for each partition; by default there is no size limit
segment.bytes536870912512 MiB for each segment file
cleanup.policydeleteOr compact, or both
With 12 partitions, this size limit keeps at most about 12 GiB, plus one segment each, of the topic on disk, and the same again for each replica.

Cleanup 1

Retention: delete by age or size

Four messages, seven days

  1. 1

    msg-1 and msg-2 are 8 days old

    They are past the limit.

  2. 2

    msg-3 is 2 days old, msg-4 is 1 day old

    They are within it.

  3. 3

    If each pair is in its own segment

    The first segment is deleted as a whole file.

  4. 4

    If all four are in one segment

    Nothing is deleted yet. A segment goes when its newest message is too old.

So retention promises at least this long, not exactly. A consumer that stops for longer than the retention loses messages. Its saved offset no longer exists, and a rule decides where it continues: at the earliest message, at the latest one, or with an error.

Cleanup 2

Compaction: the latest value of each key

Sometimes the question is not what happened this week but what is true now. Compaction removes a message when a later one has the same key. What remains is a snapshot of the current state, still in log form.

Before and after

OffsetKeyValueAfter compaction
0A1removed
1B1removed
2A2removed
3C1removed
4B2removed
5A3kept
6Cnone (tombstone)kept for a day, then removed
7B3kept
The end state is A = 3 and B = 3. Offsets stay 5 and 7: there are gaps, and that is fine.

Which cleanup?

The setting is cleanup.policy, and compaction needs a key on every message.

Compaction settings in Kafka

SettingDefaultMeaning
min.cleanable.dirty.ratio0.5Clean when at least half of the log is uncompacted
delete.retention.ms86400000Keep tombstones for a day, so that slow readers see them
min.compaction.lag.ms0The least time before a message may be removed
The active segment is never compacted. So readers of a compacted topic still see several values for a key, and must take the last one.

Good uses of compaction

  • Change data capture from a database
  • Rebuilding a cache or the state of an application
  • User profiles and preferences
  • The last known location of a device

Wrong uses

  • Page views or payments, where every event counts
  • Messages without a key
  • Deleting personal data at once: it takes time until segments are cleaned
  • A guarantee of only one value for each key

Reading again

Replay and rebuilding state

Fix a bug by replay

The old group and table keep working until the switch. Nothing is asked of the producer.

A replay repeats effects. Counting into a new table is safe. Sending emails again is not. Keep effects on the outside world in a consumer of their own, and make them idempotent.

How long does catching up take?

B=2 MBs×3×86,400 s=518,400 MBt=518,40010−2=64,800 s=18 hB = 2\ \tfrac{\text{MB}}{\text{s}} \times 3 \times 86{,}400\ \text{s} = 518{,}400\ \text{MB} \qquad t = \frac{518{,}400}{10 - 2} = 64{,}800\ \text{s} = 18\ \text{h}
Three days of backlog at 2 MB/s, read at 10 MB/s while new messages keep coming. Compare it with the retention before you need it.

Processing

Streams and tables

Kafka Streams is a client library that reads topics, transforms the messages and writes the result to other topics. It has two views of a topic.

KStream: events

  • An endless stream of records
  • Each record stands for itself
  • Insert: alice 1, then alice 3, sums to 4

KTable: current values

  • A stream of changes
  • One value for each key
  • Upsert: alice 1, then alice 3, means 3

From a stream to a table

filter and map need no memory. groupBy moves records by the new key, and reduce keeps state for each key.

Common operations

OperationWhat it doesState
filter()Keeps records that matchnone
map()Changes the key or the valuenone
flatMap()One record becomes severalnone
groupByKey()Groups by the message keynone by itself
join()Combines streams or tablesyes
aggregate()Builds a value for each keyyes
State is stored locally and backed by a changelog topic, so a replacement can rebuild it by reading a log. Such a changelog suits compaction. Never compact the input of a KStream: the sum of alice would change from 4 to 3.

Numbers

Size a log

Assume 172.8 million events a day of 1 KB: 2,000 a second, 2 MB/s on average and 6 MB/s at a 3x peak, with three replicas and seven days.

Disk

2 MBs×86,400×7×3=3,628,800 MB≈3.6 TB2\ \tfrac{\text{MB}}{\text{s}} \times 86{,}400 \times 7 \times 3 = 3{,}628{,}800\ \text{MB} \approx 3.6\ \text{TB}
With 12 partitions, one of them gets about 0.17 MB/s, so a 1 GB segment fills in about 6,000 seconds, or 100 minutes.

Summary

The whole topic in one minute.

A log-based queue appends, numbers and keeps. Readers own their position, so a new reader, a slow reader and a replay cost the log almost nothing.

Segments make cleanup and lookup cheap. Retention deletes whole old segments, compaction keeps the latest value for each key, and a tombstone removes a key. A stream of events and a table of current values are two views of the same log.

  • Append only, one offset for each message, and reading removes nothing.
  • Readers own their position: new, slow and repeated readers are cheap.
  • Segments allow cheap deletes, and sparse indexes allow quick lookups.
  • Retention deletes whole old segments. Compaction keeps the latest value of each key, and a tombstone deletes a key.
  • A consumer that stays away longer than the retention loses messages.

Sources