00:00

Kafka Log Retention vs Log Compaction

Last updated:

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:

Kafka log compaction before and afterBefore compaction the log holds offset 0 key K1 value v1, offset 1 K2 v1, offset 2 K1 v2, offset 3 K3 v1, offset 4 K2 null which is a tombstone, and offset 5 K1 v3 in the active segment. After compaction the closed part keeps offset 2 K1 v2, offset 3 K3 v1 and the tombstone at offset 4; offsets 0 and 1 are removed. Offsets do not change, leaving gaps. The active segment with offset 5 is not compacted. The tombstone itself is removed after delete.retention.ms. Before cleaning offset 0K1: v1 offset 1K2: v1 offset 2K1: v2 offset 3K3: v1 offset 4K2: null offset 5K1: v3 closed segments: eligible for cleaning active segment After cleaning offset 2K1: v2 offset 3K3: v1 offset 4K2: null offset 5K1: v3 offsets 0, 1 removed Offsets keep their values (gaps are normal). The tombstone for K2 stays for delete.retention.ms, then it is removed too.
Compaction removes superseded records from closed segments, keeps the latest value per key and leaves offsets unchanged. The active segment is never compacted.
  1. 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 than max.compaction.lag.ms.
  2. Build a key map. The cleaner reads the dirty segments and records the latest offset for each key.
  3. 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.
  4. Tombstones. A record with a key and a null value is a delete marker. It removes older values of the key during compaction and is itself kept for delete.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)
RemovesWhole old segments, by age or sizeOlder records of a key that has a newer record
KeepsEvery record within the time or size windowAt least the latest record per key, indefinitely
KeysOptionalRequired: records without a key are rejected
Deletes a keyNot possible individuallyWith a tombstone (null value)
Disk usageBounded by time or sizeBounded by the number of distinct keys
Typical dataEvents: clicks, orders, logsState: latest customer profile, configuration, changelogs
Examples in Kafka itselfMost 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 settingDefaultEffect
cleanup.policydeletedelete, compact, or both
retention.ms604800000 (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.bytes1073741824 (1 GB)Segment size; smaller segments are cleaned sooner
segment.ms604800000 (7 days)Rolls the active segment after this time, even if it is small
min.cleanable.dirty.ratio0.5Compact when this share of the log is dirty
min.compaction.lag.ms0Minimum time a record stays uncompacted
max.compaction.lag.msunlimitedMaximum time before a record becomes eligible for compaction
delete.retention.ms86400000 (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

Terminal
# 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

Terminal
$ 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

CustomerProfilePublisher.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 to segment.ms longer 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.bytes thinking 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.

11. References