Apache Kafka — Event Streaming from Basics to a Platform Service›09 · Storage, retention and compaction

Lesson 09 of 17 · How Kafka works

Storage, retention and compaction

How Kafka stores data on disk and removes it: partitions as segment files with offset and time indexes, why sequential writes and the page cache make Kafka fast, retention by time and size (and why it works per segment), log compaction that keeps the latest value per key, tombstones for deletes, combining both policies, and tiered storage for long retention. Includes a verified compaction run.

Practitioner
Key wordslog segmentsactive segmentoffset indextime indexsegment.bytessegment.msretention.msretention.bytescleanup.policydeletecompactlog compactiontombstonedelete.retention.msmin.cleanable.dirty.ratiopage cachezero-copytiered storageKIP-405compacted topic

A partition on disk

Each partition is a directory on a broker's disk, holding segment files:

orders-0/
  00000000000000000000.log        records, offsets 0 … 41,999
  00000000000000000000.index      offset → byte position in the .log
  00000000000000000000.timeindex  timestamp → offset
  00000000000000042000.log        the ACTIVE segment: new records are appended here
  00000000000000042000.index
  00000000000000042000.timeindex
  leader-epoch-checkpoint
  • The file name is the first offset in the segment.
  • Only the newest, active segment is written to. It is closed and a new one started at segment.bytes (1 GiB) or segment.ms (7 days), whichever comes first.
  • The indexes let a consumer jump to any offset or time quickly, which is how offset resets and --to-datetime work.

Why Kafka is fast

  • Sequential writes: appending to the end of a file is the fastest thing a disk can do.
  • The page cache: Kafka leaves caching to the operating system. Recent data is read from memory, so consumers that keep up rarely touch the disk.
  • Zero-copy: for unencrypted traffic, data goes from the page cache to the network socket without passing through the Java process.
  • Batches stay compressed from producer to disk to consumer.

That is why brokers want plenty of RAM for the OS, not a huge Java heap (typically 6 GB of heap even on large machines).

Retention: deleting old data

With cleanup.policy=delete (the default), Kafka deletes data that is too old or too large:

  • retention.ms: maximum age (default 7 days; -1 keeps forever).
  • retention.bytes: maximum size per partition (default unlimited).

Retention works on whole closed segments: a segment is deleted when its newest record is older than retention.ms. The active segment is never deleted. So with 1-hour retention and 1 GiB segments on a quiet topic, data can live much longer than an hour. Lower segment.ms if you need retention to be precise, for example to meet a data-deletion promise.

Retention is a promise to consumers

A consumer that is down longer than the retention period loses data: its committed offset points to deleted records, and auto.offset.reset decides where it restarts. Set retention from the longest outage you must survive, plus a margin, and alert on lag in time.

Compaction: keep the latest value per key

Some topics represent current state, not history: a user's profile, a product's price, a configuration value. You need the latest value for each key, forever, but not every old value. That is a compacted topic (cleanup.policy=compact).

Before compaction                         After compaction
offset 0  u1 {email: a@x}                 offset 1  u2 {email: b@x}
offset 1  u2 {email: b@x}                 offset 3  u1 {email: a3@x}
offset 2  u1 {email: a2@x}                offset 4  u3 {email: c@x}
offset 3  u1 {email: a3@x}                offset 5  u4 {email: d@x}   (active segment)
offset 4  u3 {email: c@x}
offset 5  u4 {email: d@x}

This is real output from a lab topic created with tiny segments so the cleaner runs quickly:

$ kafka-topics.sh --bootstrap-server localhost:9092 --create --topic user-profile --partitions 1 --replication-factor 1 \
    --config cleanup.policy=compact --config segment.ms=2000 \
    --config min.cleanable.dirty.ratio=0.01 --config delete.retention.ms=1000
  … produce u1, u2, u1, u1, then u3, then u4, waiting between them …
$ kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic user-profile --from-beginning \
    --property print.key=true --property print.offset=true
Offset:1    u2  {"email":"b@x"}
Offset:3    u1  {"email":"a3@x"}
Offset:4    u3  {"email":"c@x"}
Offset:5    u4  {"email":"d@x"}

Notice:

  • The two older u1 values (offsets 0 and 2) are gone; the latest is kept.
  • Offsets never change: there are now gaps (no 0, no 2). Consumers handle this transparently.
  • Compaction runs in the background on closed segments; the active segment and recent data are not compacted yet, so consumers may still see some older values.

Tombstones: deleting a key

To delete a key, produce a record with that key and a null value, a tombstone. Compaction removes the older values, keeps the tombstone for delete.retention.ms (1 day by default) so consumers see the deletion, then removes it too. A consumer that is offline longer than that may never learn the key was deleted.

Both policies at once

cleanup.policy=compact,delete keeps the latest value per key and removes anything older than retention.ms. Useful for "latest state, but not older than 30 days".

A normal topic is a diary: every day's entry is kept until the diary is full, then the oldest pages are torn out. A compacted topic is an address book: when a friend moves house, you cross out the old address and keep only the newest one. To remove a friend completely, you write "deleted" next to their name, and later the whole line is rubbed out.

Where compaction is used

  • Kafka's own __consumer_offsets topic: the latest offset per group and partition.
  • Kafka Connect configuration, offsets and status topics.
  • State tables for stream processing (lesson 12): a Kafka Streams KTable is backed by a compacted topic.
  • Change data capture: the latest row for each primary key.

Tiered storage

Keeping months of data on broker disks is expensive and makes broker replacement slow. Tiered storage (production-ready since Kafka 3.9) keeps recent segments on local disk and moves older closed segments to object storage (S3, Azure Blob, GCS) through a remote storage plugin. Consumers read old data transparently. Enable it on the cluster (remote.log.storage.system.enable=true plus a plugin), then per topic (remote.storage.enable=true, with local.retention.ms for the local part). Managed services offer their own versions.

Try it: retention and compaction

  1. Create a topic with retention.ms=60000 and segment.ms=10000. Produce a few records, wait two minutes, and consume from the beginning. What is left?
  2. Repeat with segment.ms left at its default and explain the difference.
  3. Create the compacted user-profile topic above, produce several values per key, wait for compaction, and confirm only the latest remain, with offset gaps.
  4. Look inside a broker: docker exec kafka ls /tmp/kraft-combined-logs/ (the data directory in the official image) and find your partition directories and segment files.

Going deeper

  • Disk is the most common reason brokers fail. Alert on disk usage per broker, and remember that one partition lives entirely on one disk of one broker per replica.
  • Changing retention.ms is instant and irreversible for shortening: the next check deletes the data.
  • Very many small partitions create very many open files and memory-mapped indexes; raise OS file limits and keep partition counts sensible.

Recap

  • A partition is a series of segment files with indexes; only the active segment is written.
  • Kafka is fast thanks to sequential I/O, the page cache, zero-copy and compressed batches.
  • Retention deletes whole closed segments by age or size; consumers offline too long lose data.
  • Compaction keeps the latest value per key; tombstones delete keys; offsets keep their gaps.
  • Tiered storage moves old segments to object storage for cheap, long retention.

This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.