Kafka: Log compaction keeps the latest value per key for ever

It turns a topic into a changelog you can replay to rebuild state.

Code
# Topic config
cleanup.policy=compact
min.cleanable.dirty.ratio=0.5

# a record with a null value is a TOMBSTONE - it deletes the key
producer.send(new ProducerRecord<>("users", "user-7", null));
Output
Before: user-7=Ada, user-7=Ada2, user-8=Ben, user-7=Ada3
After:  user-7=Ada3, user-8=Ben

A null value removes the key entirely once the tombstone expires.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11