ML
Apache Kafka

Kafka Log Compaction Tombstones: Why Premature Cleaner Sweeps Resurrected Deleted Records

A tombstone deletion marker with a null value is retained only until delete.retention.ms expires. When cleaner threads purge tombstones before slow consumers or recovering replicas read them, deleted records reappear as active state. How cleaner lag, compaction mechanics, and retention windows prevent state corruption.

November 29, 202612 min readKafkaDistributed SystemsStorageEvent StreamingArchitecture

During a post-incident audit in an e-commerce platform, our operations team discovered that user accounts and balance updates explicitly deleted days earlier were reappearing across downstream reporting services. The affected microservices consumed a compacted Kafka topic serving as an authoritative changelog for customer profile state. A customer who opted out under data privacy regulations had their record purged, yet 48 hours later, a batch analytical service replayed the topic from an earlier checkpoint and emitted notifications to the deleted user.

The root cause was not an application bug or an inadvertent database restore. It was a subtle distributed systems race condition in Kafka log compaction: tombstone deletion markers had been permanently pruned by cleaner threads before a lagging consumer service caught up with the log head.

1. How Kafka Log Compaction Operates

In standard Kafka topics, log retention is governed by time (log.retention.hours) or segment size (log.retention.bytes). When retention thresholds are exceeded, the oldest log segments are deleted wholesale from disk.

For key-value changelog topics, Kafka provides log compaction. Instead of deleting entire segments by age, compaction ensures that Kafka retains at least the latest known value for each message key within the partition log:

  • Clean Log: Segments that have already been compacted by the cleaner thread. Each key appears at most once in this portion of the partition.
  • Dirty Log: Newly appended segments where multiple updates for the same key may coexist.
  • Active Segment: The segment currently receiving write appends from producers. The active segment is never touched by the cleaner thread.

When the ratio of dirty records to total records exceeds min.cleanable.dirty.ratio (default 0.5), the background LogCleaner thread selects eligible dirty segments. It builds an in-memory hash table called SkimpyOffsetMap, which maps an 8-byte MD5 digest of each message key to its largest dirty offset. The cleaner then sequentially copies older segments to new clean segments, discarding any record whose offset is strictly smaller than the offset stored in the map.

2. The Tombstone Deletion Lifecycle

To delete a key in a compacted topic, a producer cannot simply issue an HTTP DELETE or an SQL DROP command. Instead, the producer must write a tombstone record:

// Writing a tombstone deletion marker in Kafka:
ProducerRecord<String, String> tombstone = new ProducerRecord<>(
    "customer-profiles",
    customerId,
    null // null payload signals tombstone deletion
);
producer.send(tombstone).get();

When downstream consumers read a record with a non-null key and a null value, they interpret it as an instruction to delete the corresponding key from their local caches, RocksDB stores, or relational tables.

However, Kafka cannot keep tombstones in the log indefinitely; doing so would cause disk usage to grow without bound. Kafka manages tombstone lifespan using the topic-level configuration delete.retention.ms (default 86,400,000 milliseconds, or 24 hours):

  1. The producer writes a tombstone at offset N.
  2. The cleaner thread compacts the dirty segment. It recognizes the record has a null payload, updates older records with that key, but preserves the tombstone in the clean segment.
  3. Once the segment containing the tombstone rolls and its modification timestamp exceeds delete.retention.ms, the next cleaner pass permanently discards the tombstone from disk.

3. The Resurrection Race Condition

The failure occurs when a consumer group or a restored follower replica falls behind the tombstone retention window:

Timeline of Record Resurrection:
T0: Key "user-409" written at offset 100 with value "active".
T1: Key "user-409" written at offset 500 with value null (Tombstone).
T2: Downstream Consumer A reads offset 500 and deletes "user-409" locally.
T3: 24 hours pass. delete.retention.ms expires.
T4: Log cleaner runs. Tombstone at offset 500 is completely removed from disk.
    Offset 100 had previously been compacted, but if an older uncompacted
    segment was pending, or if a consumer resets its offset to 0:
T5: Downstream Consumer B initializes from offset 0 (or reprocesses from offset 50).
T6: Consumer B reads offset 100 ("active"). Because offset 500 no longer exists,
    Consumer B never receives the null tombstone.
T7: Key "user-409" is resurrected as an active user in Consumer B.

The same vulnerability strikes when a broker node suffers storage failure and an administrator restores data from a day-old cold backup, or when an offline follower replica rejoins after prolonged network partitioning. If the leader has already discarded tombstones, the follower re-replicates historical records that it should have deleted.

