Log Compaction Deep Dive and Tombstones
Discover how Kafka log compaction retains the latest state per message key, how background log cleaner threads operate, and how tombstones delete records.
Most Kafka topics use time-based or size-based retention (log.cleanup.policy=delete), where records older than a configured period (such as seven days) are permanently discarded.
However, for topics that represent current entity state—such as customer profiles, product catalog prices, or database changelogs—deleting records based on age destroys critical business data. If a customer created their account three years ago and has not updated it since, a time-based policy would delete their account record entirely.
Kafka solves this with Log Compaction (log.cleanup.policy=compact), guaranteeing that the broker retains at least the last known value for every single message key indefinitely.
In this lesson, you will learn the internal mechanics of log compaction, how the Log Cleaner thread deduplicates records, and how tombstones represent deletions.
01Log Compaction vs Time-Based Deletion
To understand when to choose log compaction, compare the two cleanup policies:
| Feature | Time/Size-Based Cleanup (delete) | Log Compaction (compact) |
|---|---|---|
| Primary Purpose | Transient event streams (e.g. clickstreams, sensor logs) | State stores, entity changelogs, database tables |
| Retention Trigger | Message age (log.retention.hours) or partition byte limit | Superseded by a newer record with the same key |
| Storage Horizon | Messages expire and are purged after a configured number of days | The latest version of every key is preserved forever |
| Record Requirement | Keys are optional (key = null allowed) | Every record must have a non-null key |
Loading the rest of the lesson…