Log Compaction: Keep the Latest Value per Key
19:10. A twelve-row directory
November 2, 2184, the dispatch room of Vault-9. The reading room needs an antenna directory: twelve rows, s01…s12, each with a sector of the sky and a status. The comms level already has one: the sources topic. Your relief maintained it, and this morning you brought it back online with the rest of the level. Over the years, it has accumulated 2.1 million messages for those twelve keys. Antennas are retuned, statuses flicker, and every change is sent as a message keyed by source_id. The topic's is set to “forever.”
A new consumer that needs the directory reads the topic from the beginning: more than two million messages just to reconstruct twelve rows, with three minutes spent on startup alone. So you do exactly what you learned at 17:40: set the topic's retention to thirty days and run retention cleanup.
A few minutes later, the reading room shows one antenna in the directory — s07. The other eleven antennas are still there; they simply haven't changed in six months, so the latest message for each one is older than thirty days. Retention deleted those messages along with their entire segments, exactly as designed.
You didn't delete a single message by mistake. You followed the rules perfectly — and lost eleven of the twelve rows.
QUERY: Retention can ask only one question: how old is this message? A directory needs a different answer.

sources: 2,002 messages for the same twelve keys instead of 2.1 million. Otherwise the table would not fit on the screen, and the result does not depend on scale. Each segment holds 500 messages. The same stream is written to two topics; only the policy differs: sources gets 30 days of retention, while sources_demo is created with a different policy that you can see in the code. The third printout deletes one key from sources_demo. We'll examine what the second policy does right after the cell.Two questions a topic can answer
The first printout is a miniature version of the failure from the scene: two segments were deleted, there were 12 keys, and 1 remains. Retention worked correctly. The mistake was choosing the wrong policy for the question the topic needed to answer.
A topic can answer two different kinds of questions:
- “what happened?” — this is history. Every message matters on its own, and an old one can be discarded once nobody needs it anymore. The
signal_rawfeed works this way, so it needs ; - “what is the current state?” — this is state. Of all the messages about an antenna, only the latest one matters. Its age tells you nothing about whether the antenna still exists: an antenna that hasn't changed for six months is still there. The
sourcesdirectory works this way.
A directory does not need the entire history — it needs the latest value for every key. That requirement leads directly to log compaction: among all messages with the same key, keep the latest one and discard the earlier ones. The log then acts as a directory.
You enable log compaction on a topic with one setting. A topic that uses it is called a compacted topic. (ClickHouse ReplacingMergeTree tables use the same rule: “latest version per key.”)
You do not run compaction yourself. A background broker process, the log cleaner, works through closed segments. For each key, it keeps one message: the latest one across all closed segments, rather than one per segment. It does not touch the active segment.
What the second printout showed
- Scale. There were 2,002 messages; 14 remain, while the number of keys stays at 12. The latest values for eleven antennas are in closed segments. For s07, the latest value among the closed segments is at offset 1999, with two more messages in the active segment. The two million messages in the real topic ultimately represent the same twelve rows.
- Offsets are not reassigned. The surviving messages keep their original offsets — 988, 989, 991… then straight to 1999 — while everything in between is gone forever. These are offset gaps. The partition's log start offset is still 0, but the first offset the consumer receives is 988. Code that assumes offset n is always followed by n + 1 will break on the first compacted topic it encounters.
poll()skips the gaps for you: the consumer's position moves past them and only increases. - The active segment is untouched. Offsets 1999, 2000, and 2001 are three messages for key s07, and all three are still there. The log cleaner does not inspect the active segment, so it does not know that message 1999 is already obsolete. This is why “a compacted topic has one message per key” is inaccurate. The correct version is “eventually.”
How do you delete a key if the latest value is kept?
Log compaction can keep the latest message for a key indefinitely. So how do you say, “this antenna no longer exists”? Send a tombstone — a message with a key and no body: p.send('sources_demo', None, key='s11'). To the log cleaner, the tombstone is the latest message for that key, so it discards all earlier values for s11. A consumer building the directory removes the key from its local directory when it sees the empty body.
The third printout uses a copy — nobody has actually retired s11. It shows two steps:
- at 19:10, the tombstone landed in the active segment, so the log cleaner ignored it for the time being. At 20:10, s07 sent a new value, and the segment containing the tombstone closed. Only then did compaction see it and remove three messages: the previous value for s11 and two older values for s07;
- s11 is no longer in the directory, so there are 11 keys. The tombstone itself is still in the log, though, and it has a lifetime of 24 hours.
That lifetime is the tombstone window: the tombstone remains in the log long enough for lagging consumers to see it. The countdown starts from the compaction pass that first encounters it in a closed segment. Once the window expires, the next compaction removes the tombstone as well — leaving no record of that key in the log.
There is a cost to this. If a consumer already has s11 in its directory and then stays offline longer than the window, it will never learn about the deletion. By the time it returns, the tombstone is gone, so s11 remains in its directory forever.
build_directory(consumer): the consumer reads the compacted topic sources_demo from beginning to end, and the function returns a directory — a dictionary mapping antenna → body. The topic is in the same state as after the cell's third printout: the offsets have gaps, and key s11 was deleted with a tombstone.
The deleted key must not appear in the directory with any value, including None. make_consumer() gives you the consumer: it belongs to a new group and starts at the beginning of the partition's log. That is the default in our teaching Kafka; a real consumer would use auto_offset_reset='earliest'. The check will build the directory twice with two new consumers and expects the same result both times.sources_demo: p.send('sources_demo', {'sector': 2, 'status': 'active'}). What happens?What's real in this lesson, and what's simplified for teaching
In the sandbox, compaction runs through an explicit cluster.compact(...) call. A real log cleaner runs on its own schedule: it starts working on the log only after the portion that has not yet been compacted crosses a threshold, and it may remain idle for hours. This is why we say “eventually”: at any given moment, a topic can contain a tail that compaction has not touched yet.
The cell also uses teaching-scale numbers. The threshold for that uncompacted portion is lowered to 0.1 instead of the default 0.5; otherwise the second compaction would not happen on such a small copy. Each segment contains exactly 500 messages because all the messages have the same size. The 24-hour tombstone window, however, is not a teaching simplification: it is the real Kafka default.
The sandbox closes segments according to the cluster clock, while a real broker uses message timestamps. That is why messages from 10:00 and 18:40 can sit in the same active segment in the cell, whereas a cluster would lay out a history with old timestamps differently. The rule of log compaction stays the same.
The cell does not print the rule from the question about a message without a key, but the sandbox enforces it just as the broker does. Answer the question, then verify your answer yourself with one line.
The real rules in this lesson are these: log compaction keeps the latest message per key, it does not touch the active segment, offsets are not reassigned, a tombstone has a limited lifetime — and the rule from the question about a message without a key.
Interview question
How this comes up in interviews
The first question is almost always phrased the same way, usually in English: “what's the difference between log compaction and time-based , and when would you use each?” Answer in terms of the question the data needs to answer, rather than starting with settings. If the topic answers “what happened?” it is an event log, so it needs retention (retention.ms). If it answers “what is the current state?” it represents state, so it needs log compaction (cleanup.policy=compact).
The question has a common trap: many candidates say, “it removes duplicates.” It does not. Log compaction keeps the latest message per key. Two identical messages with different keys are not duplicates to compaction, so both remain.
The second question is, “how do you delete a key from a compacted topic?” Interviewers expect more than the word tombstone — a message with a key and an empty body. You should also mention that it has a limited lifetime (delete.retention.ms, one day by default), so a consumer that falls behind for longer than that can miss the deletion.
The third question is more advanced: “can a compacted topic replace a directory in a database?” Yes — but you lose the change history. If you need that history, you need two topics. Other terms that may come up are log cleaner, min.cleanable.dirty.ratio, active segment, and non-contiguous offsets — offsets with gaps.
Key takeaways
| topic | policy | messages | keys |
|---|---|---|---|
sources | 30-day | 2,002 → 1,002 | 12 → 1 |
sources_demo | log compaction | 2,002 → 14 | 12 → 12 |
sources_demo, s11 deleted | log compaction | 13, including the tombstone | 11 |
Retention answers “what happened?”; log compaction answers “what is the current state?”: for each key, the latest message remains. The log cleaner works only on closed segments and does not reassign offsets, which creates offset gaps. To delete a key, send a tombstone — a message with no body. It has a limited lifetime called the tombstone retention window; a consumer that falls behind for longer than that can miss the deletion. You can build a directory from a compacted topic with a single consumer pass from the beginning.
You switch the real sources topic to log compaction and write all twelve rows again: no policy can restore data that retention has already deleted.
QUERY: A log remembers everything. A directory needs only the last word from each antenna.