Replication, ISR, Retention and Compaction

Replication, ISR, Retention and Compaction in Apache Kafka: sets how many copies of each partition exist.

Replication

replication.factor sets how many copies of each partition exist. One is the leader; the rest are followers that continuously fetch from the leader.

partition orders-0, RF=3

  b1: LEADER    [0..500]   ← all client traffic
  b2: follower  [0..500]   ← caught up
  b3: follower  [0..487]   ← lagging

Followers serve no client traffic by default. They exist so that losing a broker does not lose data.

RF=3 is the standard for production: it tolerates one broker loss while still allowing min.insync.replicas=2. RF=1 means a single broker failure permanently loses that partition's data — acceptable only for genuinely disposable streams. Spread replicas across racks or availability zones, otherwise "three copies" can share one failure domain.

In-sync replicas (ISR)

The ISR is the set of replicas considered caught up with the leader. A follower drops out if it stops fetching or falls too far behind in time (replica.lag.time.max.ms), and rejoins when it catches up.

ISR is the pivot on which durability turns:

RF=3, min.insync.replicas=2

ISR={b1,b2,b3}  acks=all writes succeed, 1 failure tolerated
ISR={b1,b2}     acks=all writes succeed, 0 failures tolerated
ISR={b1}        acks=all writes REJECTED (NotEnoughReplicas)

Only ISR members are eligible for leader election, which is what makes committed data safe. If you enable unclean.leader.election.enable=true, an out-of-sync replica may become leader — restoring availability at the cost of silently truncating committed records. Leave it off unless you have consciously decided that availability outranks durability for that topic.

Under-replicated partitions — partitions whose ISR is smaller than their replica set — is the single best broker-health alarm. A sustained non-zero count means you are one failure away from either data loss or rejected writes.

Retention: how data leaves

Kafka deletes by segment, on whichever limit hits first.

SettingMeaning
retention.msDelete segments older than this
retention.bytesDelete oldest segments once the partition exceeds this size (per partition, not per topic)
segment.ms / segment.bytesWhen to roll a new segment; only closed segments are eligible for deletion

Two things people get wrong. First, retention.bytes is per partition, so total topic storage is roughly that value times partitions times replication factor — easy to under-estimate by an order of magnitude. Second, retention is enforced at segment granularity, so a topic can hold data slightly older than retention.ms until the active segment rolls.

Retention is not just a storage setting; it is your replay budget. Seven days of retention means you can reprocess at most seven days of history. If your disaster-recovery plan is "replay the topic", retention has to cover the worst-case detection-plus-fix window.

Compaction: keeping the latest value per key

cleanup.policy=compact changes the model. Instead of deleting by age, the log cleaner removes superseded records: for each key, older values are eventually removed and the most recent one is retained forever.

before compaction
  k=A v=1 | k=B v=1 | k=A v=2 | k=C v=1 | k=A v=3 | k=B v=2

after compaction
  k=C v=1 | k=A v=3 | k=B v=2

Offsets of surviving records do not change; gaps simply appear. A compacted topic is therefore a durable, replayable table — a new consumer reading from the beginning reconstructs current state for every key.

Deletion in a compacted topic uses a tombstone: a record with a real key and a null value. The cleaner keeps the tombstone for delete.retention.ms so consumers have a chance to observe the delete, then removes the key entirely.

Details that matter:

  • Compaction requires non-null keys. A null-keyed record in a compacted topic cannot be compacted meaningfully.
  • Compaction is asynchronous and best-effort. It works on the "dirty" portion of the log, governed by min.cleanable.dirty.ratio. Duplicates for a key can survive for a while, so consumers must still tolerate seeing older values.
  • cleanup.policy=compact,delete combines both: keep the latest per key, but still age out very old data.

Choosing between them

UsePolicyReasoning
Order placed, click, sensor readingdelete with a time windowFacts that stop mattering; you want a bounded replay window
Customer profile, product catalogue, configcompactCurrent value per key must survive indefinitely
Audit trail for compliancedelete with long retention, or archive to object storageYou need every event, not just the latest
Stream-processing state changelogcompactState is restored by replaying latest-per-key

A common mistake is compacting an event stream. If every event for a key is meaningful history, compaction destroys it: Deposited(50) and Withdrawn(20) are not versions of each other. Compaction is for state, not for events.

Storage arithmetic worth doing before launch

daily bytes = records/day x avg record size (post-compression)
topic bytes = daily bytes x retention days x replication factor
add headroom for: segment rolls, index files, replica catch-up bursts

Brokers that run out of disk fail in a genuinely unpleasant way, and recovery involves either deleting data under pressure or adding capacity to a degraded cluster. Alert on disk usage trend, not just a static threshold.


Exercise: A team stores current inventory levels as events on a topic with retention.ms=86400000 (one day) and cleanup.policy=delete. After a bad deploy they need to rebuild a downstream cache from scratch and discover items that have not changed in two days are simply absent. Explain what went wrong conceptually, specify the topic configuration you would use instead, and describe what the producers must guarantee for that configuration to work.