How does Kafka's log retention policy work?

Instruction: Explain the mechanisms Kafka uses for log retention and how these can be configured.

Context: This question explores the candidate's knowledge of Kafka's data retention policies, crucial for managing data lifecycle and storage within a Kafka cluster.

Updated

Official answer

Kafka appends records to partition log segments. Retention determines which older segments are eligible for deletion; it is independent of whether every consumer has read the records.

Use topic-level retention.ms and retention.bytes with cleanup.policy=delete. The byte limit is per partition, not per whole topic. Broker settings such as log.retention.ms provide defaults, while explicit topic settings override them. If time and size limits are both enabled, either can make old data eligible for removal.

A topic configuration change in current Kafka uses the Admin API or kafka-configs.sh with --bootstrap-server, --entity-type topics, the intended topic name, and --add-config retention.ms=604800000 for a seven-day time setting. Use --alter only after reviewing the current policy and deletion impact. The old --zookeeper topic command and topic-level log.retention.hours example are inappropriate for Kafka 4.x.

Deletion operates through segment/cleanup behavior; the configured time is not an exact individual-record erasure deadline or a guarantee that disk use never temporarily exceeds the target. Reducing a limit can permanently remove replay history, so verify the change in a disposable environment and plan recovery requirements first.

cleanup.policy=compact instead cleans superseded keyed values, and compact,delete combines both policies. Monitor the effective topic configuration, oldest available data, disk headroom and consumer lag. A seven-day time setting does not ensure seven days of history if a smaller byte cap binds first.

Sources

Kafka topic configuration; current topic administration commands.

Related Questions