Data Reliability and Fault Tolerance Questions
Designing pipelines that survive failures: retries, idempotency, checkpointing, exactly-once semantics, dead-letter handling, and recovery/replay. Covers reasoning about partial failures, poison messages, and consistency guarantees under faults. The resilience angle distinct from monitoring (detecting and alerting on a failure) and from Workflow Orchestration and Scheduling (the DAG/scheduler mechanics that decide whether and when a task runs again, including backfills and dependency management): this topic owns whether the data itself stays correct, not lost, not duplicated, not corrupted, when a process is retried or replayed.
Describe how a Change Data Capture pipeline (e.g., Debezium -> Kafka -> a warehouse or data lake) maintains ordering of operations and idempotent application on the target, including across connector restarts. Discuss the use of source LSN or transaction id, partitioning and keying, MERGE semantics in the sink, and approaches to handle out-of-order or missing transactional events.
Sample Answer
Direct answer
A change-data-capture (CDC) pipeline (Debezium reading a database's transaction log, publishing to Kafka, consumed into a warehouse or lake) maintains ordering by preserving the source database's own log sequence number (LSN) or transaction ID as an explicit field on every emitted event, and by keying Kafka partitions so all changes for the same row land on the same partition, guaranteeing Kafka's own per-partition ordering applies to that row's change history. Idempotent application on the target uses that same LSN/transaction ID as the version key in a MERGE, so a redelivered or replayed change (including across a connector restart) either applies cleanly in order or is recognized as already-applied and skipped.
Structured elaboration
Source LSN / transaction ID as the ordering authority. The database's own commit log already has a strict, monotonic ordering (Postgres's LSN, MySQL's binlog position); Debezium (or an equivalent CDC connector) reads that log in order and stamps every captured change event with this exact position. This position is the ground truth for "what order did these changes really happen in," independent of anything about the connector's own processing speed or Kafka's delivery timing.
Partitioning and keying. Kafka guarantees ordering only WITHIN a partition, not across partitions. A CDC pipeline must key each emitted event by the source row's primary key (or table+primary key), so every change to a given row is routed to the same partition and processed in the same relative order it was committed in the source, even though changes to DIFFERENT rows may be processed out of relative order across partitions (which is fine, since they do not depend on each other).
MERGE semantics in the sink. Applying a change is a conditional upsert: MERGE INTO target USING (source change) ON target.pk = change.pk WHEN MATCHED AND change.lsn > target.lsn THEN UPDATE ... WHEN NOT MATCHED THEN INSERT .... The change.lsn > target.lsn guard is what makes this idempotent AND order-safe simultaneously: applying the same change twice (lsn unchanged) is a no-op (the guard fails on the second application), and applying an out-of-order OLDER change after a newer one has already landed is also correctly rejected by the same guard, rather than silently regressing the target to stale data.
Connector restarts. A Debezium connector tracks its own committed offset into the source log (which LSN it has successfully published through). On restart after a crash, it resumes from its last committed offset, which, being at-least-once (not exactly-once) by construction, can redeliver a range of already-published events. This is precisely why the MERGE's LSN guard matters: redelivery after a restart is exactly the same problem as any other duplicate delivery, and the same idempotent-apply logic handles both uniformly, "must not apply the same DB change twice" is not a special restart-only case, it is the general case that restarts happen to trigger reliably.
Out-of-order or missing transactional events. Two distinct failure shapes: (1) events legitimately arrive out of LSN order at the SINK (different partitions processed at different speeds, or a retry reorders delivery within normal Kafka semantics), handled by the MERGE guard as described. (2) A gap in the LSN sequence itself, some transactional event is genuinely missing (a connector bug, a source-side log rotation before the connector caught up), which the MERGE guard CANNOT detect or fix, since a missing event just means the target never receives an update it should have. Detecting this requires separate monitoring: tracking the connector's own lag and continuity against the source's current LSN, and alerting on a detected gap rather than relying on the apply logic to somehow notice data that never arrived.
Worked example
A customers table row with primary key cust-77 receives three updates in the source, committed at LSN 1001, 1002, 1003 respectively. Due to a connector restart between publishing LSN 1002 and confirming its offset commit, the connector redelivers LSN 1002 and 1003 on restart (an honest at-least-once redelivery). The sink receives, in this exact arrival order: LSN 1001, LSN 1003, LSN 1002 (redelivered), LSN 1003 (redelivered again).
- Apply LSN 1001: target has no row for
cust-77yet (or an older LSN);WHEN NOT MATCHEDinserts it, target now showslsn=1001. - Apply LSN 1003:
1003 > 1001, guard passes, updates; target now showslsn=1003. - Apply LSN 1002 (redelivered, arrives AFTER 1003 due to the restart):
1002 > 1003is FALSE, guard rejects the update; target correctly STAYS atlsn=1003, the actually-latest state, rather than regressing to the stale 1002 value. - Apply LSN 1003 (redelivered again):
1003 > 1003is FALSE (not strictly greater), guard rejects as a duplicate no-op; target stays atlsn=1003.
Final target state: lsn=1003, byte-identical to what a strictly-in-order, no-duplicates application would have produced. The MERGE guard's > (strictly greater, not >=) is what makes both the out-of-order and the exact-duplicate cases resolve correctly with the SAME single rule.
Trade-offs and pitfalls
- Common mistake: keying Kafka partitions by something other than the row's primary key (e.g., by source table name only, for load-balancing convenience). This destroys the per-row ordering guarantee entirely, since two updates to the same row can land on different partitions and be consumed out of order with no guaranteed relative sequencing at all, not even the "eventually correct via the LSN guard" story above, because the guard only works if events for the same row are at least eventually all seen; if a partition consumer falls permanently behind, the target can be permanently stale for rows on that partition.
- Common mistake: using wall-clock arrival time instead of source LSN as the ordering/version key. Clock skew, network jitter, and reprocessing can all make arrival order diverge from true commit order; only the source's own log position is a reliable ordering authority.
- The MERGE guard handles duplicates and reordering, but not gaps. As shown above, a genuinely missing event is invisible to this mechanism; a healthy pipeline needs separate lag/continuity monitoring on the CDC connector itself, watching for the connector's confirmed LSN falling behind the source's current LSN by more than an alerting threshold.
- DELETE events need the same discipline, and are easy to get wrong. A CDC delete event should also carry an LSN and be subject to the same ordering guard (a delete arriving out of order after a later re-insert of the same key must not delete the newer row); teams that handle inserts/updates correctly sometimes special-case deletes as an unconditional
DELETE WHERE pk = ..., which reopens the exact same ordering hazard the MERGE guard was built to close for everything else.
Provide pseudocode for the Chandy-Lamport distributed snapshot algorithm adapted to capture consistent operator state and in-flight messages in a streaming dataflow. Include handling for a snapshot attempt that partially fails and how to resume or abort safely. Then explain how you would adapt the same algorithm to implement consistent checkpoints across cooperating microservices that exchange events over Kafka or message queues, and discuss the practical challenges of capturing in-flight messages and integrating with persisted broker logs.
Sample Answer
Direct answer
The Chandy-Lamport algorithm captures a globally consistent snapshot (every operator's local state, plus every in-flight message on every channel) without stopping the dataflow, using one rule: when an operator sees the FIRST marker on any incoming channel, it immediately records its own local state and forwards a marker on every outgoing channel; any data that arrives on a channel AFTER recording starts but BEFORE that specific channel's own marker is genuinely in-flight and must be recorded as part of that channel's snapshot. A snapshot attempt that never completes (a marker lost or indefinitely delayed) is handled with a bounded wait followed by an explicit abort that discards the partial recording and resets the operator to a clean state, so a fresh attempt can safely retry. The same core rule extends to cooperating microservices over Kafka or a message queue, but the practical challenges shift: a durable broker already persists the channel's history, so "in-flight capture" becomes an offset-range bookkeeping problem rather than a memory-buffering one, at the cost of needing per-partition markers (a Kafka topic is not a single FIFO channel) and needing every participating service to actually understand and propagate markers.
Structured elaboration
The core marker-propagation rule. An operator that is the SNAPSHOT INITIATOR records its own state immediately, then sends a marker on every outgoing channel. Any OTHER operator, on receiving its first marker (on any one incoming channel), does the same: record local state now, propagate markers on all outgoing channels immediately, and begin recording every OTHER incoming channel until that channel's own marker arrives. The snapshot is complete for an operator once a marker has been seen on EVERY incoming channel, since only then is it guaranteed nothing pre-snapshot is still unaccounted for on that channel.
Why FIFO, loss-free channels are the algorithm's core assumption. The whole scheme depends on a marker on a given channel being a reliable boundary: everything the operator receives on that channel BEFORE the marker is "before the cut," everything after is "after the cut." This only works if messages on a channel are delivered in the order sent (FIFO) and none are silently dropped; a channel that can reorder or lose messages can let a genuinely pre-snapshot message arrive AFTER its own marker, silently excluding it from the snapshot with no way to detect the gap.
Handling a snapshot attempt that partially fails: resume versus abort. These are two genuinely different responses, and which one is safe depends on WHY the marker is late. If the delay is merely a slow producer or a backlog the missing channel is still working through (the channel partner is alive, just behind), RESUMING is possible and often preferable: keep waiting, since the channel's own FIFO ordering guarantee still holds and the marker will eventually arrive with the cut still correctly defined, just later than hoped. If the delay reflects a genuine failure (the channel partner crashed, or a marker was lost on an unreliable transport and will never arrive), waiting is pointless and RESUME is not an option at all, no amount of extra time produces a marker that was never sent or was silently dropped. Bounding the wait with a timeout is what turns "which case is this?" from a judgment call made too late into an explicit, enforced decision: below the bound, resume (keep waiting); at the bound, assume the worse case and ABORT, discarding the recorded state and every channel's partial recording buffer, and returning to a not-in-progress state. This is not just bookkeeping hygiene, it is what makes a subsequent RETRY (a fresh snapshot attempt, distinct from resuming the SAME attempt) safe: an operator that aborted cleanly can treat the next marker it sees as a genuinely fresh first marker and begin a new, independent attempt, rather than mixing stale partial state from the failed attempt into a new one.
Adapting to cooperating microservices over Kafka/message queues. The same three-part rule (record on first marker, propagate markers immediately, record data until each channel's own marker) still applies, but three things change in practice:
- The broker is the channel's own persisted history. Unlike the in-memory channel in the reference implementation below, a Kafka topic-partition already durably retains every message. "In-flight capture" becomes: record the OFFSET at which this consumer's snapshot recording started per partition, and the offset at which the marker for that partition was seen; everything between those two offsets IS the channel's snapshot state, retrievable from the broker's own log rather than a buffer the operator must maintain itself.
- A Kafka topic is not one FIFO channel, it is N independent FIFO partitions. Ordering is only guaranteed WITHIN a partition, so a marker must be sent (and waited for) on EVERY partition of every relevant topic a service consumes from, not once per topic; treating a multi-partition topic as a single channel silently reintroduces the reordering risk the algorithm's FIFO assumption is meant to rule out.
- Every participating service must understand markers. The algorithm assumes every node in the graph propagates markers correctly; a service that is unaware of the protocol (a legacy consumer, or a service owned by a different team not opted into the snapshot mechanism) simply will not forward one, which either stalls the snapshot at that service (if it is expected to) or silently produces an incomplete cut if the coordinator does not realize that service was supposed to participate. In practice this argues for either a dedicated coordination topic carrying markers as control messages (out-of-band from the data topics, so unmodified consumers of the data topics are unaffected) or an explicit registry of exactly which services participate in a given consistent-checkpoint boundary.
Worked example
Reference implementation below (a graph with fan-in: A feeds both B and C, and B also feeds C, so C must wait for markers on BOTH its incoming channels, exercising the rule beyond a trivial linear chain). Scenario 1 proves successful capture of a genuinely in-flight message; scenario 2 proves the partial-failure timeout, abort, and clean retry.
"""
Chandy-Lamport distributed snapshot: capture consistent operator state AND
in-flight channel messages in a streaming dataflow with fan-in (a cycle-free
but non-trivial graph, not just a linear pipeline).
Topology: A -> B, A -> C, B -> C (C has two incoming channels, exercising
the "wait for a marker on EVERY incoming channel before declaring complete"
rule that makes Chandy-Lamport work correctly on fan-in, not just a chain).
Scenario 1: successful snapshot with a genuine in-flight message captured.
Scenario 2: a snapshot attempt where one marker never arrives within a
bounded wait -> abort() discards the partial recording and resets the
operator to a clean, resumable state -> a FRESH snapshot attempt afterward
succeeds normally, proving abort did not leave the operator corrupted.
"""
from collections import deque
class Channel:
def __init__(self, src, dst):
self.src, self.dst = src, dst
self.queue = deque()
def send(self, msg):
self.queue.append(msg)
def receive(self):
return self.queue.popleft() if self.queue else None
def __repr__(self):
return f"{self.src}->{self.dst}"
class Operator:
def __init__(self, name):
self.name = name
self.state = 0
self.incoming = []
self.outgoing = []
self.snapshot_in_progress = False
self.recorded_state = None
self.recording_channels = {} # channel -> list of messages recorded before ITS marker
self._markers_by_channel = set()
self.snapshot_complete = False
self.ticks_since_snapshot_started = 0
self.aborted_count = 0
def _begin_snapshot(self):
self.recorded_state = self.state
self.snapshot_in_progress = True
self.snapshot_complete = False
self._markers_by_channel = set()
self.recording_channels = {c: [] for c in self.incoming}
self.ticks_since_snapshot_started = 0
for c in self.outgoing:
c.send(("MARKER", None))
def initiate_snapshot(self):
"""This operator is the INITIATOR: records its own state, then
immediately sends a marker on every outgoing channel."""
self._begin_snapshot()
def receive_marker(self, channel):
if not self.snapshot_in_progress:
# First marker seen anywhere: record state now, propagate
# markers on all outgoing channels immediately (Chandy-Lamport's
# core rule), and start recording every OTHER incoming channel.
self._begin_snapshot()
self._markers_by_channel.add(channel)
if self.snapshot_in_progress and set(self.incoming) <= self._markers_by_channel:
self.snapshot_complete = True
def process_data(self, channel, value):
self.state += value
if self.snapshot_in_progress and channel not in self._markers_by_channel:
# Genuinely in-flight: arrived on this channel AFTER recording
# started but BEFORE that channel's own marker -- must be
# captured as part of the channel's snapshot state.
self.recording_channels.setdefault(channel, []).append(value)
def tick(self):
if self.snapshot_in_progress and not self.snapshot_complete:
self.ticks_since_snapshot_started += 1
def abort_if_timed_out(self, timeout_ticks):
"""Bounded wait -> abort: discard the partial recording and return
the operator to a clean, pre-snapshot state so it can safely
participate in a FRESH snapshot attempt afterward. This is the
actual mechanism, not just a description of one."""
if (self.snapshot_in_progress and not self.snapshot_complete
and self.ticks_since_snapshot_started >= timeout_ticks):
self.snapshot_in_progress = False
self.snapshot_complete = False
self.recorded_state = None
self.recording_channels = {}
self._markers_by_channel = set()
self.ticks_since_snapshot_started = 0
self.aborted_count += 1
return True
return False
def snapshot_result(self):
return {
"operator_state": self.recorded_state,
"channel_states": {str(c): list(v) for c, v in self.recording_channels.items()},
"complete": self.snapshot_complete,
}
def main():
ops = {n: Operator(n) for n in ["A", "B", "C"]}
ch_ab, ch_ac, ch_bc = Channel("A", "B"), Channel("A", "C"), Channel("B", "C")
ops["A"].outgoing = [ch_ab, ch_ac]
ops["B"].incoming, ops["B"].outgoing = [ch_ab], [ch_bc]
ops["C"].incoming = [ch_ac, ch_bc] # fan-in: must wait for BOTH markers
ops["A"].state, ops["B"].state, ops["C"].state = 10, 5, 2
# --- Scenario 1: successful snapshot, with a GENUINE in-flight message ---
# B->C already has one pending DATA message queued BEFORE any marker
# exists anywhere in the system (a normal, pre-snapshot in-flight message).
ch_bc.send(("DATA", 7))
ops["A"].initiate_snapshot()
print(f"A initiates: recorded_state={ops['A'].recorded_state}, markers queued on {[str(c) for c in ops['A'].outgoing]}")
msg = ch_ab.receive()
assert msg == ("MARKER", None)
ops["B"].receive_marker(ch_ab) # B's first marker: records state=5, propagates its own marker to C
print(f"B receives marker from A: recorded_state={ops['B'].recorded_state}, propagates marker to C "
f"(queued BEHIND the pre-existing DATA(7) already on {ch_bc})")
msg2 = ch_ac.receive()
assert msg2 == ("MARKER", None)
ops["C"].receive_marker(ch_ac)
print(f"C receives marker from A (first marker C has seen): recorded_state={ops['C'].recorded_state}, "
f"now recording {ch_bc}, still waiting for its marker")
msg3 = ch_bc.receive()
assert msg3 == ("DATA", 7)
ops["C"].process_data(ch_bc, 7)
print(f"C receives DATA(7) on {ch_bc} BEFORE that channel's marker: recorded into channel snapshot")
msg4 = ch_bc.receive()
assert msg4 == ("MARKER", None)
ops["C"].receive_marker(ch_bc)
print(f"C receives marker from B (second and final marker): snapshot_complete={ops['C'].snapshot_complete}")
result_C = ops["C"].snapshot_result()
print(f"\nC's final snapshot: {result_C}")
assert result_C["complete"] is True
assert result_C["operator_state"] == 2, "C's recorded state should be its state AT the moment of its first marker"
assert result_C["channel_states"][str(ch_bc)] == [7], \
"the in-flight B->C message (arrived before that channel's marker) must be captured"
assert result_C["channel_states"][str(ch_ac)] == [], "no in-flight data arrived on A->C before its marker"
print("Assertions passed: C's snapshot captures its own operator state (2) at the moment")
print("of its FIRST marker, PLUS the genuinely in-flight B->C message (7), proving")
print("in-flight message capture actually works, not just operator-state capture.")
# --- Scenario 2: partial snapshot failure -> bounded timeout -> ABORT ---
# (actually executed: a real tick-based timeout, a real state reset, and
# a real follow-up snapshot proving the reset left C usable again.)
ops2 = {n: Operator(n) for n in ["A", "B", "C"]}
ch_ac2, ch_bc2 = Channel("A", "C"), Channel("B", "C")
ops2["C"].incoming = [ch_ac2, ch_bc2]
ops2["A"].outgoing = [ch_ac2]
ops2["B"].outgoing = [ch_bc2]
ops2["C"].state = 1
ops2["A"].initiate_snapshot()
ch_ac2.receive() # pop A's marker
ops2["C"].receive_marker(ch_ac2)
print(f"\nScenario 2: C receives marker from A only (B's marker never sent/arrives). "
f"snapshot_complete={ops2['C'].snapshot_complete}")
assert ops2["C"].snapshot_complete is False, \
"snapshot must NOT be complete while a marker from another incoming channel is still outstanding"
TIMEOUT_TICKS = 5
aborted_before_deadline = ops2["C"].abort_if_timed_out(TIMEOUT_TICKS)
assert aborted_before_deadline is False, "must not abort before the bound is reached"
for _ in range(TIMEOUT_TICKS):
ops2["C"].tick()
print(f"Ticked {TIMEOUT_TICKS} times with B's marker still outstanding "
f"(ticks_since_snapshot_started={ops2['C'].ticks_since_snapshot_started})")
aborted = ops2["C"].abort_if_timed_out(TIMEOUT_TICKS)
print(f"abort_if_timed_out({TIMEOUT_TICKS}) returned {aborted}; "
f"snapshot_in_progress={ops2['C'].snapshot_in_progress}, "
f"recording_channels={ops2['C'].recording_channels}, "
f"aborted_count={ops2['C'].aborted_count}")
assert aborted is True
assert ops2["C"].snapshot_in_progress is False
assert ops2["C"].recorded_state is None
assert ops2["C"].recording_channels == {}
assert ops2["C"].aborted_count == 1
print("Assertions passed: the timed-out attempt was discarded, not left half-recorded --")
print("C is back to a clean, pre-snapshot state with zero residual recording buffers.")
# Prove the reset is genuinely clean, not just superficially: retry with a
# FRESH snapshot (both markers now actually arrive) and confirm it
# completes correctly, with no leftover state from the aborted attempt.
ops2["A"].initiate_snapshot()
ch_ac2.receive()
ops2["C"].receive_marker(ch_ac2)
ops2["B"].initiate_snapshot() # B independently sends its own marker this time
ch_bc2.receive()
ops2["C"].receive_marker(ch_bc2)
retry_result = ops2["C"].snapshot_result()
print(f"\nRetry after abort: {retry_result}")
assert retry_result["complete"] is True
assert retry_result["operator_state"] == 1, "retried snapshot's recorded state must be C's CURRENT state, not stale data from the aborted attempt"
assert retry_result["channel_states"][str(ch_ac2)] == []
assert retry_result["channel_states"][str(ch_bc2)] == []
print("Assertions passed: the retried snapshot completes cleanly and independently --")
print("the abort left no residue that could corrupt or interfere with the next attempt.")
if __name__ == "__main__":
main()
Output (actually executed with python3):
A initiates: recorded_state=10, markers queued on ['A->B', 'A->C']
B receives marker from A: recorded_state=5, propagates marker to C (queued BEHIND the pre-existing DATA(7) already on B->C)
C receives marker from A (first marker C has seen): recorded_state=2, now recording B->C, still waiting for its marker
C receives DATA(7) on B->C BEFORE that channel's marker: recorded into channel snapshot
C receives marker from B (second and final marker): snapshot_complete=True
C's final snapshot: {'operator_state': 2, 'channel_states': {'A->C': [], 'B->C': [7]}, 'complete': True}
Assertions passed: C's snapshot captures its own operator state (2) at the moment
of its FIRST marker, PLUS the genuinely in-flight B->C message (7), proving
in-flight message capture actually works, not just operator-state capture.
Scenario 2: C receives marker from A only (B's marker never sent/arrives). snapshot_complete=False
Ticked 5 times with B's marker still outstanding (ticks_since_snapshot_started=5)
abort_if_timed_out(5) returned True; snapshot_in_progress=False, recording_channels={}, aborted_count=1
Assertions passed: the timed-out attempt was discarded, not left half-recorded --
C is back to a clean, pre-snapshot state with zero residual recording buffers.
Retry after abort: {'operator_state': 1, 'channel_states': {'A->C': [], 'B->C': []}, 'complete': True}
Assertions passed: the retried snapshot completes cleanly and independently --
the abort left no residue that could corrupt or interfere with the next attempt.
Scenario 1 proves the mechanism end to end, not just the happy path's surface: C's snapshot correctly records its OWN state (2) at the moment of its first marker, and separately captures the B->C message (7) that genuinely arrived after C started recording that channel but before that channel's marker, while the A->C channel (which had no in-flight data) correctly records nothing. Scenario 2 proves the failure path is not just described but actually exercised: C is left waiting on B's marker, five simulated ticks pass with no marker arriving, the timeout fires, and the assertions confirm every piece of partial state (recorded state, recording buffers, seen-markers set) is genuinely cleared, not merely marked complete. The retried snapshot immediately afterward succeeds and reflects C's CURRENT state (1, correctly different from the first attempt's 2), proving the abort left no residue from the failed attempt to contaminate the next one.
Trade-offs and pitfalls
- Common mistake: treating "wait forever for a marker" as acceptable. Without a bounded timeout and explicit abort, a single crashed or slow participant blocks the snapshot indefinitely and leaves the operator's recording buffers growing without bound in the meantime; the abort mechanism demonstrated above is what keeps a partial failure from becoming an unbounded resource leak.
- Common mistake: one marker per multi-partition Kafka topic instead of one per partition. Since ordering is only guaranteed within a partition, sending a single marker to just one partition and treating the whole topic as "covered" reintroduces exactly the reordering risk FIFO channels are meant to eliminate, silently corrupting the cut.
- The algorithm assumes reliable, lossless delivery, which a real message queue does not always guarantee end to end (a broker outage, a consumer-group rebalance dropping in-flight state); production adoptions typically pair this with the broker's own durability guarantees and an explicit marker-acknowledgment protocol rather than assuming the abstract channel model holds perfectly.
- Recording buffers are only bounded if the wait is bounded. A snapshot attempt with no timeout at all defeats the purpose of the abort mechanism entirely; the timeout value itself is a real trade-off (too short aborts attempts that would have completed given slightly more time under normal load; too long lets a stuck attempt hold recording buffers open unnecessarily long).
Write pseudocode for a checkpoint recovery algorithm that replays a write-ahead log (WAL) to restore operator state and reconciles external sinks with idempotency keys to ensure consistency after a crash. Address ordering guarantees, deduplication, and complexity analysis.
Sample Answer
Direct answer
Recovery has two distinct phases that must not be conflated: first, replay the WAL sequentially to rebuild the operator's in-memory state exactly as it stood right before the crash; second, reconcile with every external sink using each WAL record's own sequence number as an idempotency key, so a sink that ALREADY received some of those writes before the crash (a real case: the write succeeded, but the operator crashed before it could note that fact) treats a replayed write as a safe no-op instead of double-applying it. Below is executable pseudocode-as-real-Python implementing both phases, including a negative control proving what happens without the idempotency-key guard.
Structured elaboration
Phase 1: WAL replay to rebuild operator state. Read WAL records strictly in append order (their sequence number), applying each record's delta to an in-memory state dict. Reading in order is what preserves ordering guarantees: if state updates were non-commutative (a "last write wins" field instead of a running sum), applying them out of order would silently produce the wrong final state even though every record was individually applied correctly.
Corruption handling during replay. Each record carries a checksum. On the first corrupt or truncated record (a torn write from a crash mid-append, the exact scenario a WAL exists to survive), replay stops there rather than guessing at the record's content; anything after that point is treated as never durably written, which is the conservative, correct choice, since a torn write's own outcome is genuinely unknown.
Phase 2: idempotent reconciliation with external sinks. The WAL's own monotonic sequence number IS a natural idempotency key: it uniquely identifies one logical write. The sink's apply(seq, key, delta) checks whether that seq has already been applied; if so, no-op (deduplication); if not, apply and remember the seq. This is necessary because the crash could have happened AFTER a sink write succeeded but BEFORE the operator's own bookkeeping (a checkpoint, or an internal "last-reconciled-seq" watermark) recorded that fact, exactly the general crash-after-write-before-confirm gap any idempotency-store design has to close, here solved at the sink itself via a persistent per-seq applied-set rather than a separate claim-then-confirm protocol.
Ordering guarantee, stated precisely. WAL replay yields records in seq order; the reconciliation step processes them in that same order, so if two records touch the SAME key, the sink observes them in the correct original order even during recovery, not merely eventually-consistent-in-some-order.
Complexity. Replay is O(n) in the number of WAL records since the last durable checkpoint (each record is read and its checksum verified exactly once). State reconstruction is O(1) per record (a dict update). Sink reconciliation is O(1) amortized per record (a set membership check plus insert). Total recovery time is O(n), linear in WAL size since the last checkpoint, which is exactly why checkpoint frequency directly bounds worst-case recovery time.
Worked example
"""
Checkpoint recovery: replay a WAL to restore operator state, then reconcile
external sinks using idempotency keys (the WAL's own seq number) so replay
is safe even if the sink already received some writes before the crash.
"""
import os, struct, zlib
class WAL:
HEADER_FMT = "!IQ"
HEADER_SIZE = struct.calcsize(HEADER_FMT)
def __init__(self, path):
self.path = path
self._next_seq = 0
def append(self, key, delta):
payload = f"{key}|{delta}".encode()
seq = self._next_seq
self._next_seq += 1
crc = zlib.crc32(payload)
with open(self.path, "ab") as f:
f.write(struct.pack(self.HEADER_FMT, len(payload), seq))
f.write(payload)
f.write(struct.pack("!I", crc))
f.flush()
os.fsync(f.fileno())
return seq
def replay(self):
if not os.path.exists(self.path):
return
with open(self.path, "rb") as f:
while True:
header = f.read(self.HEADER_SIZE)
if len(header) < self.HEADER_SIZE:
break
length, seq = struct.unpack(self.HEADER_FMT, header)
payload = f.read(length)
crc_bytes = f.read(4)
if len(payload) < length or len(crc_bytes) < 4:
break
if zlib.crc32(payload) != struct.unpack("!I", crc_bytes)[0]:
break
key, delta = payload.decode().split("|")
yield seq, key, int(delta)
class ExternalSink:
def __init__(self):
self.applied_seqs = set()
self.totals = {}
def apply(self, seq, key, delta):
if seq in self.applied_seqs:
return "duplicate_noop"
self.applied_seqs.add(seq)
self.totals[key] = self.totals.get(key, 0) + delta
return "applied"
def recover(wal, sink):
state = {}
applied = duplicates = 0
for seq, key, delta in wal.replay():
state[key] = state.get(key, 0) + delta
if sink.apply(seq, key, delta) == "applied":
applied += 1
else:
duplicates += 1
return state, applied, duplicates
def main():
wal_path = os.path.join(os.path.dirname(__file__), "s24_test.wal")
if os.path.exists(wal_path):
os.remove(wal_path)
wal = WAL(wal_path)
for key, delta in [("a", 5), ("b", 3), ("a", 2), ("c", 10), ("a", -1), ("b", 7)]:
wal.append(key, delta)
sink = ExternalSink()
# Simulate: sink ALREADY applied seq 0,1,2 before the crash.
sink.apply(0, "a", 5); sink.apply(1, "b", 3); sink.apply(2, "a", 2)
pre_crash_totals = dict(sink.totals)
print("Sink totals BEFORE recovery (pre-applied seq 0,1,2):", pre_crash_totals)
state, applied, duplicates = recover(wal, sink)
print("Recovered operator state (from full WAL replay):", state)
print("Sink totals AFTER recovery:", sink.totals)
print(f"Reconciliation: {applied} newly applied, {duplicates} correctly recognized as duplicates")
expected_state = {"a": 5 + 2 - 1, "b": 3 + 7, "c": 10}
assert state == expected_state
assert sink.totals == expected_state
assert duplicates == 3 and applied == 3
# Negative control: WITHOUT the idempotency-key check, naive replay
# double-counts seq 0,1,2.
naive_totals = dict(pre_crash_totals)
for seq, key, delta in wal.replay():
naive_totals[key] = naive_totals.get(key, 0) + delta
print("\nWITHOUT idempotency-key reconciliation, naive replay gives:",
naive_totals, "(WRONG: double-counts seq 0,1,2)")
assert naive_totals != expected_state
os.remove(wal_path)
if __name__ == "__main__":
main()
Output (actually executed with python3):
Sink totals BEFORE recovery (pre-applied seq 0,1,2): {'a': 7, 'b': 3}
Recovered operator state (from full WAL replay): {'a': 6, 'b': 10, 'c': 10}
Sink totals AFTER recovery: {'a': 6, 'b': 10, 'c': 10}
Reconciliation: 3 newly applied, 3 correctly recognized as duplicates
WITHOUT idempotency-key reconciliation, naive replay gives: {'a': 13, 'b': 13, 'c': 10} (WRONG: double-counts seq 0,1,2)
The correct run shows operator state and sink totals converging to the identical {'a': 6, 'b': 10, 'c': 10}, and the reconciliation counters (3 applied, 3 duplicates) confirm the guard actually distinguished the pre-crash-applied records from the genuinely new ones. The negative control is the deliberately non-vacuous proof: replaying the full WAL against the SAME pre-crash sink state WITHOUT the seq-based guard produces 'a': 13 instead of the correct 6 (double-counting the +5 and +2 deltas at seq 0 and seq 2), concretely demonstrating why the idempotency check is load-bearing, not defensive boilerplate.
Trade-offs and pitfalls
- Common mistake: reconstructing operator state from the WAL but skipping sink reconciliation entirely, assuming "the sink will just get whatever we send it now." As the negative control shows, this silently double-applies any write that succeeded before the crash but was not yet acknowledged back to the operator.
- Common mistake: treating the sink's own idempotency as automatic. The
applied_seqsset itself must be durable (backed by the sink's own storage, not the crashed operator's now-lost memory), or the sink has no way to know it already saw seq 0 through 2 after ITS OWN restart; this is the same durability requirement any idempotency-key store has. - Stopping replay at the first corrupted record is a real, deliberate data-loss trade-off, not a bug: it guarantees recovery only ever trusts CONFIRMED-INTACT records, at the cost of potentially losing a record that was actually fine but happened to be written just before an unrelated corruption; the alternative (skip and continue past a bad record) risks silently applying a record whose content cannot be trusted.
- Recovery cost scales with WAL length since the last checkpoint, not total historical WAL size, which is why in production this algorithm always runs against the WAL segment(s) since the last completed checkpoint, never the entire WAL history, tying recovery time directly to the checkpoint-interval trade-off.
Implement a Java method deduplicate(List<Event> events, int capacity) that returns the input events in original order but removes duplicates by event.id. Use an LRU strategy of given capacity to track seen IDs and bound memory. Assume class Event { String id; long ts; String payload; }. Provide the method and explain time and space complexity.
Sample Answer
Direct answer
LinkedHashMap in ACCESS-ORDER mode is the direct Java tool for this: overriding removeEldestEntry to return true once size exceeds capacity turns it into a bounded LRU cache with O(1) get/put, and using it purely as a "seen set" (values unused, just presence) tracks the most-recently-seen capacity event IDs. Iterate the input once in order, skip any event whose ID is already in the LRU set, otherwise keep it and add its ID; this preserves original order and bounds memory to capacity entries regardless of total input size.
Structured elaboration
Why LinkedHashMap, not a plain HashMap plus a separate queue. LinkedHashMap constructed with accessOrder=true maintains its own internal doubly-linked list of entries in access order, and both get() and put() automatically move the touched entry to the "most recently used" end, giving true LRU semantics (not FIFO) with no extra bookkeeping in the calling code. Overriding removeEldestEntry(eldest) to return size() > capacity after every put lets the map evict its own least-recently-used entry automatically, again O(1), no manual linked-list management needed.
Why order-preserving iteration, not a Set-based filter. The method must return events in ORIGINAL order (a Set alone would lose this), so the implementation iterates the input list once, appending each non-duplicate event to a separate output ArrayList in the order encountered, while the LRU map only tracks WHICH ids have been seen recently, not the output ordering itself.
LRU eviction changing behavior, not just bounding memory. Because eviction is real, a previously-seen ID that ages out of the capacity-sized window is correctly treated as NEW again on a later occurrence, this is not a bug, it is the deliberate, stated trade-off of using a BOUNDED memory structure: perfect, unbounded deduplication is not possible within fixed memory, so old entries must eventually be forgotten, and LRU forgets the LEAST RECENTLY relevant ones first, a reasonable policy for a stream where recent activity is more likely to matter.
Worked example
import java.util.*;
class Event {
String id; long ts; String payload;
Event(String id, long ts, String payload) { this.id = id; this.ts = ts; this.payload = payload; }
public String toString() { return id; }
}
public class Dedup {
public static List<Event> deduplicate(List<Event> events, int capacity) {
LinkedHashMap<String, Boolean> seen = new LinkedHashMap<String, Boolean>(capacity, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
return size() > capacity;
}
};
List<Event> result = new ArrayList<>();
for (Event e : events) {
if (seen.containsKey(e.id)) {
seen.get(e.id); // touch: moves to MRU position, but do NOT add to result
continue;
}
seen.put(e.id, Boolean.TRUE);
result.add(e);
}
return result;
}
static void assertEquals(Object expected, Object actual, String msg) {
if (!Objects.equals(expected, actual))
throw new AssertionError(msg + " -- expected=" + expected + " actual=" + actual);
}
static List<String> idsOf(List<Event> events) {
List<String> ids = new ArrayList<>();
for (Event e : events) ids.add(e.id);
return ids;
}
public static void main(String[] args) {
// Test 1: basic dedup, order preserved, first occurrence kept.
List<Event> input1 = Arrays.asList(
new Event("a", 1, "p1"), new Event("b", 2, "p2"),
new Event("a", 3, "p1-dup"), new Event("c", 4, "p3"), new Event("b", 5, "p2-dup"));
List<Event> out1 = deduplicate(input1, 10);
System.out.println("Test 1 (basic dedup, capacity=10): " + idsOf(out1));
assertEquals(Arrays.asList("a", "b", "c"), idsOf(out1), "Test 1 failed");
// Test 2: capacity SMALLER than distinct IDs, forcing LRU eviction --
// proves eviction actually changes behavior (evicted ID treated as new).
List<Event> input2 = Arrays.asList(
new Event("x1", 1, "p"), new Event("x2", 2, "p"),
new Event("x3", 3, "p"), new Event("x1", 4, "p-again"));
List<Event> out2 = deduplicate(input2, 2);
System.out.println("Test 2 (capacity=2, forces eviction): " + idsOf(out2));
assertEquals(Arrays.asList("x1", "x2", "x3", "x1"), idsOf(out2), "Test 2 failed");
// Test 3: negative control -- SAME input, capacity=10 (no eviction),
// proving x1 IS correctly deduped when capacity is not exceeded.
List<Event> out3 = deduplicate(input2, 10);
System.out.println("Test 3 (same input, capacity=10, no eviction): " + idsOf(out3));
assertEquals(Arrays.asList("x1", "x2", "x3"), idsOf(out3), "Test 3 failed");
// Test 4: accessing an ID refreshes its LRU position (true LRU, not FIFO).
List<Event> input4 = Arrays.asList(
new Event("y1", 1, "p"), new Event("y2", 2, "p"),
new Event("y1", 3, "p-dup"), new Event("y3", 4, "p"), new Event("y1", 5, "p-dup2"));
List<Event> out4 = deduplicate(input4, 2);
System.out.println("Test 4 (LRU refresh-on-access, capacity=2): " + idsOf(out4));
assertEquals(Arrays.asList("y1", "y2", "y3"), idsOf(out4), "Test 4 failed");
System.out.println("\nAll assertions passed.");
}
}
Output (actually compiled with javac and run with java, OpenJDK 17):
Test 1 (basic dedup, capacity=10): [a, b, c]
Test 2 (capacity=2, forces eviction): [x1, x2, x3, x1]
Test 3 (same input, capacity=10, no eviction): [x1, x2, x3]
Test 4 (LRU refresh-on-access, capacity=2): [y1, y2, y3]
All assertions passed.
Test 2 is the deliberately non-vacuous proof for eviction: with capacity=2, x1 gets evicted once x3 arrives (the map is full at {x1, x2}, and x3 evicts the LRU entry, x1), so x1's later reoccurrence is correctly treated as NEW, appearing a second time in the output. Test 3 is the negative control proving this is genuinely eviction-driven, not a bug: the IDENTICAL input with capacity=10 (never full) correctly deduplicates x1 normally, appearing only once. Test 4 proves true LRU (not FIFO) semantics: y1's SECOND appearance (offset 3) refreshes its position, so when y3 arrives and forces an eviction, y2 (now the actual LRU entry) is evicted instead of y1, and y1's third appearance (offset 5) is still correctly recognized as a duplicate.
Complexity
- Time: O(n) for n input events. Each event does one
containsKey/getorputon theLinkedHashMap, both O(1) amortized (hash table lookup plus O(1) linked-list-position update for the access-order maintenance). - Space: O(min(capacity, n)) for the LRU map, plus O(n) for the output list (which, in the worst case of no duplicates, holds all n events); the BOUNDED part of the memory footprint, the part this design exists to control, is exactly the
capacity-sized seen-set, independent of total stream length.
Trade-offs and pitfalls
- Common mistake: using a plain
HashMapwith manual eviction bookkeeping (a separate queue tracking insertion order) instead ofLinkedHashMap's built-in access-order mode; this is more code, more places to introduce a bug, and typically no faster,LinkedHashMapalready provides exactly this mechanism natively. - Common mistake: forgetting to call
.get()(or otherwise touching the entry) on a detected duplicate. If a duplicate check only doescontainsKeywithout an access that updates LRU order, the map degrades toward FIFO- rather than LRU-eviction behavior, since frequently-seen duplicates would not be kept "fresh"; Test 4 above specifically exercises this detail. - Capacity sizing is a real trade-off, not a default. Too small, and legitimately spaced-apart duplicates (arriving further apart than
capacitydistinct IDs) are missed (treated as new, per Test 2's deliberate demonstration); too large, and memory use grows without the bound the LRU design exists to provide. - This design assumes event IDs are the sole correctness signal for "duplicate." If two events could share an ID but represent genuinely different logical events (a reused ID after a long gap), this bare ID-based approach would incorrectly treat them as the same, a compound key (ID plus a version/epoch) would be needed instead.
Design a deduplication solution for a streaming pipeline that must dedupe billions of event IDs with limited RAM per partition. Discuss probabilistic data structures (Bloom filters, counting filters), the trade-off of false positives, persistent compaction stores, and a hybrid architecture combining in-memory filters plus exact compaction. Explain how to validate and monitor false-positive rates in production.
Sample Answer
Direct answer
At billions of event IDs with limited RAM per partition, exact deduplication (a hash set of every ID) does not fit in memory, so the design combines a Bloom filter (or the more space-efficient counting-filter variant) as a fast, in-memory FIRST-PASS check that can definitively say "definitely new" but only "probably seen" for the rest, with a persistent compaction store (an on-disk, compacted key-value store, RocksDB or a compacted Kafka topic) as the authoritative, exact source of truth for anything the Bloom filter flags as a possible duplicate. This hybrid gets the Bloom filter's O(1)-in-memory speed for the common case (most IDs are genuinely new) while never actually LOSING correctness to a false positive, since every "probably seen" result is confirmed (or refuted) against the exact store before a decision is made.
Structured elaboration
Why a Bloom filter alone is insufficient here. A Bloom filter's false positives mean it can incorrectly report "seen" for a genuinely new ID, silently dropping real data if trusted alone, unacceptable for a deduplication mechanism whose entire job is correctness. Used correctly, the Bloom filter is a FILTER, not a decision-maker: "definitely not seen" (a negative result) can be trusted immediately (fast path, no exact-store lookup needed, this is the common case for genuinely new data and where the Bloom filter earns its keep), but "possibly seen" (a positive result) must be confirmed against the exact store before treating the ID as a true duplicate.
Counting filters versus plain Bloom filters. A counting Bloom filter (each slot is a small counter, not a single bit) supports DELETION (decrementing a counter when an ID ages out of relevance), which a plain Bloom filter cannot do without a full rebuild; this matters for a sliding-window dedup scenario where old IDs need to be forgotten, at the cost of more memory per slot (a counter needs several bits, versus one bit for a plain filter).
The persistent compaction store. A compacted, on-disk key-value store (RocksDB with native compaction, or a Kafka topic with log compaction keyed by event ID) holds the EXACT set of recently-seen IDs, persisted to disk (not memory-bound the way the Bloom filter is), with compaction periodically removing IDs old enough to be outside the relevant dedup window. This store is the authoritative check for anything the Bloom filter flags as a possible duplicate, and its own disk-based capacity is what actually scales to billions of IDs, the Bloom filter's job is purely to avoid paying a disk lookup for the (common) case where the answer is trivially "no."
Hybrid architecture, put together. On each incoming event ID: check the Bloom filter first. If NEGATIVE ("definitely new"): process as new, and asynchronously add the ID to both the Bloom filter and the compaction store (no blocking disk read needed on this fast path). If POSITIVE ("possibly seen"): look up the exact compaction store; if the ID IS actually present there, it is a true duplicate (skip); if NOT present (a Bloom filter false positive), it is genuinely new, process it and add it to both structures. This means every disk lookup is reserved for the (hopefully small) fraction of IDs that trigger a Bloom filter positive, most of which will genuinely be true duplicates in a healthy pipeline, keeping disk I/O proportional to the ACTUAL duplicate rate, not to total event volume.
Validating and monitoring false-positive rates in production. Periodically sample a batch of IDs the Bloom filter flagged POSITIVE and measure what fraction were confirmed FALSE POSITIVES by the exact-store lookup (a genuinely free-to-compute metric, since every positive already triggers an exact-store check as part of normal operation, this is just aggregating those results); alert if the measured rate drifts meaningfully above the Bloom filter's theoretically configured rate, which would indicate the filter is under-sized relative to actual ID cardinality (more distinct IDs inserted than the filter was sized for) rather than a bug, a capacity-planning signal, not a correctness bug, since correctness is preserved by the exact-store fallback regardless.
Worked example
At 2 billion distinct event IDs per partition per day, with 4 GB of RAM available per partition for the Bloom filter, targeting a 1% false-positive rate:
bits needed=−(ln2)2nln(p)=−(ln2)22,000,000,000×ln(0.01)≈1.917×1010 bits≈2.24 GiBcomfortably within the 4 GB budget, leaving headroom for the hash-function computation overhead and other process memory. If the actual observed cardinality grows to 4 billion IDs (2x the planned capacity) without resizing the filter, the effective false-positive rate does NOT merely double, it degrades steeply: using the exact closed-form Bloom filter formula, p=(1−e−kn/m)k, with the same m≈1.917×1010 bits and k=7 hash functions sized for the planned n=2×109 (which correctly reproduces the target p≈1.00%), doubling n to 4×109 with m and k unchanged gives p≈15.7%, roughly a 16x increase, not 2x. This is not an approximation error, it is how the formula behaves: false-positive rate is an EXPONENTIAL function of the load factor n/m, so a fixed bit array under 2x its designed cardinality does not degrade linearly with the overrun ratio, it degrades far faster once the filter's designed load factor is exceeded. This is directly visible via the monitored false-positive-rate metric described above, and the correct operational takeaway is sharper than 'roughly doubles' would suggest: a capacity review (resize the filter, or shard into more partitions) needs to trigger on a SMALL overrun, well before 2x, since by the time cardinality has doubled the fast path has already degraded by an order of magnitude, not a modest, easily-absorbed factor of two.
Trade-offs and pitfalls
- Common mistake: trusting a Bloom filter positive as a definitive duplicate without the exact-store confirmation. This silently drops genuinely new data at exactly the filter's configured false-positive rate, a correctness bug hiding behind what looks like a performance optimization; the hybrid architecture's entire value depends on NEVER skipping the confirmation step for a positive result.
- Common mistake: sizing the Bloom filter for a snapshot cardinality without planning for growth. As the worked example shows, actual item count exceeding planned capacity degrades the false-positive rate predictably; monitoring (per the dedicated subsection above) is what catches this before it becomes a meaningfully increased disk-lookup rate.
- The compaction store's own compaction cadence is a real trade-off. Compacting too aggressively risks removing an ID still within the relevant dedup window (reopening a genuine duplicate-acceptance risk); too infrequently, and the store's disk footprint grows past what it needs to for the actual dedup window: the same checkpoint/compaction trade-off any bounded store faces, applied here specifically to a dedup-metadata store.
- A counting filter's extra memory cost per slot is a real, not negligible, trade for supporting deletion. For a workload where the dedup window is genuinely sliding (old IDs must be actively forgotten, not just left to a periodic rebuild), the extra memory is usually worth it; for a workload with a simpler, append-only "have we EVER seen this ID" semantic, a plain Bloom filter (rebuilt periodically if needed at all) may be sufficient and cheaper.
Unlock Full Question Bank
Get access to all 22 Data Reliability and Fault Tolerance interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.