Log compaction — keep the last value per key
A compacted topic retains only the last value per key, with tombstones (null values) for explicit deletes — turning the log into a state store that Streams k-tables, Connect CDC sinks, and the __consumer_offsets topic itself rely on.
Time-based retention drops old records. Compaction is the OTHER retention policy — keep the latest value per key forever, and turn the log into a state store the rest of the ecosystem reads from.
Scene 05a
Log compaction — keep the last value per key
- Watch
- Try it
- Predict
- Capture
A topic called "users" with one partition. The producer keeps writing the same keys (alice, bob, carol) with new values. Watch the compactor pass at the end — same key, only the last value survives.
Highlighted lines are the ones running in the diagram right now.
def compact(segment):# pass 1: scan, remember newest offset per keylatest_offset_for_key = {}for record in segment:latest_offset_for_key[record.key] = record.offset# pass 2: emit only the survivor of each keycleaned = []for record in segment:if shouldRetain(record, latest_offset_for_key):cleaned.append(record)swapSegment(segment, cleaned)
def shouldRetain(record, latest_offset_for_key):latest = latest_offset_for_key[record.key]# survivor = the record at the newest offsetif record.offset != latest:return False# tombstones (null value) linger one extra round so# downstream consumers observe the delete, then goif record.value is None:return within(delete.retention.ms, record.timestamp)return True
def dropTombstone(record, now):if record.value is not None:return False# delete.retention.ms gives slow consumers a chance# to observe the null and propagate the deleteif now - record.timestamp < delete.retention.ms:return Falsereturn True # key vanishes from the log
Where this sits in Build Kafka
Scene 05a of 13, in the Write side act — Partitioning, replication, and durability knobs.. Compact-retention turns the log into a state store; tombstones propagate deletes.
Up next. Leader epoch — when a leader fails over, how do followers know which records to keep and which to truncate? Pre-KIP-101 used the High Water Mark, and that silently lost acked writes.
Designs that use this
- Twitter / X TimelinePush or pull? Both. The canonical fanout problem.
- Uber / Lyft — Match Drivers and RidersMatch a rider to the closest acceptable driver in under 3 s. Geohash, S2, surge.
- Slack / DiscordChannels and history. Push or pull — and how a hot-channel fanout doesn't melt the gateway.
- WhatsApp / MessengerHundreds of millions of long-lived sockets, sub-second 1:1 + group delivery, E2E-encrypted, multi-device, multi-region active-active.