The interview problem
Design a compacted change log for a product catalog with ten million live keys. Search and cache services maintain local copies. Updates replace complete records, and deletions must remove local copies. A consumer returns after a long outage with old state and an apparently valid offset. Explain when it can resume, when it must rebuild, and how the rebuild avoids resurrecting deleted products.
Original system-design practice, not a reported company interview. All sizes and retention examples are hypothetical. Apache Kafka 4.1 documentation retrieved September 27, 2026; page publication date not stated; interview date not applicable.
1. Separate current state from historical events
This service distributes the latest catalog state. It does not promise to preserve every price transition or reconstruct the catalog at any arbitrary past instant. Keep a separate retained history if those are requirements. Compaction is unsuitable for independently meaningful events such as purchases when keying them only by customer would discard transactions.
Each update contains a stable product key and a complete replacement value. Keeping only the latest increment would not reconstruct a counter; deltas require a different representation or a valid base plus retained deltas. Define whether a deleted key may later be reused and how a new incarnation differs from a delayed old update.
Use stable key serialization and partition routing. A per-partition order is not a global order across products. Changing partition counts or key encoding requires a migration plan so the same logical key is not silently split into unrelated histories.
2. Define publication and materialization
catalog commit + durable change record
↓
keyed partitioned log
↙ ↘
background compaction state consumers
↓
state + applied checkpoint
↓
versioned snapshot publisher
↓
replacement bootstrapPublish committed replacements and deletions through a durable change-capture path. Order changes for each key according to the source's authority. Compaction follows log order, not whichever business timestamp is greatest. A delayed producer that appends an obsolete value after a delete can make that obsolete value the latest log entry. Prevent stale publication at the source or ordered publication boundary; consumer-side rejection alone cannot restore a newer value already removed by compaction.
Consumers process each partition in order and atomically store the resulting local mutation with its applied checkpoint, or use an equivalent recoverable protocol. An offset committed before the local deletion can skip the deletion after a crash. An offset committed afterward can cause replay, so applying replacements and deletions must be idempotent.
Store schema version, source epoch and log identity with checkpoints. Topic recreation, source restoration and partition migration can invalidate an old checkpoint even when its numeric offset looks plausible. Separate a checkpoint that exists from a checkpoint whose recovery contract is still valid.
3. Understand what compaction preserves
Kafka's documented compaction retains later keyed state while removing superseded records without renumbering remaining offsets. Null-valued keyed records represent deletion tombstones, which can themselves be removed. The documentation warns that slow consumers can miss deletes. Compaction runs asynchronously; eligibility is not an exact physical-removal deadline.
For this design, use a compaction-only state feed and treat tombstone retention as part of the consumer recovery contract. Additional time-based segment deletion changes what can be reconstructed and must be assessed separately. Do not promise complete state replay simply because a topic has compaction enabled.
An offset gap is normal after compaction. It does not tell a consumer which product was deleted, and a readable offset does not prove its old local state remains repairable. The broker cannot infer every external consumer's local contents from the offset alone.
4. Trace the missing-delete failure
At offset 100, product P has value V1. Consumer C applies it and stops with next offset 101. At offset 120, the producer writes a tombstone for P. Later, compaction removes V1 and eventually the tombstone under the configured policy. Other product records remain at higher offsets.
C returns holding P=V1 and resumes at 101. It reads the remaining later records, none of which mention P. Its offset reaches the head, yet P remains incorrectly present. Catching up numerically did not repair its state. Replaying the surviving feed on top of the same old map has the same problem: absence from the feed is not an instruction to delete an existing local row.
A truly empty replacement map avoids carrying V1 forward, but an arbitrarily slow full replay is not automatically safe either. It could read an old value before a concurrent cleaning pass and miss the later tombstone after that marker is removed. Recovery must complete under a verified replay-retention contract, or use a snapshot and protected suffix.
Do not interpret a configured retention duration as the exact moment of deletion. The example assumes cleaning actually removed both records. The correctness problem exists whenever a consumer has lost the opportunity to observe a required delete, whether or not an offset-out-of-range error occurs.
5. Rebuild into a new state generation
Maintain an explicit application recovery policy: consumers outside a validated replay window must bootstrap rather than resume old state. A conservative implementation rejects stale checkpoints based on the age of the unconsumed suffix, source epoch and an operationally verified retention margin. Persisting a new checkpoint timestamp while remaining far behind does not refresh the age of the missing changes. If that bound cannot be established, use a protected recovery feed or retain deletion state until acknowledged by all supported consumers. Indefinitely offline consumers cannot receive a finite-retention guarantee without another recovery mechanism.
Publish a snapshot from a consistent cut of a state materializer whose own recovery validity has been established. A consistent snapshot of an already stale map can preserve a missed deletion; consistency alone does not prove correctness. Record the exact next offset for each partition covered by that snapshot. Freeze state and offsets together with database snapshot/checkpoint semantics; reading offsets before an unrelated table scan does not establish a consistent cut. Cross-key transactional consistency, if required, needs an additional coordinated snapshot contract.
Load the snapshot into a new empty local generation, then replay the suffix from its recorded positions. Protect the necessary suffix, including deletion information, for the entire load and catch-up interval. This may use a separately retained uncompacted recovery stream or an enforced retention arrangement; it is not an automatic lease feature supplied by ordinary Kafka compaction.
Validate checksums, schema and source identity, catch up to an agreed barrier, then atomically switch the serving pointer to the new generation. Fence old workers so they cannot write into the new state. If recovery fails, discard the incomplete generation and retry with a still-valid snapshot. Never merge snapshot rows into the old generation and assume absent rows have been deleted.
6. Calculate storage and recovery headroom
At ten million live records averaging 500 bytes including key and value, final logical state occupies about 5 GB decimal. One hundred million updates/day at the same size append 50 GB/day before compression and framing. Three replicated copies represent 150 GB/day of raw appended bytes. Current-state size is not a hard log-size bound: uncleaned segments, retained tombstones, indexes and cleaner workspace consume additional space.
Suppose a snapshot scan of five GB takes 100 seconds at an effective 50 MB/s, followed by 200 seconds of loading and verification. At 20,000 new updates/s during these 300 seconds, six million updates accumulate. A replay worker handling 50,000 updates/s has net catch-up capacity of 30,000/s, so catch-up takes another 200 seconds. Total ideal recovery is 500 seconds, not 300 plus six million divided by 50,000 while ignoring new arrivals.
If replay capacity falls to 15,000/s while arrivals remain 20,000/s, this consumer cannot catch up. More retention postpones loss but does not fix insufficient throughput. Partition skew and sink write limits can dominate even when aggregate capacity appears adequate. Measure the slowest partition.
The required retention margin must cover snapshot age, transfer, loading, catch-up, retries and operational detection time under the actual policy. A nominal one-day setting does not justify a one-day outage promise plus an unbounded rebuild. Test restoration at the largest supported dataset and preserve room for failures.
7. Test the recovery contract
Test a consumer that stops before a tombstone and returns after its removal, a crash between deletion and checkpoint, snapshot creation during updates, a reset interrupted halfway and a stale worker writing after generation cutover. Verify actual key absence, not only offset lag. Include delete-then-recreate cases and source-epoch changes.
Monitor replay-window margin, progress age, restore duration, cleaner backlog, disk pressure and state divergence probes. A heartbeat from a stalled consumer is not progress. Count unresolved resets and deliberately unavailable replicas in the operational status instead of presenting them as caught up.
Protect compaction settings and source publication paths with change control. A retention reduction can invalidate existing recovery assumptions before clients notice. Update the supported checkpoint policy and provide a rebuild path before relying on the new limit. Recovery correctness should not depend on a cleaner happening to run slowly.
8. Trade-offs and follow-ups
Longer tombstone retention supports slower consumers at a storage cost. Permanent explicit deletion values preserve absence information but accumulate keys and require a separate deletion-state lifecycle. Tracking every consumer's acknowledgment allows targeted cleanup but couples retention to membership management. Snapshot resets decouple old consumers from indefinite history while adding consistent-cut and cutover complexity.
Follow-ups: What if keys move between partitions? Can compaction support a balance represented as increments? How do you rebuild a search index with its own asynchronous writes? What if a snapshot outlives its retained suffix? When is a persistent deleted flag preferable to a tombstone? What happens if an old producer appends after a key is recreated?
9. Self-review rubric
- Separate latest-state recovery from complete history.
- Specify replacement values, key identity and source ordering.
- Explain why tombstone removal can leave an old consumer incorrect.
- Bind local state to checkpoints and source identity.
- Rebuild from a consistent snapshot into an empty generation.
- Protect recovery deletes and fence stale workers.
- Calculate net catch-up capacity and validate retention headroom.
Sources and related practice
Apache Kafka 4.1 design: Log Compaction, page publication date not stated; retrieved September 27, 2026. Version-specific primary reference for compaction, offsets and delete-retention limitations. Snapshot generations, recovery policy and arithmetic here are original application design, not built-in broker guarantees.
Continue with change-data capture and database backup and restore.
Continue your preparation
Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.