Log compaction is a data retention mechanism in distributed streaming platforms that ensures only the most recent record for each message key is retained by purging older records with identical keys. Unlike time-based retention, which deletes data after a fixed duration, compaction operates on a per-key basis, transforming the log from a complete history into a snapshot of the latest state. This process is essential for restoring state after a failure or for bootstrapping a new consumer without replaying the entire event history.
Glossary
Log Compaction

What is Log Compaction?
A data retention strategy for distributed event logs that selectively removes obsolete records to preserve storage space while maintaining the latest state for each unique key.
The mechanism works by identifying duplicate keys across a log's segments and removing older entries during a background cleanup process, leaving a compacted log that contains the last known value for every key. This is particularly critical for use cases like maintaining a **KTable** in Apache Kafka or restoring a state store in stream processors, where only the current state matters, not the sequence of changes that led to it. A tombstone record—a message with a key and a null value—can also be written to explicitly delete a key from the compacted log.
Key Characteristics of Log Compaction
Log compaction is a data retention strategy that transforms a stream of updates into a snapshot of the latest state by removing obsolete records sharing the same key.
Snapshot Semantics
Unlike time-based retention, log compaction retains the last known value for every unique message key. It operates by removing older records with identical keys, effectively turning the log into a key-value store of current state. This is critical for restoring stateful services after failure or scaling operations.
- Guarantees at least one record per key
- Deletes are signaled by a tombstone record (a record with a null value)
- Compaction runs as a background process on immutable segments
Tombstone Records and Deletion
To explicitly delete a key from the compacted log, a producer sends a tombstone—a record with the key and a null value. The compaction process retains this tombstone for a configurable period (delete.retention.ms) before physically removing it.
- Prevents deleted keys from reappearing on partition leader changes
- Consumers must handle null values as explicit delete signals
- Tombstone retention must be longer than the maximum expected consumer downtime
Offset Management Implications
Log compaction breaks the strict sequential offset guarantee. Since records with duplicate keys are removed, offsets become non-contiguous. Consumers cannot assume that offset N+1 exists just because offset N was consumed.
- Consumers must not rely on offset gaps for logic
- Re-consuming a compacted topic from offset 0 yields only the latest value per key
- Ideal for KTable state restoration in Kafka Streams
Use Cases and Anti-Patterns
Log compaction excels for state restoration and change data capture scenarios where the current value matters more than the full history.
- Ideal: Database changelogs, Kafka Streams state stores, shipping addresses
- Anti-pattern: Immutable event logs (e.g., financial transactions, clickstreams) where every event must be retained
- Anti-pattern: Topics with infinite unique keys, as compaction cannot delete any records
Compaction vs. Retention
Standard time-based retention deletes entire segments after a time threshold. Log compaction operates on key granularity within segments, merging non-compacted segments into compacted ones.
- Time-based: Deletes all records older than T
- Compaction: Deletes older records with the same key, regardless of age
- Both policies can be combined: a topic can have both
retention.msandcleanup.policy=compact
Segment and Cleaner Mechanics
The Log Cleaner thread builds an in-memory offset map for each compacted segment. It scans from the latest segment backward, retaining only the highest offset for each key.
- Operates on immutable segments; never modifies the active segment
- Dirty ratio (
min.cleanable.dirty.ratio) controls when cleaning triggers - A segment is eligible when the ratio of dirty (obsolete) to total records exceeds the threshold
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Frequently Asked Questions
Clear, technically precise answers to the most common questions about log compaction, a critical data retention mechanism in distributed streaming platforms.
Log compaction is a data retention mechanism in distributed streaming platforms that selectively removes older records from a log based on their key, ensuring that only the last known value for each unique message key is retained. Unlike time-based or size-based retention policies that delete entire segments of a log wholesale, compaction operates granularly. When the compaction process runs, it scans the log, identifies all records sharing the same key, and physically deletes all but the most recent one. This transforms the log from a complete chronological history into a snapshot of the latest state for every key. The mechanism relies on a background thread, often called the Log Cleaner, which iterates over inactive log segments, builds an in-memory offset map of the latest occurrence of each key, and recopies the segment omitting the stale duplicates. This process is non-blocking for active producers and consumers, operating on closed segments only. The result is a compacted topic that serves as a persistent, key-indexed state store, ideal for restoring state after a failure or bootstrapping a new service instance.
Related Terms
Understanding log compaction requires familiarity with the broader streaming ecosystem. These concepts define how compacted topics interact with state stores, fault tolerance, and data serialization.
State Store
A persistent or in-memory storage engine used by stream processors to maintain the intermediate state required for stateful operations like aggregations and joins.
- Relationship to Compaction: A compacted topic acts as a durable, external changelog for a state store. During recovery, the store can be rebuilt by replaying the compacted topic, reading only the latest value for each key.
- RocksDB is a common local state store implementation that leverages compaction for efficient lookups.
Checkpointing
A fault-tolerance mechanism that periodically saves the state of an operator or application to durable storage, enabling recovery from failures without data loss.
- Distinction: Checkpointing captures the entire internal state of a processing graph (including offsets and local state), while log compaction provides a changelog-based recovery path.
- In frameworks like Apache Flink, checkpoints are coordinated, globally consistent snapshots, whereas a compacted topic is an asynchronous, continuous cleanup process.
Change Data Capture (CDC)
A design pattern that identifies and captures row-level changes to a source database and streams them as events to downstream systems in real-time.
- Synergy: CDC tools like Debezium often stream database changes into compacted Kafka topics. The compaction ensures the topic retains the current state of every database row, making it a perfect source for rebuilding materialized views.
- This pattern effectively turns a database's transaction log into a scalable, queryable event stream.
Kappa Architecture
A software architecture pattern that treats all data as a stream, using a single stream processing engine for both real-time and batch processing.
- Role of Compaction: In a Kappa architecture, compacted topics serve as the long-term, queryable master dataset. Reprocessing historical data is done by simply replaying the compacted log, eliminating the need for a separate batch layer.
- This unifies operational and analytical data pipelines under a single streaming backbone.
Schema Registry
A centralized service that stores and manages the schemas for data formats like Apache Avro or Protobuf, ensuring compatibility and enforcing governance in data pipelines.
- Critical Dependency: Log compaction relies on stable, consistent message keys. A schema registry enforces backward and forward compatibility on the key schema, preventing compaction failures caused by serialization mismatches.
- Without schema governance, a change to the key structure can render an entire compacted topic unrecoverable.
Materialized View
A pre-computed, persisted result of a query, continuously updated by a stream processor, providing low-latency read access to aggregated or joined data.
- Implementation: A materialized view is often backed by a state store that is itself populated and restored from a compacted topic. The compaction ensures the view's underlying dataset remains bounded in size.
- This pattern is fundamental to CQRS, where the query model is a materialized view built from a compacted event stream.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us