Explain the use of compacted topics in Kafka and their use cases.

Instruction: Describe how log compaction works in Kafka and discuss scenarios where compacted topics are particularly useful.

Context: Assesses when a compacted topic is appropriate for current keyed state, how consumers reconstruct that state, and why it cannot preserve complete event history.

Updated

Official answer

Use a compacted topic when consumers need to reconstruct current keyed state, such as the latest configuration or a table's change-data-capture image. Compaction deliberately removes superseded values; it does not preserve the complete history of changes and cannot replace an immutable event/audit log.

Model the key as a stable entity identifier and the value as the state needed for reconstruction. For an inventory record, a value such as quantity=8 can replace an earlier quantity=10. A delta such as decrement by 2 cannot generally replace all earlier deltas: replaying only the latest delta would produce the wrong state. Keep an event-history topic separately if those operations must remain auditable.

A new consumer builds its local map by replaying retained records, applying later values and deleting keys on tombstones. It must tolerate multiple versions before asynchronous cleaning completes and must satisfy the tombstone-retention scan requirements. Kafka is still an ordered log; compaction does not provide a point lookup API or a globally atomic snapshot across partitions.

Use cleanup.policy=compact when retaining current keyed values is the goal. If time/size deletion is also enabled, old last-known values may expire, so a rebuild may require an external snapshot plus a correctly aligned log position. Choose key partitioning consistently; compaction acts within a partition.

Validate a full rebuild, updates, deletions and a lagging consumer before relying on the topic for recovery. Measure retained bytes and rebuild time, but do not promise a fixed storage bound from compaction alone: key cardinality, record sizes, active segments and cleaner progress still matter.

Sources

Kafka log compaction semantics; cleanup policies and tombstone retention.

Related Questions