Video in progress
What is log compaction in Kafka, and which topics would you make compacted?
In a compacted topic, Kafka keeps at least the last value for each key and cleans out older versions in the background. It's meant for data like "the current state of each entity": a new consumer can read the topic from the start and rebuild the full state, while the topic doesn't grow forever.
📖 Answer
A regular topic is cleaned by time or size (retention.ms): messages older than 7 days are deleted — regardless of key. That's right for an event stream.
With compaction (cleanup.policy=compact), Kafka looks at the key:
before: k1=A k2=B k1=C k3=D k2=E
after: k1=C k3=D k2=E
The last value of each key stays. A message with a null value is a tombstone: after a while (delete.retention.ms) the key is removed entirely.
Where it's needed:
- Kafka itself stores consumer offsets in the compacted
__consumer_offsetstopic; KTableand state store changelogs in Kafka Streams;- state like "product prices" or "user settings" — when a new service starts and reads the topic from the beginning, it gets the current price of every product without going to the DB;
- CDC (Debezium) topics — to keep a current copy of the table in Kafka.
Subtle points:
- compaction isn't immediate — the active segment isn't cleaned, and a consumer may also see several old values for one key. The consumer must always work with "last one wins" logic;
- messages without a key can't be written to a compacted topic;
cleanup.policy=compact,deleteexists too — compaction plus deleting old keys by time.
If you need the full history of events (audit, event sourcing), compaction doesn't fit — it deliberately throws history away.
Sign up to mark studied questions and save your progress.