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.
Enumerate plausible failure modes for a high-cardinality IoT ingestion pipeline (device churn, network jitter, malformed messages, hot partitions, state-store corruption, disk-full). For each failure mode propose detection methods, mitigation strategies, and automated recovery steps, and rank the failures by impact and likelihood.
Sample Answer
Direct answer
For a high-cardinality IoT ingestion pipeline, the highest-impact failure modes are the ones that scale with device count rather than message volume alone: device churn (devices joining/leaving continuously) and hot partitions (a small subset of devices generating disproportionate traffic) are both consequences of the SAME underlying cardinality challenge and typically rank highest by combined impact and likelihood, since they are structural properties of the workload, not rare edge-case events; malformed messages and network jitter are common but individually lower-impact per occurrence; state-store corruption and disk-full are lower-likelihood but high-impact when they occur, warranting strong detection even at lower investment in prevention.
Structured elaboration, ranked by impact x likelihood
1. Hot partitions (high impact, high likelihood at this cardinality). A small number of high-frequency devices (or a partitioning scheme keyed poorly, e.g., by a low-cardinality device TYPE rather than device ID) can overload specific partitions while others sit idle. Detection: per-partition throughput/lag metrics, specifically flagging partitions whose load deviates significantly from the fleet average. Mitigation: partition by a higher-cardinality key (device ID with consistent hashing) rather than a coarser grouping; for a genuinely bursty individual device, a per-device rate limit protects the shared partition from any single device's burst. Automated recovery: dynamic re-partitioning or a dedicated overflow path for detected hot keys.
2. Device churn (high impact, high likelihood). Devices connecting/disconnecting continuously means per-device state (a connection record, a dedup window, a last-seen timestamp) is constantly being created and torn down at high cardinality; naive per-device state that never expires grows unboundedly (a direct memory-cost failure mode). Detection: total tracked-device count trending upward without bound, versus a stable or seasonally-varying ACTIVE-device count. Mitigation: TTL-based expiry on per-device state (the same sharded/time-bucketed expiry discipline as any bounded dedup store: keep only devices ACTIVE within a relevant recent window, drop the rest). Automated recovery: periodic garbage collection of expired device state, sized to the pipeline's own churn rate.
3. Malformed messages (medium impact, high likelihood at IoT scale). Firmware bugs, partial writes from flaky device connectivity, and protocol version drift across a large, heterogeneous device fleet make malformed messages a near-certainty at scale. Detection and mitigation: standard DLQ/poison-message handling applies directly (schema validation at ingestion, quarantine rather than crash). Automated recovery: standard DLQ replay after a fix, scoped per firmware-version or device-model if the malformation correlates with a specific device population (a common IoT-specific diagnostic angle: "which FIRMWARE VERSION is producing these," not just "which messages").
4. Network jitter (medium impact, high likelihood). Variable, sometimes-high latency from IoT devices (often on constrained or cellular connectivity) causes events to arrive significantly out of order relative to their true event time. Detection: monitoring the distribution of (ingestion_time - event_time) lag, watching for a widening tail. Mitigation: a watermark/lateness tolerance sized generously enough for this specific device population's realistic jitter (wider than a typical low-jitter server-to-server pipeline would need), using the pipeline's own dedup/windowing logic. Automated recovery: late-arriving events within the tolerance window are simply processed normally by the existing lateness-handling logic; events beyond it fall to the DLQ or a dedicated late-arrival reconciliation path.
5. State-store corruption (high impact, lower likelihood). Corruption of an operator's persistent state store (RocksDB or similar) is rarer but severe when it happens, since it can affect ALL keys the corrupted store shard is responsible for, not just one device. Detection: checksums on state-store reads (many embedded stores support this natively) and periodic state-store integrity validation. Mitigation and recovery: the standard WAL-plus-checkpoint recovery pattern is the direct defense, since corrupted local state can be discarded entirely and rebuilt from checkpoint plus WAL replay, exactly the scenario that pattern exists to handle.
6. Disk-full (high impact, lower likelihood but worth explicit planning). A rarely-tested but real risk, especially for a high-cardinality workload where state-store growth is less predictable than in a low-cardinality system. Detection: proactive disk-usage alerting well before capacity, not reactive discovery at 100%. Mitigation: the TTL/expiry discipline from device churn (above) directly bounds state growth, reducing this risk's likelihood; capacity planning informed by MEASURED per-device state size x expected device-count growth, not a static provisioning guess.
Worked example
A fleet of 5 million devices, average message rate 1/minute/device (steady), but with a measured top-0.1% of devices sending at 100x the average rate (a common real IoT pattern: a subset of devices in a debug/verbose mode, or malfunctioning and retrying excessively):
5,000,000×0.001=5,000 devices in the ’hot’ tail 5,000×100=500,000 "device-rate-units" of load from just these 5,000 devices versus (5,000,000−5,000)×1≈4,995,000 device-rate-units from the remaining 99.9% of the fleetso the 0.1% hot tail contributes roughly 500,000/(500,000+4,995,000)≈9.1% of total load concentrated on whichever partitions those 5,000 devices happen to hash to, a real, measurable hot-partition risk from a small device subset, exactly why per-device rate limiting (capping any single device's contribution) and monitoring per-partition load deviation (not just aggregate throughput) both matter at this cardinality specifically.
Trade-offs and pitfalls
- Common mistake: ranking failure modes by how DRAMATIC they sound rather than by actual impact x likelihood. State-store corruption sounds alarming, but at most fleets' actual observed frequency, hot partitions and device churn cause far more day-to-day operational cost; the ranking in this answer is deliberately grounded in that combined metric, not in narrative severity alone.
- Common mistake: sizing partitioning and state-expiry policies for the AVERAGE device, not the observed tail. As the worked example shows, a small tail of high-rate devices can dominate a specific partition's load even when the fleet-wide average looks entirely comfortable.
- Detection for state-store corruption needs to exist BEFORE it happens, not be reactive. Because the WAL-plus-checkpoint recovery pattern only helps once corruption is DETECTED, a store silently serving wrong data without a checksum failure firing is a bigger risk than the corruption event itself.
- All six failure modes interact, not just co-occur. A device-churn spike (many new devices connecting at once) can itself CREATE a temporary hot-partition condition (many new keys landing on the same consistent-hashing range briefly) and a burst of malformed messages (new device firmware not yet fully validated), which is why the ranking above should inform prioritization, not be read as "handle these independently and in isolation."
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.
Design a reproducible pipeline to build deterministic trip facts from a noisy raw event lake. Requirements: fully reproducible runs that produce identical outputs for the same input snapshot, support reprocessing and backfills, and minimize consumer downtime. Describe storage layout (immutable dataset versions), checkpointing, and the idempotency guarantees needed to make replay safe.
Sample Answer
Direct answer
Byte-identical, reproducible runs against the same input snapshot require three things: an IMMUTABLE, explicitly versioned reference to "the input" (a specific table version or dated extract, never "whatever the source currently contains"), a transformation that is deterministic with respect to physical read/arrival order (every reduction fixes an explicit sort or tiebreak key before folding, since a distributed engine's own partition read order is not guaranteed stable run to run), and immutable, versioned OUTPUT datasets built in isolation and cut over via an atomic pointer swap, so reprocessing and backfills never touch what is currently being served. Below is an executed demonstration proving that a naive, order-dependent build genuinely produces two DIFFERENT results from the identical input, and that fixing an explicit ordering key resolves it.
Structured elaboration
Storage layout: immutable, versioned input snapshots. "The same input" is only a well-defined concept if it refers to an explicit, immutable version (a specific Delta/Iceberg table version, or a date-partitioned, never-overwritten extract), not the live, mutable state of a source that can change between when a job first runs and when the "same" job reruns later. Without this, reproducibility is undefined in principle, not just hard in practice.
Deterministic transformations. A distributed engine's shuffle and partition read order is not guaranteed to be stable across runs (different task scheduling, different partition-to-worker assignment). Any reduction that is naturally order-INSENSITIVE (sum, count, min, max) is safe regardless. Any reduction that is order-SENSITIVE by nature (last-value-wins, first-seen-wins, string concatenation) must have its ordering made EXPLICIT: sort by a stable key (an event timestamp, a per-record sequence number) before reducing, rather than trusting whatever order records happen to arrive in during a given run.
Storage layout: immutable, versioned OUTPUT datasets. Write each build to a NEW versioned output (a new Delta/Iceberg version, or a distinctly named dataset version), never overwriting the currently-served version in place. This is what makes both reprocessing and rollback safe: a bad build never touches what consumers are currently reading, and reverting is just re-pointing at the prior version.
Minimizing consumer downtime via atomic cutover. Build the new version fully, validate it, and only then switch consumers to it via a single atomic pointer/view update, so the cutover moment itself is a metadata change, not a data copy, and causes no meaningful downtime; the actual time investment (building and validating the new version) happens entirely before the cutover, with zero impact on what is currently being served.
Idempotency guarantees for safe replay. Content-address the output version by a hash of everything that determines it (the input snapshot version, the transformation code's version, and its configuration). Re-running the identical pipeline version against the identical input snapshot then either produces the identical output (a safe no-op if already built) or, if genuinely re-executed, an output that is byte-identical to the prior run, both proving and enforcing the reproducibility guarantee at the metadata level, not just asserting it.
Worked example
The demonstration below builds a single trip's facts (a total fare from several fare-adjustment events, and a status from several status-change events) from the SAME 5 raw events, delivered in two DIFFERENT physical arrival orders (simulating two reruns reading the same immutable input snapshot through a shuffled, multi-partition distributed read path, a realistic and common source of nondeterminism). A naive build folds directly over arrival order; a deterministic build sorts by a stable event key first.
"""
Demonstrates WHY a naive fold-over-arrival-order build of "trip facts" is
NOT reproducible across reruns against the identical input snapshot, and why
a build that fixes an explicit sort key before reducing IS. Two "runs" read
the SAME 5 raw events for one trip, but a distributed source (multiple
shuffled input partitions) delivers them in a genuinely DIFFERENT physical
order each run -- the input SET is identical, only arrival order differs,
which is exactly the situation "same input snapshot" must be immune to.
"""
import hashlib
import json
# The same 5 raw, noisy events for trip "T-9001", identical in both runs.
EVENTS = [
{"event_id": "e1", "ts": 100, "type": "fare_adjustment", "amount": 12.50},
{"event_id": "e2", "ts": 103, "type": "status", "value": "in_progress"},
{"event_id": "e3", "ts": 101, "type": "fare_adjustment", "amount": -1.25},
{"event_id": "e4", "ts": 105, "type": "status", "value": "completed"},
{"event_id": "e5", "ts": 102, "type": "fare_adjustment", "amount": 3.75},
]
# Two DIFFERENT physical arrival orders for the SAME set of events, simulating
# two reruns reading the same input snapshot through a shuffled/partitioned
# distributed read path (a realistic, common source of nondeterminism).
RUN_1_ARRIVAL_ORDER = [EVENTS[0], EVENTS[1], EVENTS[2], EVENTS[3], EVENTS[4]]
RUN_2_ARRIVAL_ORDER = [EVENTS[3], EVENTS[2], EVENTS[4], EVENTS[0], EVENTS[1]]
def naive_build(events_in_arrival_order):
"""BUG: folds directly over whatever order the events arrived in.
'Last status wins' means last-in-ARRIVAL-order, not last-by-EVENT-TIME."""
total_fare = 0.0
last_status = None
for e in events_in_arrival_order:
if e["type"] == "fare_adjustment":
total_fare += e["amount"]
elif e["type"] == "status":
last_status = e["value"] # overwritten by ARRIVAL order
return {"trip_id": "T-9001", "total_fare": round(total_fare, 2), "status": last_status}
def deterministic_build(events_in_arrival_order):
"""FIX: sort by an explicit, stable key (event_id, a stand-in for a
monotonic per-trip sequence number) BEFORE reducing, so the reduction
itself never depends on physical arrival order."""
ordered = sorted(events_in_arrival_order, key=lambda e: e["event_id"])
total_fare = 0.0
last_status = None
last_status_ts = -1
for e in ordered:
if e["type"] == "fare_adjustment":
total_fare += e["amount"]
elif e["type"] == "status" and e["ts"] > last_status_ts:
last_status = e["value"] # last-by-EVENT-TIME, order-independent
last_status_ts = e["ts"]
return {"trip_id": "T-9001", "total_fare": round(total_fare, 2), "status": last_status}
def content_hash(record):
return hashlib.sha256(json.dumps(record, sort_keys=True).encode()).hexdigest()[:12]
def main():
naive_1 = naive_build(RUN_1_ARRIVAL_ORDER)
naive_2 = naive_build(RUN_2_ARRIVAL_ORDER)
print("Naive build, run 1 (arrival order: e1,e2,e3,e4,e5):", naive_1, "hash=", content_hash(naive_1))
print("Naive build, run 2 (arrival order: e4,e3,e5,e1,e2):", naive_2, "hash=", content_hash(naive_2))
assert naive_1["total_fare"] == naive_2["total_fare"] == 15.0, \
"fare sum is commutative here regardless of order (isolating the bug to the status field)"
assert naive_1["status"] == "completed", "run 1's LAST-ARRIVING event happens to be e5 (fare), so last STATUS event seen is e4=completed"
assert naive_2["status"] == "in_progress", "run 2's LAST-ARRIVING status event is e2=in_progress, even though e4 (completed) happened LATER in real time"
assert naive_1 != naive_2, "the SAME input snapshot produced two DIFFERENT outputs -- reproducibility is broken"
print("\nCONFIRMED: naive build is non-reproducible. Same 5 input events, two physically")
print("different (but equally valid) arrival orders, two DIFFERENT final records --")
print(f"including a wrong-by-construction status ('in_progress' when the trip actually")
print(f"completed at ts=105), not just a cosmetic hash difference.")
det_1 = deterministic_build(RUN_1_ARRIVAL_ORDER)
det_2 = deterministic_build(RUN_2_ARRIVAL_ORDER)
print("\nDeterministic build, run 1:", det_1, "hash=", content_hash(det_1))
print("Deterministic build, run 2:", det_2, "hash=", content_hash(det_2))
assert det_1 == det_2, "sorting by a stable key before reducing must make the two runs byte-identical"
assert content_hash(det_1) == content_hash(det_2)
assert det_1["status"] == "completed", "correctly reflects the event with the LATEST event-time, not arrival order"
print("\nCONFIRMED: deterministic build is reproducible (identical output, identical content")
print("hash) across both arrival orders, AND correctly reflects the true last-by-event-time")
print("status ('completed'), fixing both the nondeterminism and the underlying correctness bug.")
if __name__ == "__main__":
main()
Output (actually executed with python3):
Naive build, run 1 (arrival order: e1,e2,e3,e4,e5): {'trip_id': 'T-9001', 'total_fare': 15.0, 'status': 'completed'} hash= 27141dcab833
Naive build, run 2 (arrival order: e4,e3,e5,e1,e2): {'trip_id': 'T-9001', 'total_fare': 15.0, 'status': 'in_progress'} hash= 2ecc4bf114e8
CONFIRMED: naive build is non-reproducible. Same 5 input events, two physically
different (but equally valid) arrival orders, two DIFFERENT final records --
including a wrong-by-construction status ('in_progress' when the trip actually
completed at ts=105), not just a cosmetic hash difference.
Deterministic build, run 1: {'trip_id': 'T-9001', 'total_fare': 15.0, 'status': 'completed'} hash= 27141dcab833
Deterministic build, run 2: {'trip_id': 'T-9001', 'total_fare': 15.0, 'status': 'completed'} hash= 27141dcab833
CONFIRMED: deterministic build is reproducible (identical output, identical content
hash) across both arrival orders, AND correctly reflects the true last-by-event-time
status ('completed'), fixing both the nondeterminism and the underlying correctness bug.
This is not a cosmetic hash mismatch: the naive build's SECOND run produces a status of in_progress for a trip that had actually reached completed (its true last event by real time), purely because that run's physical arrival order happened to deliver the completed status event before the in_progress one. The deterministic build, sorting by a stable key before reducing, produces the byte-identical, correct result on both runs. This is exactly the class of bug that "looks fine" in a single test run (whichever order the developer happened to test with) and only surfaces as a silent, wrong-and-different result on a LATER rerun, precisely when reproducibility is being relied upon most.
Trade-offs and pitfalls
- Common mistake: assuming a "last write wins" reduction is naturally reproducible because it is simple. As demonstrated, it is exactly the reduction that is NOT reproducible unless explicitly keyed by something stable (event time, a sequence number), since "last" implicitly means "last in whatever order this run happened to process records," which a distributed engine does not guarantee is stable.
- Common mistake: overwriting the output dataset in place rather than versioning it. This makes both rollback and safe backfill much harder: a bad build corrupts the only copy, and a backfill covering the same range as a currently-live build has nothing safe to write into without risking a partial, visible bad state mid-write.
- Content-addressing the output by input-version plus code-version is what turns "we believe this is reproducible" into something CHECKABLE, a hash mismatch on a rerun that should have been identical is a concrete, automatic signal that some hidden nondeterminism exists, rather than something a team discovers only when two engineers' results disagree by chance.
- Floating-point summation order can, in some cases, also affect bit-level reproducibility even for a genuinely order-INSENSITIVE reduction like sum, since floating-point addition is not strictly associative; for a use case that needs bit-exact reproducibility (not just logically-equivalent results), pinning the summation order explicitly (not just the final tiebreak key) may also be necessary, beyond what this worked example's status-field bug required to demonstrate.
Compare low-latency exactly-once approaches (e.g., Kafka/Flink transactions) with at-least-once processing plus deduplication when designing a pipeline for analytics versus one for payments. Discuss throughput, complexity, operational burden, and failure scenarios for each workload.
Sample Answer
Direct answer
The right choice is workload-driven, not universally "better": an analytics pipeline should default to at-least-once processing plus deduplication, because analytics tolerates small windows of eventual correctness in exchange for much simpler operations and higher throughput, while a payments pipeline should pay for low-latency exactly-once (Kafka transactions plus Flink's two-phase-commit sink, or an equivalent) because a financial system cannot tolerate even a transient double-charge, and its lower relative throughput requirement makes the extra operational cost affordable.
Structured elaboration
Throughput. Kafka/Flink transactional exactly-once adds coordination overhead: a transaction commit protocol across producer, broker, and consumer offsets, plus (for Flink) checkpoint-aligned barriers gating when transactions can commit. This measurably reduces maximum sustainable throughput compared to plain at-least-once (no coordination, just produce and consume as fast as the hardware allows). At-least-once plus downstream dedup keeps the hot path simple and fast, paying the correctness cost later, at the dedup step, which can often be batched or made cheaper than transactional coordination on every single record.
Complexity. Exactly-once via transactions requires every component in the chain to participate correctly: idempotent producers, transactional consumers reading only committed offsets (read_committed isolation level), and checkpoint-aligned sink commits. Misconfiguring any one piece (an accidental read_uncommitted consumer, a non-transactional sink in the chain) silently breaks the guarantee without any error, since the pipeline keeps running, just with a weaker guarantee than intended. At-least-once-plus-dedup is conceptually simpler: get everything delivered, then deduplicate by key, a technique any single team can implement and reason about locally.
Operational burden. Exactly-once transactional pipelines need careful monitoring of transaction timeouts (a stalled transaction blocks downstream consumers reading read_committed, since they cannot see past an open transaction) and of checkpoint health (a stalled checkpoint stalls transaction commits). At-least-once-plus-dedup's operational surface is simpler: monitor consumer lag and dedup-store health, both well-understood, widely-tooled concerns.
Failure scenarios. Under exactly-once transactions, a coordinator or broker failure mid-transaction can leave a transaction open longer than its timeout, causing downstream consumers to stall waiting for it to resolve, a availability-for-consistency trade that is exactly the E in CAP terms being spent. Under at-least-once-plus-dedup, the same failure just causes redelivery, handled by the dedup layer with no consumer-side stall, at the cost of a brief window where duplicates could theoretically reach a consumer that skips dedup (a real risk only if the dedup step itself is bypassed or misconfigured).
Worked example
Analytics pipeline: 500,000 events/sec of clickstream data, at-least-once ingestion via Kafka, deduplicated downstream using a 24-hour sliding window on event_id. A brief network blip causing 0.1% redelivery:
500,000×0.001=500 duplicate events/sec, all silently absorbed by the dedup stepNo consumer stall, no transaction timeout risk; the analytics aggregate is correct within the normal dedup-window latency, and 500,000 events/sec throughput is realistically sustainable with plain at-least-once delivery.
Payments pipeline: 2,000 transactions/sec (a full order of magnitude lower than the analytics case, typical of a payments-critical path versus a clickstream), using Kafka transactions end to end with a transactional, idempotent sink (a Flink job with exactly-once checkpointing and a two-phase-commit database sink). At 2,000 TPS, the added coordination overhead of transactional commits is comfortably absorbable, whereas at 500,000 events/sec the same coordination overhead would likely become the pipeline's throughput ceiling. This is the concrete shape of "throughput budget determines whether the exactly-once tax is affordable": payments pays it because it can and must; analytics does not pay it because the value of doing so is lower and the cost of paying it (throughput ceiling) is higher relative to its actual load.
Trade-offs and pitfalls
- Common mistake: assuming exactly-once via transactions eliminates the need for any dedup logic at all. Transactional exactly-once guarantees correctness WITHIN the transactional chain (producer to this specific consumer's committed offset), not necessarily end-to-end if any hop in the chain is not itself transactional (a REST call to a legacy system with no transaction support); a payments pipeline calling such a system still needs idempotent-write discipline at that hop.
- Common mistake: choosing at-least-once-plus-dedup for payments "because it's simpler." Simplicity is a real virtue, but for payments the downside of a dedup-layer bug (a transient double-charge visible to the customer before correction) is categorically worse than the operational cost of transactions; the choice should be driven by the cost of a guarantee failure, not by engineering convenience alone.
- Transaction timeouts are a real, underestimated operational risk. A payments team that adopts exactly-once transactions without also monitoring and alerting on transaction duration can be surprised by a slow downstream dependency silently stalling every consumer reading
read_committed, a failure mode that simply does not exist under at-least-once-plus-dedup. - The choice is not binary across an entire pipeline. A hybrid is common and often correct: exactly-once for the specific payments-critical hop, at-least-once-plus-dedup for a downstream analytics fan-out reading the same event stream for reporting, since the reporting consumer's correctness needs do not justify inheriting the payments hop's operational cost.
Architect a replayable ingestion pipeline that supports transactional reprocessing: guarantees ordering per key, deduplication, idempotent sinks, and the ability to replay from arbitrary offsets across Kafka and object-storage input sources. Include the metadata/tracking store design, how you will coordinate replays across multiple pipelines, and how to ensure correctness and performance during reprocessing.
Sample Answer
Direct answer
A replayable ingestion pipeline needs four pieces: a REPLAY MANIFEST that is the durable source of truth for what a given replay run covers and how far it has progressed (itself checkpointed and resumable), per-key ordering preserved by re-deriving a stable ordering key from event metadata rather than relying on physical read order (which Kafka and object storage do not share), deduplication and idempotent sinks keyed by an identity that is IDENTICAL whether a record arrives via normal ingestion or replay, and replay execution isolated into a separate shadow output track that is validated and then atomically promoted, rather than replayed directly against the live production output.
Structured elaboration
Metadata/tracking store (the replay manifest). One row per replay run: a replay ID, the pipeline it targets, a range specification (an offset range per Kafka partition; an object-key prefix plus version for object storage), a status (pending, running, validating, promoted, aborted), and its own progress checkpoints. The replay job is itself checkpointed against this manifest, so an interrupted replay is resumable rather than needing to restart from the beginning.
Ordering per key across two source types that do not share a native ordering concept. Kafka gives per-partition FIFO order for free; object storage gives none at all, files simply exist. Relying on either source's physical read or listing order for cross-source ordering is exactly the mistake a naive fold over arrival order, rather than a fixed key, makes. The fix is the same one: every record carries an explicit ordering key at ORIGINAL ingestion time (an event timestamp or a per-key monotonic sequence number), and replay sorts or routes by that key rather than by however the record happens to be read back.
Deduplication and idempotent sinks. A replayed record's identity key (used for the sink's idempotent upsert) must be IDENTICAL to what original ingestion would have assigned it. This means no separate "replay merge logic" is needed: the sink's ordinary idempotent-write path naturally reconciles a replay against anything already applied, whether the original write succeeded, partially succeeded, or never happened.
Coordinating replays across multiple, dependent pipelines. Downstream pipelines that consume this pipeline's output form a dependency graph. A replay must not silently feed a downstream pipeline mid-run, since that mixes replay-track data into the downstream pipeline's normal live processing. Tagging every replayed record with its replay ID lets downstream consumers distinguish replay-track output from production-track output, and a coordinator sequences dependent pipelines' replays in TOPOLOGICAL order (an upstream pipeline's replay must reach "promoted" status before a dependent downstream pipeline's corresponding replay begins), rather than letting them race.
Correctness and performance during reprocessing. Correctness: replay writes into a shadow output (a separate table or namespace), validated against expected checksums or row counts before an atomic promote makes it visible to consumers, so a bug discovered mid-replay never contaminates the live production output. Performance: replay throughput is throttled against the source's and sink's normal capacity budget, since an unthrottled replay competing with live traffic for the same infrastructure risks becoming a NEW incident rather than resolving the one it was meant to fix.
flowchart TB
subgraph Sources
K[Kafka topics]
O[Object storage]
end
K --> R[Replay coordinator]
O --> R
M[(Replay manifest:\nrange, status, progress)] <--> R
R --> S[Shadow output namespace]
S --> V[Validation: checksum / row-count check]
V -->|pass| P[Atomic promote]
V -->|fail| X[Abort, alert]
P --> D1[Downstream pipeline 1]
P -->|replay_id gates start| D2[Downstream pipeline 2]
Worked example
Pipeline P1 ingests raw payment events; pipeline P2 consumes P1's output to build a daily settlement aggregate. A bug in P1 is found and fixed; a replay of P1 for the affected 3-day window is registered in the manifest as replay_id=R100, covering the corresponding Kafka offset ranges and object-storage key prefixes for that window. P1's replay writes to a shadow table, validated (row count and checksum match the expected recomputation) against the affected window, then atomically promoted. Only once the manifest shows R100: promoted does the coordinator register and release P2's OWN replay (replay_id=R101) for the same 3-day window, now correctly consuming P1's corrected, promoted output rather than racing against a still-in-progress P1 replay or against P1's pre-fix production data.
Trade-offs and pitfalls
- Common mistake: replaying directly into the live production output instead of a shadow track. This is faster to build but means a bug discovered mid-replay (or a validation failure after the fact) has already contaminated what consumers are reading; the shadow-then-promote pattern trades some extra storage and compute during the validation window for the ability to catch a bad replay before it ships.
- Common mistake: letting a downstream pipeline's replay start before its upstream dependency's replay is confirmed promoted. This silently mixes replay-track and production-track (or partially-replayed) upstream data into the downstream replay, corrupting its result in a way that is hard to detect after the fact.
- Coordinating replay ordering across many dependent pipelines adds real end-to-end latency to a full-catalog replay. This is worth paying specifically when correctness genuinely depends on the pipelines observing a consistent upstream state, not as a default for every replay regardless of whether the pipelines are actually coupled.
- Throttling replay against live capacity extends how long the replay takes, but an unthrottled replay competing for the same infrastructure as live production traffic risks becoming the SECOND incident on top of the one the replay was meant to fix.
Unlock Full Question Bank
Get access to all 45 Data Reliability and Fault Tolerance interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.