4. Architectural Remediation

A. Align delete.retention.ms with Consumer Lag SLAs

Never leave delete.retention.ms at an arbitrary low value if consumers can be offline over a weekend or during recovery windows. For critical state stores, increase tombstone retention to match your maximum acceptable consumer lag and backup recovery objectives:

# Extend tombstone retention to 7 days:
kafka-configs --bootstrap-server kafka:9092 --alter   --entity-type topics --entity-name customer-profiles   --add-config delete.retention.ms=604800000

B. Enforce min.compaction.lag.ms

By default, min.compaction.lag.ms is 0, meaning newly written records and tombstones become eligible for compaction as soon as an active segment rolls. To ensure all active real-time consumers have an enforced minimum time window to observe tombstones before cleaner passes execute, configure a compaction lag floor:

# Enforce a 24-hour immunity period before any record is compacted:
kafka-configs --bootstrap-server kafka:9092 --alter   --entity-type topics --entity-name customer-profiles   --add-config min.compaction.lag.ms=86400000

C. Monitor Log Cleaner Performance Metrics

Track JMX metrics on your Kafka brokers to identify stalled cleaner threads before dirty segments accumulate and cleaner cycles skip critical retention boundaries:

// Key JMX MBeans to monitor:
kafka.log:type=LogCleanerManager,name=max-dirty-percent
kafka.log:type=LogCleaner,name=cleaner-recopy-percent
kafka.log:type=LogCleaner,name=DeadThreadCount

If max-dirty-percent remains near 100 percent, the cleaner thread is starved of I/O or memory, delaying tombstone transitions and risking unexpected burst compaction.

Summary

Compacted Kafka changelogs guarantee eventual consistency only if consumers process events faster than the tombstone garbage collection cycle. When delete.retention.ms is shorter than consumer downtime or replication recovery windows, purged tombstones allow historical records to resurrect undetected. Setting appropriate compaction lags, extending tombstone retention, and alerting on cleaner thread health eliminates state discrepancies across distributed streaming systems.

SharePostLinkedIn

Reader Discussion

7 replies// weighed in

TopNewestAuthor
Add to the thread
Disagree, agree harder, or share your own experience…
Email instead →markdown okbe kind
  1. Highlighted by author
    Tuấn Phạm🇻🇳 HCMC· Staff Engineer · Tiki Data PlatformStory

    min.insync.replicas=2 với acks=all là combo chuẩn. Bọn em từng để mặc định min.insync.replicas=1, một broker rolling restart là mất 4 message — xui là đúng cái event payment confirm. Ngồi viết postmortem từ 2h sáng đến 7h.

    Nov 30, 2026·1 day later
    • ML
      Minh LeAuthor

      Đúng cái khoảnh khắc realize default = 1 thì đã muộn. Cảm ơn bro share — mình sẽ thêm warning box vô post.

      Nov 30, 2026
  2. Derek Okonkwo· Principal Engineer · FintechAgrees

    The Kafka→anything-else caveat is the single most important paragraph in this post. I cannot count how many "exactly once" pipelines I've reviewed that write to Postgres without an outbox and the team still calls it EOS. It's at-least-once with extra steps and a worse mental model.

    Nov 30, 2026·1 day later
  3. Sven Bergström· Senior SWEStory

    fresh transactional.id on each pod restart is THE silent killer. We had it for ~14 months. Realised when a zombie producer wrote 80k duplicates after a node went catatonic and came back.

    Dec 04, 2026·5 days later
  4. Quốc Anh· Backend Lead · FinhayAgrees

    Đoạn segment files giải thích quá ngắn gọn. Bọn em hay quên log.segment.bytes vs log.retention.bytes là 2 thằng khác nhau, bị retention không kick in là vì segment chưa rolled — đúng cái rule of thumb cuối bài.

    Dec 01, 2026·2 days later
  5. Amelia Brooks· Distributed SystemsPushback

    tiny nit but acks=0 is not literally fire-and-forget at the protocol layer — the producer still writes to its socket buffer. The 'forget' is the broker side. Pedantic but bites people in metrics dashboards.

    Dec 08, 2026·1 week later
  6. Rachel Gold· Staff SREAgrees

    the on-call framing throughout this piece is what makes it land. too many infra articles assume you never get paged. those are written by people who never got paged.

    Dec 02, 2026·3 days later

Worked on something similar? Email ducminhldm@gmail.com — I read every one. The good ones become future posts.

Comments seeded · live discussion via email