Compacted Topics, Log Deduplication, Changelog Topics
Difficulty: Senior | Asked at: Confluent, LinkedIn, Uber
âšī¸Interview Context
Compacted topics are fundamental to Kafka's state management. Interviewers expect you to understand how compaction works, when to use it, and how changelog topics enable exactly-once processing.
The Question
How do Kafka compacted topics work? Explain the log compaction process and how changelog topics enable state management in Kafka Streams.
A strong answer has three parts: what compaction guarantees, which knobs control it, and why stream-processing state depends on it. Start with the guarantee, because most candidates get it wrong. Compaction does not drop old records on a timer the way retention does. It rewrites the active log so that the newest value for each key survives, tombstones propagate deletions, and keys that never reappear are removed entirely. Then walk through the cleaner: the log is divided into segments, only closed segments are eligible, and the cleaner builds a key-and-offset index to decide what to keep. Finish with changelog topics, because that is where the mechanism pays off: every Kafka Streams state store is backed by a compacted changelog, so local RocksDB state can be rebuilt after a crash by replaying one compacted topic instead of re-reading the entire input stream from the beginning of time.
Compacted Topic Basics
How Compaction Works
Think of a compacted topic as a materialized table that happens to be stored as an append-only log. Producers keep writing updates for the same entity keys â user profiles, configuration entries, consumer cursor positions â and compaction trims the history so the log stays bounded by the number of distinct keys rather than by the number of writes. Three properties matter in interviews. First, compaction never removes the latest value for a key: the newest record for every live key is always retained, so a consumer reading from the earliest available offset can rebuild full current state. Second, order within a key is preserved: surviving values appear oldest-first, so replay is deterministic. Third, compaction runs per partition inside the broker's log cleaner, in the background â it is not a query, not a synchronous delete command, and not something a produce call waits on.
Before Compaction:
Offset: 0 1 2 3 4 5 6 7
Key: A=1 B=2 A=3 C=1 B=4 A=5 C=2 B=6
â â â â
Latest A Latest B Latest A Latest B
After Compaction:
Offset: 0 1 2 3 4 5 6 7
Key: A=1 B=2 A=3 C=1 B=4 A=5 C=2 B=6
(old A deleted, old B deleted, old C deleted)
Result:
Offset: 2 3 4 5 6 7
Key: A=3 C=1 B=4 A=5 C=2 B=6
Compaction guarantees:
1. For each key, at least one value remains
2. Newer values are never deleted
3. Order within key is preserved (newest value appears last)
Compaction Configuration
# Topic-level compaction configuration
from kafka.admin import KafkaAdminClient, NewTopic
admin = KafkaAdminClient(bootstrap_servers='localhost:9092')
# Create compacted topic
topic = NewTopic(
name='user-sessions',
num_partitions=6,
replication_factor=3,
topic_configs={
'cleanup.policy': 'compact', # Enable compaction
'min.cleanable.dirty.ratio': 0.3, # 30% dirty triggers clean
'segment.ms': 604800000, # 7 days
'delete.retention.ms': 86400000, # 24 hours for tombstones
'min.compaction.lag.ms': 0, # No minimum lag
'max.compaction.lag.ms': 604800000 # Max 7 days before compaction
}
)
admin.create_topics([topic])
Compaction Properties
compaction_properties = {
'cleanup.policy': {
'delete': 'Default. Delete segments after retention.',
'compact': 'Enable log compaction.',
'compact,delete': 'Both compaction and deletion.'
},
'min.cleanable.dirty.ratio': {
'description': 'Ratio of dirty (uncompacted) messages to trigger cleaning.',
'default': 0.5,
'range': '0.0 to 1.0',
'recommendation': '0.3 for frequent compaction'
},
'segment.ms': {
'description': 'Time before segment is eligible for compaction.',
'default': 604800000, # 7 days
'recommendation': 'Lower for faster compaction'
},
'delete.retention.ms': {
'description': 'How long tombstone markers are retained.',
'default': 86400000, # 24 hours
'recommendation': 'Match your delete expectations'
}
}
Choosing among the cleanup policies is a per-topic decision that interviewers like to probe:
| Policy | Keeps | Bounded by | Typical use |
|---|---|---|---|
| delete | every record until retention expires | retention.ms and retention.bytes | event streams, logs, CDC outboxes |
| compact | newest value per key, plus live tombstones | number of distinct keys | tables, config topics, changelog topics |
| compact,delete | compacted state, but compacted segments also age out | key count plus delete.retention.ms | state topics that must also shrink when keys vanish long ago |
â ī¸Compaction Warning
Compaction is NOT real-time. There's a delay between writing and compaction. Don't rely on immediate deduplication. Use min.cleanable.dirty.ratio=0.1 for more frequent compaction.
Tombstone Records
What are Tombstones
A tombstone is a record whose value is null. Writing one tells every downstream consumer that the key has been deleted, and during the next cleaning pass the broker removes both the tombstone and the last real value for that key â but only after delete.retention.ms has elapsed. That delay is deliberate: consumers that are lagging, or that restarted from the earliest offset, must still observe the deletion before the evidence disappears. If delete.retention.ms is shorter than the worst consumer lag, a slow consumer can miss the tombstone entirely and resurrect the key in its local state. The practical rule is to set delete.retention.ms well above your maximum expected lag â 24 hours is the common floor â and to treat every consumer of a compacted topic as responsible for handling null values rather than crashing on them.
# Tombstone = key with null value
# Signals deletion of a key
# Writing a tombstone
producer.send('user-sessions', key=b'user123', value=None)
# Tombstone behavior:
# 1. Tombstone is written to topic
# 2. During compaction, tombstone deletes the key
# 3. Tombstone is removed after delete.retention.ms
# Tombstone retention
tombstone_retention = {
'delete.retention.ms': 86400000, # 24 hours
'purpose': 'Allow consumers to see deletion',
'cleanup': 'Tombstone removed after retention period'
}
Tombstone Handling
class TombstoneHandler:
"""
Handle tombstone records in compacted topics.
"""
def __init__(self):
self.active_keys = {}
def process_message(self, key, value):
"""
Process message from compacted topic.
If value is None, it's a tombstone (deletion).
"""
if value is None:
# Tombstone - key should be deleted
if key in self.active_keys:
del self.active_keys[key]
log.info(f"Key {key} deleted via tombstone")
else:
# Regular message - update state
self.active_keys[key] = value
def get_state(self):
"""Get current state (all non-deleted keys)"""
return self.active_keys.copy()
Changelog Topics
How Changelog Topics Work
Kafka Streams keeps record-level state â counts, joins, windowed aggregations â in local RocksDB stores for speed, but local disk is disposable. Every mutation is therefore written to a dedicated changelog topic before the state store update counts as durable. The changelog is compacted by default, because its purpose is to hold the current value per key, not an infinite history. On restart, Streams restores each store by reading the changelog partition assigned to that task from the earliest available offset, rebuilding exactly the key space the task owned before the failure. Two configuration details come up in interviews. The changelog cleanup policy is always compact â if you override it to delete, restoration can no longer guarantee the full key set. And stores that never need restoration, such as metrics gauges or aggregates you can cheaply recompute from the input topic, can be created with logging disabled, which removes the changelog topic and its write amplification entirely.
Kafka Streams Changelog:
1. Processor maintains local state store
2. State changes written to changelog topic
3. Changelog topic is compacted
4. On failure, state rebuilt from changelog
Processor Flow:
Input Event â Update State â Write to Changelog Topic
State Recovery:
Read Changelog Topic â Rebuild Local State â Resume Processing
Example:
Event: {user: "alice", action: "login"}
State Update: {alice: {login_count: 1}}
Changelog: alice â {login_count: 1}
Event: {user: "alice", action: "purchase"}
State Update: {alice: {login_count: 1, purchases: 1}}
Changelog: alice â {login_count: 1, purchases: 1}
Changelog Topic Configuration
from kafka.streams import StreamsBuilder, Materialized
from kafka.streams.state import RocksDBStore
# Changelog topic configuration
changelog_config = {
'changelog.replication.factor': 3,
'changelog.num.partitions': 1,
'changelog.retention.ms': 604800000, # 7 days
'changelog.cleanup.policy': 'compact'
}
# Materialized state store with changelog
builder = StreamsBuilder()
stream = builder.stream('input-topic')
# Aggregate with state store
aggregated = (
stream
.group_by_key()
.aggregate(
initializer=lambda: {'count': 0},
aggregator=lambda key, value, agg: {
'count': agg['count'] + 1,
'last_value': value
},
materialized=Materialized.as('user-counts')
.with_key_serde(Serdes.String())
.with_value_serde(JsonSerde())
.with_logging_enabled() # Enable changelog
.with_config(changelog_config)
)
)
Changelog Topic Naming
# Changelog topic naming convention
# {application.id}-{store.name}-changelog
# Example:
# application.id: user-analytics
# store.name: user-counts
# changelog topic: user-analytics-user-counts-changelog
# Internal topics:
# - {app.id}-{store.name}-changelog (state store backup)
# - {app.id}-{store.name}-repartition (repartitioning)
# - {app.id}-{store.name}-compact (compacted store)
âšī¸Changelog Purpose
Changelog topics serve as durable backups for Kafka Streams state stores. If a node crashes, the state is rebuilt from the changelog. This enables exactly-once semantics by ensuring state consistency.
Log Deduplication
Deduplication Strategies
Compaction is often proposed as a deduplication mechanism, and the interview answer needs nuance. Compaction collapses multiple values for the same key down to the latest, which looks like deduplication from the outside, but it does not stop a consumer from observing duplicates while cleaning lags behind the produce rate â every intermediate value is still readable until the cleaner runs. When strict duplicate suppression matters, the right tools are the idempotent producer, where a producer id plus per-partition sequence numbers let the broker discard replayed batches, or application-level deduplication keyed by a business event id. Bloom filters offer a memory-bounded probabilistic alternative: at one million expected ids and a one percent false positive rate, the filter needs roughly 1.2 MB and seven hash functions, and it will wrongly reject about one percent of genuinely new ids. Choose the filter when dropping a new message is acceptable; choose a compacted id-to-timestamp table when it is not.
# Strategy 1: Compacted topic with latest value
# Producer sends multiple values for same key
# Compaction keeps only the latest
# Strategy 2: Deduplication window
class DeduplicationWindow:
"""
Deduplicate messages within a time window.
"""
def __init__(self, window_size_ms=60000):
self.window_size = window_size_ms
self.seen = {} # key -> timestamp
def is_duplicate(self, key, message_id):
"""Check if message is duplicate"""
current_time = int(time.time() * 1000)
# Clean old entries
self.seen = {
k: v for k, v in self.seen.items()
if current_time - v < self.window_size
}
# Check if seen
if message_id in self.seen:
return True
# Mark as seen
self.seen[message_id] = current_time
return False
# Strategy 3: Bloom filter for probabilistic dedup
class BloomFilterDedup:
"""
Probabilistic deduplication using Bloom filter.
Lower memory, but false positives possible.
"""
def __init__(self, expected_items=1000000, false_positive_rate=0.01):
from pybloom_live import BloomFilter
self.bloom = BloomFilter(
capacity=expected_items,
error_rate=false_positive_rate
)
def is_duplicate(self, message_id):
"""Check if message might be duplicate"""
if message_id in self.bloom:
return True # Might be duplicate (false positive possible)
self.bloom.add(message_id)
return False
Deduplication Formula
Where:
- = filter size (bits)
- = number of elements
- = number of hash functions
def calculate_bloom_filter_size(
expected_items: int,
false_positive_rate: float
) -> dict:
"""
Calculate optimal Bloom filter parameters.
"""
import math
# Optimal filter size
m = - (expected_items * math.log(false_positive_rate)) / (math.log(2) ** 2)
# Optimal number of hash functions
k = (m / expected_items) * math.log(2)
# Memory in bytes
memory_bytes = m / 8
return {
'filter_size_bits': int(m),
'num_hash_functions': int(k),
'memory_bytes': int(memory_bytes),
'memory_mb': memory_bytes / (1024 * 1024)
}
# Example
bloom = calculate_bloom_filter_size(
expected_items=1000000,
false_positive_rate=0.01
)
print(f"Filter size: {bloom['memory_mb']:.1f} MB")
print(f"Hash functions: {bloom['num_hash_functions']}")
â ī¸Deduplication Limitation
Compacted topics only guarantee at-least-once delivery until compaction occurs. For strict exactly-once, you need idempotent producers or application-level deduplication.
Use Cases for Compacted Topics
The three patterns below share one shape: a compacted topic stands in for a mutable table, producers write the full current value for each key, and consumers treat the log as a source of current state rather than as an event history. The materialized view pattern suits configuration distribution and service discovery â a service publishes its endpoints under a stable key and every instance reads the compacted log to learn the current set. The event sourcing pattern keeps the immutable event log as truth and mirrors derived state into a compacted topic so projections rebuild cheaply. The configuration store pattern is the simplest: a read from the beginning of the compacted topic yields the full configuration map, and tombstones remove entries without a separate delete path.
Materialized View Pattern
# Materialized view using compacted topic
class MaterializedView:
"""
Maintain materialized view in compacted topic.
Each update writes the complete current state.
Compaction ensures only latest state per key.
"""
def __init__(self, topic, producer):
self.topic = topic
self.producer = producer
self.state = {}
def update(self, key, value):
"""
Update materialized view.
Writes complete state to compacted topic.
Old values are cleaned up by compaction.
"""
# Merge with existing state
if key in self.state:
self.state[key].update(value)
else:
self.state[key] = value
# Write to compacted topic
self.producer.send(
self.topic,
key=key.encode(),
value=json.dumps(self.state[key]).encode()
)
def delete(self, key):
"""Delete key via tombstone"""
if key in self.state:
del self.state[key]
# Write tombstone
self.producer.send(
self.topic,
key=key.encode(),
value=None
)
Event Sourcing Pattern
# Event sourcing with compacted topics
class EventSourcing:
"""
Event sourcing using compacted topics.
Events are the source of truth.
Compacted topic maintains current state.
"""
def __init__(self, events_topic, state_topic, producer):
self.events_topic = events_topic
self.state_topic = state_topic
self.producer = producer
def append_event(self, event):
"""
Append event to event log.
"""
self.producer.send(
self.events_topic,
key=event['entity_id'].encode(),
value=json.dumps(event).encode()
)
def update_state(self, entity_id, state):
"""
Update state in compacted topic.
State is derived from events.
Compaction keeps only latest state.
"""
self.producer.send(
self.state_topic,
key=entity_id.encode(),
value=json.dumps(state).encode()
)
Configuration Store Pattern
# Configuration store using compacted topics
class ConfigurationStore:
"""
Distributed configuration store using compacted topics.
Configuration updates written to compacted topic.
Consumers read latest configuration.
"""
def __init__(self, config_topic, producer, consumer):
self.config_topic = config_topic
self.producer = producer
self.consumer = consumer
self.config = {}
def update_config(self, key, value):
"""Update configuration"""
self.producer.send(
self.config_topic,
key=key.encode(),
value=json.dumps(value).encode()
)
def load_config(self):
"""
Load configuration from compacted topic.
Read all messages, keeping only latest per key.
"""
self.consumer.subscribe([self.config_topic])
for message in self.consumer:
key = message.key.decode()
value = json.loads(message.value.decode()) if message.value else None
if value is None:
# Tombstone - delete config
if key in self.config:
del self.config[key]
else:
self.config[key] = value
return self.config
âšī¸Key Insight
Compacted topics are the foundation for:
- Stream processing state: Changelog topics backup state stores
- Materialized views: Current state per key
- Configuration distribution: Latest config per component
- Event sourcing: Derived state from event logs
Compaction Performance
def estimate_compaction_performance(
topic_size_gb: int,
dirty_ratio: float,
compaction_throughput_mbps: float
) -> dict:
"""
Estimate compaction time and resource usage.
"""
# Data to compact
dirty_data_gb = topic_size_gb * dirty_ratio
# Compaction time
compaction_time_seconds = (dirty_data_gb * 1024) / compaction_throughput_mbps
return {
'topic_size_gb': topic_size_gb,
'dirty_data_gb': dirty_data_gb,
'compaction_time_seconds': compaction_time_seconds,
'compaction_time_minutes': compaction_time_seconds / 60,
'recommended_min_cleanable_dirty_ratio': 0.3
}
# Example
perf = estimate_compaction_performance(
topic_size_gb=100,
dirty_ratio=0.5,
compaction_throughput_mbps=100
)
print(f"Compaction time: {perf['compaction_time_minutes']:.1f} minutes")
â ī¸Compaction Cost
Compaction is CPU and I/O intensive. Monitor:
LogEndOffsetvsLogStartOffsetfor uncleaned dataCleanerRecleanPercentfor compaction efficiencyBytesInPerSecduring compaction
Operating Compacted Topics in Production
Compaction moves cost from storage to the cleaner, and production incidents usually come from underestimating that cost. The cleaner rewrites whole segments: a 1 GB segment with a high dirty ratio is read, filtered and written again, consuming the same disk bandwidth your producers need for appends. Keep segments small enough that cleaning granularity stays reasonable â six to twenty-four hours of data, meaning segment.ms between 21600000 and 86400000 for most workloads â and lower min.cleanable.dirty.ratio from the default 0.5 to around 0.2 or 0.3 when key cardinality is high and staleness matters. Watch three signals on the broker: cleaner threads busy, bytes in per second during cleaning passes, and the gap between log end offset and log start offset per partition, which shows how much dirty data is waiting. If cleaning cannot keep up, the topic grows without bound even though compaction is enabled, and the fix is more cleaner threads, smaller segments or fewer distinct keys â not a bigger disk.
Common Mistakes
Treating compaction as real-time deduplication and assuming duplicates never reach consumers
Fix: Compaction only trims history after the cleaner runs. Suppress duplicates at the source with an idempotent producer, or deduplicate in the consumer with a business event id.
Setting delete.retention.ms shorter than the worst-case consumer lag
Fix: Size it well above maximum lag, typically 24 hours, so lagging or restarted consumers still observe the tombstone before the broker erases the key.
Overriding the cleanup policy on a Kafka Streams changelog topic to save space
Fix: Leave changelogs compacted; restoration depends on the full key set surviving. If the write cost is the concern, disable logging for stores you can recompute from the input topic.
Key Takeaways
- Compaction retains the newest value for every key plus live tombstones, so a compacted log is bounded by key count rather than by time or write volume
- Tombstones delete keys only after delete.retention.ms elapses, and that window must exceed the worst consumer lag or slow readers resurrect deleted keys
- Kafka Streams changelogs are compacted topics that let a task restore its local RocksDB store without replaying the full input stream
- Idempotent producers suppress duplicates before they are written; compaction only collapses history after the fact, so the two mechanisms solve different problems