Kafka Log Retention vs Log Compaction
Kafka keeps data on disk according to each topic’s cleanup policy. With log retention (cleanup.policy=delete), whole log segments are deleted once they are older or larger than a limit. With log compaction (cleanup.policy=compact), Kafka keeps at least the latest record for every key and removes older records with the same key. Retention answers “how long do we keep the history?”, compaction answers “what is the current value of each key?”.
This article compares the two, explains how each works internally at the segment level, lists the settings that control them with their Kafka 4.4 defaults, and shows how to create and use each type of topic.
1. Background: Partitions Are Made of Segments
Each partition is stored as a series of segment files. Records are appended to the newest one, the active segment. When it reaches segment.bytes (1 GB by default) or segment.ms (7 days by default), it is closed and a new active segment starts. Both cleanup policies work on closed segments only: the active segment is never deleted or compacted. This detail explains most “why is my old data still there?” questions.
2. How Log Retention Works
With cleanup.policy=delete (the default), a background task on each broker regularly checks every partition and deletes closed segments that break a limit:
- Time: a segment is deleted when its newest record is older than
retention.ms(7 days by default). - Size: the oldest segments are deleted while the partition is larger than
retention.bytes(unlimited by default). The limit is per partition, not per topic.
Deletion moves the partition’s log start offset forward. Offsets are never reused; a consumer whose committed offset is now below the log start offset is reset according to auto.offset.reset.
3. How Log Compaction Works
With cleanup.policy=compact, the log cleaner threads on each broker rewrite closed segments, keeping only the latest record for each key:
- Dirty and clean parts. The part of the log already compacted is “clean”; newer closed segments are “dirty”. A partition becomes a candidate when the dirty share exceeds
min.cleanable.dirty.ratio(0.5 by default), or when records have stayed uncompacted longer thanmax.compaction.lag.ms. - Build a key map. The cleaner reads the dirty segments and records the latest offset for each key.
- Rewrite. It copies the segments, dropping every record whose key has a newer record, and swaps the new segments in. Offsets, order and timestamps of the kept records do not change.
- Tombstones. A record with a key and a
nullvalue is a delete marker. It removes older values of the key during compaction and is itself kept fordelete.retention.ms(1 day by default), so consumers that are reading have time to see the delete.
Compaction guarantees that a consumer reading from the start sees at least the latest value of every key, not only the latest value: records that are not yet compacted can still be read.
4. Retention vs Compaction Compared
Log retention (delete) | Log compaction (compact) | |
|---|---|---|
| Removes | Whole old segments, by age or size | Older records of a key that has a newer record |
| Keeps | Every record within the time or size window | At least the latest record per key, indefinitely |
| Keys | Optional | Required: records without a key are rejected |
| Deletes a key | Not possible individually | With a tombstone (null value) |
| Disk usage | Bounded by time or size | Bounded by the number of distinct keys |
| Typical data | Events: clicks, orders, logs | State: latest customer profile, configuration, changelogs |
| Examples in Kafka itself | Most application topics | __consumer_offsets, Kafka Streams changelog topics, Connect offset topics |
The two can be combined with cleanup.policy=compact,delete: the log is compacted, and segments older than retention.ms are also deleted. This suits keyed data where only recent keys matter, such as session state for the last 30 days.
5. Important Configuration
| Topic setting | Default | Effect |
|---|---|---|
cleanup.policy | delete | delete, compact, or both |
retention.ms | 604800000 (7 days) | Maximum age of a closed segment’s newest record; -1 means no time limit |
retention.bytes | -1 (unlimited) | Maximum size per partition |
segment.bytes | 1073741824 (1 GB) | Segment size; smaller segments are cleaned sooner |
segment.ms | 604800000 (7 days) | Rolls the active segment after this time, even if it is small |
min.cleanable.dirty.ratio | 0.5 | Compact when this share of the log is dirty |
min.compaction.lag.ms | 0 | Minimum time a record stays uncompacted |
max.compaction.lag.ms | unlimited | Maximum time before a record becomes eligible for compaction |
delete.retention.ms | 86400000 (1 day) | How long tombstones are kept |
Broker-level equivalents (log.retention.hours, log.cleanup.policy, and so on) set the defaults for topics that do not override them. The log cleaner itself is enabled by default and uses log.cleaner.threads (1 by default) per broker.
6. Practical Examples
6.1 Changing retention of an event topic
# Keep page-view events for 3 days instead of 7
$ bin/kafka-configs.sh --bootstrap-server localhost:9092 --alter \
--entity-type topics --entity-name page-views --add-config retention.ms=259200000
# Check the topic's overrides
$ bin/kafka-configs.sh --bootstrap-server localhost:9092 --describe \
--entity-type topics --entity-name page-views
6.2 Creating a compacted topic
$ bin/kafka-topics.sh --bootstrap-server localhost:9092 --create --topic customer-profiles \
--partitions 6 --replication-factor 3 \
--config cleanup.policy=compact \
--config min.cleanable.dirty.ratio=0.2 \
--config segment.ms=3600000
A lower dirty ratio and hourly segments let compaction run more often, at the cost of more cleaner I/O.
6.3 Updating and deleting keys from Java
public class CustomerProfilePublisher {
private static final String TOPIC = "customer-profiles";
private final KafkaProducer<String, String> producer;
public CustomerProfilePublisher(KafkaProducer<String, String> producer) {
this.producer = producer;
}
/** The newest profile per customer survives compaction. */
public void upsert(String customerId, String profileJson) {
producer.send(new ProducerRecord<>(TOPIC, customerId, profileJson));
}
/** A tombstone: the key with a null value removes the customer after compaction. */
public void delete(String customerId) {
producer.send(new ProducerRecord<>(TOPIC, customerId, null));
}
}
A service that needs the current state of all customers reads the topic from the beginning on startup, keeping the latest value per key in memory or a local store and removing keys when it reads a tombstone. Kafka Streams does exactly this for a KTable.
7. Real-World Use Cases
- Retention: clickstreams, application logs, order events and metrics, where the history matters for a limited time and replay is needed within that window.
- Compaction: customer or product reference data, feature flags and configuration, database change streams keyed by primary key, and Kafka Streams state changelogs.
- Both: device last-known state where devices inactive for 30 days can be forgotten.
8. Common Mistakes
- Expecting data to disappear exactly at
retention.ms: only closed segments are deleted, so data can live up tosegment.mslonger on low-traffic topics. - Sending records without keys to a compacted topic: the broker rejects them.
- Assuming a compacted topic contains only one record per key at any moment.
- Setting
retention.bytesthinking it applies per topic; it is per partition. - Retention shorter than consumer downtime, which deletes data before slow consumers read it.
9. Summary
Log retention deletes whole closed segments when they exceed a time or size limit, keeping a window of history. Log compaction rewrites closed segments to keep at least the latest record per key, preserves offsets and uses tombstones to delete keys. Use retention for events, compaction for state, and both for keyed data that also expires. In both cases the active segment is untouched, so segment settings decide how soon cleanup can happen.
10. Related Reading
11. References
Kafka Log Retention and Compaction Interview Questions and Answers
Common interview questions on Kafka Log Retention and Compaction, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. What is the difference between Kafka log retention and log compaction?
Answer: Retention (cleanup.policy=delete) deletes whole closed segments when they are older than retention.ms or the partition is larger than retention.bytes, keeping a window of complete history. Compaction (cleanup.policy=compact) rewrites closed segments to keep at least the latest record per key and drop older records of the same key, so the topic holds the current state of every key indefinitely. Retention suits event streams; compaction suits keyed state such as profiles, configuration or changelogs.
Q. Why are records older than retention.ms sometimes still on disk?
Answer: Retention deletes whole segments, and only closed ones. A segment is deleted when its newest record is older than retention.ms, and the active segment is never deleted. On a low-traffic topic, the active segment may stay open until segment.ms (7 days by default) rolls it, so data can live noticeably longer than the retention setting. The deletion check also runs periodically, not continuously.
Intermediate questions
Q. Does a compacted topic contain only the latest record for each key?
Answer: No. Compaction guarantees at least the latest record per key. The active segment is never compacted, and closed segments are cleaned only when the dirty share exceeds min.cleanable.dirty.ratio or max.compaction.lag.ms forces it. Until then, older values of a key are still readable, so consumers must treat later records of a key as overriding earlier ones.
Q. What happens to offsets after compaction, and how should consumers handle it?
Answer: Kept records retain their original offsets, order and timestamps; removed records leave gaps. Consumers do not need special handling: they fetch from their position and simply get the next existing offset. Code must not assume that offsets are contiguous, for example by calculating a record count from offset differences.
Q. When would you use cleanup.policy=compact,delete?
Answer: For keyed state that should also expire. The log is compacted to the latest value per key, and segments older than retention.ms are deleted as well, so keys that have not been updated within the retention period disappear. Examples are last-known state of devices that may go permanently offline, or session data that is irrelevant after a few weeks.
Tricky and scenario questions
Q. Disk usage of a compacted topic keeps growing although the number of keys is stable. What do you check?
Answer: Whether compaction runs at all: the log cleaner threads can stop after an error, which shows in the broker’s log-cleaner log and in cleaner metrics such as the time since the last run and the maximum dirty percentage. Then the settings: a high min.cleanable.dirty.ratio or a large segment.ms/segment.bytes keeps data in uncleanable or not-yet-dirty-enough segments, and a large min.compaction.lag.ms delays cleaning. Also confirm that producers really reuse keys, since unique keys per record make compaction useless.