Video in progress
What is log compaction, and when is it used?
In a compacted topic, Kafka keeps only the latest value for each key and cleans up older ones in the background. It's for cases where you need the "current state of each object": settings, user profiles, rebuilding a cache.
📖 Answer
A regular topic is a history of "what happened". A compacted topic is a table of "what is there now".
kafka-topics.sh --create --topic customer-state \
--config cleanup.policy=compact \
--partitions 6 --replication-factor 3 \
--bootstrap-server localhost:9092
Background cleaner threads go through the closed segments and delete the old versions of a key. They don't touch the active (latest) segment, so you may see several versions of the same key at the same time, which is normal.
To delete a key entirely, you send a message with a null value (a tombstone). The tombstone itself disappears after delete.retention.ms.
Where you see it: Kafka itself uses compaction for __consumer_offsets; Kafka Streams KTables; Debezium CDC topics.
You can't write messages without a key to a compacted topic: the broker rejects them.
Sign up to mark studied questions and save your progress.