Data Consistency and Distributed Transactions Questions
Maintaining correctness of state across services and replicas: eventual consistency, conflict resolution (last-write-wins, CRDTs, vector clocks), the saga pattern, two-phase commit, and idempotency keys for exactly-once effects. Covers when to trade strict consistency for availability and how to reason about read-your-writes and monotonic guarantees. Focuses on the application/service layer rather than storage-engine internals.
Explain the differences between Lamport clocks, vector clocks, and logical timestamps in general. For each, state what it can and cannot detect (ordering versus true concurrency) and walk through a brief example of how it's updated on send and receive events.
Sample Answer
Direct answer: Lamport clocks give you a total ordering consistent with causality (if A happened-before B, A's Lamport timestamp is smaller), but they CAN'T tell you whether two events are truly concurrent, two unrelated events can end up with different Lamport timestamps that make them look ordered even though neither actually caused the other. Vector clocks fix exactly this gap: they can tell you happened-before, happened-after, AND genuinely concurrent, at the cost of a counter per replica instead of a single number.
Structured elaboration
Lamport clocks: mechanism. Each process keeps a single integer counter. On a LOCAL event, increment the counter. On SENDING a message, attach the current counter value. On RECEIVING a message with timestamp T, set the local counter to max(local_counter, T) + 1. This guarantees: if event A causally precedes event B (a happens-before relationship via a chain of local events and messages), then timestamp(A) < timestamp(B). But the CONVERSE isn't guaranteed: timestamp(A) < timestamp(B) does NOT imply A happened before B, they might be completely unrelated events that just happened to get ordered that way by the counter mechanics.
Vector clocks: mechanism. As described for causality tracking, each process keeps a vector of counters, one per process, and comparison (element-wise) tells you happened-before, happened-after, or concurrent, unambiguously. This is strictly more information than a Lamport clock provides.
What each can and cannot detect.
| Can detect happened-before? | Can detect true concurrency? | Metadata overhead | |
|---|---|---|---|
| Lamport clock | Yes (via the ordering property) | No, false ordering can appear between unrelated events | One integer per event |
| Vector clock | Yes | Yes, this is exactly what element-wise incomparability signals | One integer PER PROCESS per event |
| Logical timestamps (general term) | Depends on the specific scheme | Depends on the specific scheme | Depends |
Worked example. Two independent processes P1 and P2 never communicate. P1's local Lamport counter reaches 5 after some local events; P2's, independently, reaches 3. If you now compare timestamp(P1's event) = 5 and timestamp(P2's event) = 3, it LOOKS like P2's event happened before P1's (smaller timestamp), but there's no actual causal relationship at all, they're on completely independent tracks. A vector clock comparing {P1:5, P2:0} against {P1:0, P2:3} correctly identifies these as concurrent (neither vector dominates), the Lamport clock's single integer has no way to express that.
Send/receive update walkthrough (Lamport). P1 has local counter 2 and sends a message; the message carries timestamp 3 (2, then incremented for the send event itself). P2 has local counter 1 when it receives this message; it computes max(1, 3) + 1 = 4 and sets its own counter to 4. Any subsequent event P2 does will carry a timestamp of at least 4, correctly reflecting that it happens after P1's send (which had timestamp 3), preserving the causal ordering property even though P2's OWN prior activity (counter 1) was much lower.
Send/receive update walkthrough (vector clock). Two processes, P1 and P2, start at {P1:0, P2:0}. P1 does a local event, incrementing its own entry: {P1:1, P2:0}, then sends a message carrying that vector. P2, before receiving it, does its own local event, incrementing its own entry: {P1:0, P2:1}. When P2 RECEIVES P1's message, it merges element-wise (max per entry: {P1: max(0,1)=1, P2: max(1,0)=1}) and then increments its own entry for the receive event itself, landing at {P1:1, P2:2}. Comparing P2's pre-receive vector {P1:0, P2:1} against P1's sent vector {P1:1, P2:0} shows neither dominates, correctly flagging P1's local event and P2's local event as concurrent, exactly the distinction a Lamport clock's single integer cannot make (a Lamport clock would just assign each an arbitrary-looking total order with no way to mark them as concurrent).
Trade-offs and pitfalls. Choosing Lamport clocks when you actually NEED to detect true concurrency (e.g. for conflict detection in a replicated data store) is a real design bug, not a simplification, since Lamport clocks will silently impose a false ordering on genuinely conflicting concurrent writes rather than flagging them as needing resolution. Lamport clocks are the right, cheaper choice specifically when all you need is a consistent total order for something like event logging or debugging causality chains, not for detecting write-write conflicts.
Design a conflict detection and resolution strategy for a piece of user data that may be updated concurrently at multiple regions (for example, user preferences, or a shopping cart with offline mobile edits). What options would you weigh, and how would you present a merge conflict to the user when automatic resolution isn't confidently correct?
Sample Answer
Direct answer: For data that can be updated concurrently at multiple regions, the right conflict-resolution strategy depends on what the data actually represents: last-write-wins for genuinely replace-semantic fields, CRDTs for anything where both concurrent contributions should survive automatically, version vectors when you need to DETECT a conflict precisely but resolution requires more context than a generic rule can provide, and application-level merge (informed by user intent) when the data has domain-specific meaning a generic rule would get wrong.
Structured elaboration
Last-write-wins. Simplest option; correct choice when the field has a genuine "replace" semantic and losing an older concurrent write is a non-issue (see the LWW discussion elsewhere in this topic for where this holds and where it doesn't).
CRDTs (state-based or op-based). Correct choice when the data type has a well-defined, generic merge function that preserves both concurrent contributions automatically (counters, sets, sequences), no application-specific judgment needed at merge time, the merge function itself IS the resolution.
Version vectors (as a detection mechanism, not a resolution mechanism on their own). Useful when you need to reliably DETECT that a conflict exists (distinguishing "genuinely concurrent" from "one clearly happened after the other") but the actual resolution needs more context than a generic rule can supply, version vectors tell you THAT there's a conflict; something else (LWW, application logic, a human) has to decide WHAT to do about it.
Application-level merge based on user intent. The right choice when the data is domain-specific enough that no generic structural rule (LWW, CRDT, or otherwise) captures the correct resolution, the application needs custom logic that understands what the data MEANS. A concrete case: two concurrent edits to a user's notification preferences, where the "correct" merge might depend on business rules like "the more restrictive (less permissive) setting wins" for a privacy-sensitive toggle, a domain judgment call, not something a generic CRDT or LWW rule would know to apply.
Worked example: user preference updates. A user changes their notification preferences from their phone (enabling email notifications) while, concurrently and offline, changing them from their laptop (disabling ALL notifications, a broader privacy-oriented change). A naive LWW resolution would pick whichever device's write has the later timestamp, potentially resulting in email notifications being enabled even though the user's OTHER, more recent-feeling intent (from their perspective) was to turn things off. An application-level merge rule, informed by the specific business/privacy semantics of THIS field ("prefer the more restrictive setting on conflict" is a reasonable, defensible product decision here), produces a result that matches what the user probably actually wanted, better than either LWW or a generic CRDT structural rule would, since neither of those understands that "disable all" should take precedence over "enable one channel" for a privacy-sensitive toggle.
Presenting merge conflicts to users when automatic resolution isn't confident. For genuinely ambiguous cases where even a domain-informed rule can't confidently decide (e.g. two concurrent, materially different, both-plausible edits to a text field), the interface can show both candidate values with metadata about their origin (which device, when) and let the user explicitly choose or merge manually, rather than the system guessing silently, this converts a potential silent-data-loss bug into a small, transparent moment of user friction, generally the better trade for anything where getting it wrong silently would be worse than asking.
Handling a conflict storm. These strategies also need to hold up under volume, not just for one isolated conflicting pair. After a large network partition heals, many keys can surface divergent updates all at once, a conflict storm, and the resolution strategy above needs an operational playbook for that scale: triage which conflicts are high-value (revenue-affecting, security-relevant) versus low-stakes and can auto-resolve via the default rule; apply automated mitigation for the low-stakes majority immediately; and have a safe rollback path (freezing further writes to the affected keys, or serving from a known-good snapshot) if the automated resolution itself turns out to be producing bad results, with clear communication to stakeholders about the scope and expected resolution time while it's ongoing.
Operational and correctness trade-offs. Application-level merge logic is the most POWERFUL option (it can encode exactly the right domain behavior) but also the most bespoke and hardest to get uniformly correct, every new field with custom merge logic is new code that needs its own tests and its own review for correctness, unlike a CRDT or LWW rule that, once implemented, generalizes safely to every field that uses it.
For a high-throughput streaming ETL ingesting user events, what metadata would you record to enable efficient deduplication of events within a time window? Explain how fields such as event_id, user_id, event_time, ingestion_time, and partition offsets are used during processing, and the retention implications of keeping that metadata. Then list the common deduplication approaches available (producer-side dedupe, consumer-side dedupe using state, dedupe tables or upserts, watermark/window compaction) and give one advantage and one drawback of each.
Sample Answer
Direct answer
To deduplicate streaming events efficiently you need a compact key, event_id (or a stable natural key), plus enough context to bound how long you must remember it: event_time (when it happened), ingestion_time (when your pipeline saw it), user_id or another partition key, and the source partition offset (to resume correctly after a restart). The retention window for that metadata should track your event-time watermark, typically bounded by the maximum out-of-order lateness you tolerate, not kept forever. Four dedup approaches exist at different points in the pipeline: producer-side dedupe, consumer-side dedupe using state, dedupe tables or upserts, and watermark/window compaction; each trades off where the work happens and how much state it needs.
Structured elaboration
What each metadata field is for:
event_id: the stable identity of the logical event. This is the dedup key. It must be assigned once, upstream, and preserved through every retry or replay; a UUID generated fresh on each retry defeats the purpose (mirrors the idempotency-key discipline).user_id(or another natural partition key): lets you shard dedup state per key instead of maintaining one global structure, and lets you bound state size per partition rather than globally.event_time: the business timestamp of when the event actually occurred. This is what watermarks and windowing operate on, and what "same time window" means for compaction.ingestion_time: when the pipeline observed the event. Used to detect abnormal ingestion delay and to distinguish "arrived late but is old" from "arrived late and is actually a new, recent event."- Partition offsets (e.g. Kafka partition + offset): the resume point. After a consumer restart, replaying from the last committed offset can redeliver events already processed; offsets let you reason about exactly which range might be duplicated, narrowing what you need to re-check instead of rescanning everything.
Retention implications. Every dedup approach that keeps state (a seen-IDs set, a dedup table, windowed state) must bound that state, or memory/storage grows without limit. The bound is set by the watermark: once you declare "no event older than event_time T will arrive," you can safely forget dedup state for windows entirely older than T. Choosing too short a window lets late duplicates slip through unnoticed; choosing too long a window wastes memory holding state for windows that will never see another duplicate.
Four deduplication approaches:
| Approach | Advantage | Drawback |
|---|---|---|
| Producer-side dedupe (producer assigns a stable ID and the broker/idempotent producer API rejects a resend within its own dedup window) | Cheapest: eliminates the duplicate before it enters the pipeline at all, no downstream state needed | Only covers producer-to-broker retries; a duplicate reintroduced further downstream (a second producer instance, a replay job) is invisible to it |
Consumer-side dedupe using state (the consumer keeps a set or a compacted state store of seen event_ids per key, checked before processing) | Catches duplicates regardless of where upstream they originated; works even if the producer has no dedup guarantee | Consumer must maintain and bound the state (memory or an external store like RocksDB-backed state or Redis); adds a lookup on every event |
Dedupe tables or upserts (write to the sink keyed by event_id, letting an INSERT ... ON CONFLICT or MERGE collapse duplicates at write time) | Correctness lives in the sink, so any number of upstream retries converge to one row; no in-flight dedup state needed | Only works if the sink supports a native keyed upsert; does not prevent redundant processing work before the write, just its effect |
| Watermark/window compaction (buffer events per window, drop or merge repeats of the same key inside the window once the watermark passes, then finalize) | Bounds dedup state to "current watermark window," giving a hard memory ceiling independent of total event volume | Introduces latency (must wait for the watermark before finalizing) and cannot catch a duplicate that arrives after the window has already closed and been forgotten |
Worked example
A user-events stream runs at 20,000 events/sec, and the pipeline tolerates events arriving up to 10 minutes late (the watermark lag). Using consumer-side dedupe with a hash set of event_id keyed per 10-minute window:
At a 36-byte UUID string per event_id (or 16 bytes if stored as a raw UUID, plus hash-set overhead, call it roughly 50 bytes per entry with typical hash-set bookkeeping overhead):
If two windows must be open concurrently (the current one plus a grace-period window for late arrivals), that is roughly 1.1 GiB of dedup state, which is a real, plannable memory budget, not an afterthought. This is exactly why the retention window (the watermark lag, 10 minutes here) is a deliberate engineering choice: doubling it to 20 minutes doubles this number to roughly 2.2 GiB in-flight, while halving it to 5 minutes halves it, at the cost of dropping legitimately late (but real) events as unrecoverable duplicates-of-nothing once the window closes. Consumer-side dedup stores and compacted topics map directly onto this row: a log-compacted topic keyed by event_id is a durable, disk-backed version of the same consumer-side dedup state, trading the in-memory 572 MiB budget above for compaction-cycle latency and broker-side storage, at higher throughput headroom and lower operational risk of losing state on a consumer restart.
Trade-offs and pitfalls
- Layering approaches is normal. Producer-side dedupe removes the cheap, common case (retried sends) before it costs any consumer-side work; consumer-side or sink-side dedupe is still needed as the backstop for the cases producer-side dedupe cannot see (replays, multiple producers, cross-pipeline joins).
- Common mistake: deduplicating on the wrong key. Using a payload hash instead of
event_idtreats two textually-identical-but-distinct real events (e.g., a user clicking the same button twice, one second apart) as duplicates, silently dropping real data. The dedup key must identify the logical event, not just match its content. - Common mistake: forgetting that offsets reset on partition reassignment. If consumer group rebalancing moves a partition to a new consumer instance, dedup state that lived only in that consumer's local memory is lost, and a config that resumes "from committed offset" can redeliver a range the old instance already deduplicated. Externalizing dedup state (a shared store or the sink's own upsert) survives rebalances; purely local in-memory state does not.
- Common mistake: sizing retention from "how long till I forget" instead of "how late can a real duplicate legitimately arrive." The watermark should be derived from measured upstream latency distributions (e.g. P99 producer-to-broker delay), not picked as a round number.
Design an automated reconciliation pipeline that detects and repairs divergence between an authoritative source of record and its derived read views or replicas (search indexes, caches, a materialized streaming view, or independent downstream systems such as a CRM, payments gateway, and ERP at 100M records/day). Include detection heuristics (checksums, sampling, row counts, LSN alignment, key-level diffs), safe automated repair actions (targeted replays, upserts), audit logging for each repair, safe throttling, human-in-the-loop approval for destructive fixes, and how you'd surface prioritized mismatches for remediation with owner assignment.
Sample Answer
Direct answer
An automated reconciliation pipeline detecting and repairing divergence between a source of record and its derived views needs a detection layer that is CHEAP first, EXPENSIVE only when needed (checksums and row counts as a fast first pass, key-level diffs only on the ranges those flag as suspicious), a repair layer that is conservative by default (safe, idempotent, targeted replays and upserts for well-understood divergence, never a blind full-resync), and a governance layer (audit logging, throttling, and human-in-the-loop approval) that scales the AUTOMATION to match the RISK of the specific fix, not a single uniform automation policy across a heterogeneous, cross-business set of downstream systems.
Structured elaboration
Detection heuristics, layered by cost. (1) Row counts per partition/time-window: cheapest, catches gross divergence (a missing batch) immediately. (2) Checksums (a hash of a partition's content, or an aggregate like a sum/count over key fields): still cheap, catches content divergence a row count alone would miss (same row count, wrong values). (3) LSN/offset alignment: for a replica or view fed by CDC, compares the replica's last-applied LSN against the source's current LSN, directly measuring lag/gap rather than inferring it from content. (4) Key-level diffs: expensive (a full row-by-row comparison), reserved for ranges flagged suspicious by the cheaper checks above, never run as a blanket full-table scan at 100M records/day scale.
Safe automated repair actions. For a range confirmed divergent by a key-level diff: a TARGETED replay (only the specific keys/range identified) using idempotent UPSERTS, so repair is safe to re-run if it is itself interrupted. Repair is never a blind full-resync of the entire view, both for cost (100M records/day makes a full resync expensive) and for risk (a full resync can itself introduce NEW divergence if it races against concurrent live writes).
Audit logging for each repair. Every repair action logs: what was detected as divergent (source and target values, or the specific checksum mismatch), what action was taken (which keys were replayed/upserted), when, and by what triggered it (automated threshold, or a human approval). This is what makes the reconciliation system itself auditable and debuggable, since a system silently self-healing without a trail is nearly as concerning as the divergence it is fixing.
Safe throttling. Repair actions must not themselves become a new source of load-related incidents; throttle the RATE of repair writes (a token-bucket or dynamic backoff against the target's own capacity) against the target system's normal write budget, especially for a cross-business-system target (a CRM, a payments gateway, an ERP) where the reconciliation pipeline is a GUEST on infrastructure it does not own and must not degrade for that system's own primary traffic.
Human-in-the-loop approval for destructive fixes. A repair that OVERWRITES existing target data (versus one that only fills in missing rows) is categorically riskier, since an incorrect repair here destroys a previously-correct value, not just fails to add a missing one. The design should gate any repair classified as destructive (an update or delete, not just an insert) behind explicit human approval, at least until the specific repair pattern has enough track record to be trusted for auto-approval, an evolving, not fixed, boundary.
Surfacing prioritized mismatches with owner assignment. Not every detected divergence should trigger automated repair; some should surface to a dashboard/ticket queue, prioritized by IMPACT (records affected x downstream criticality, e.g., a payments-gateway mismatch outranks a marginally-stale cache entry) and routed to the OWNING team for that specific downstream system (a CRM mismatch to the CRM team, a payments mismatch to the payments team), since the reconciliation pipeline's own operators are rarely the right people to judge every downstream system's specific correctness requirements.
Worked example
At 100M records/day across a source-of-record database and three downstream systems (a search index, a CRM, a payments gateway), the cheap layer-1/2 checks (row counts and checksums, run hourly per partition) catch 99.9% of days with zero flagged divergence. On one day, the CRM's checksum for a specific customer-segment partition mismatches. Layer-4 key-level diff runs ONLY on that flagged partition (not the full 100M/day dataset), identifying 340 specific customer records with stale CRM data (a sync job silently failed for that segment 6 hours earlier). Classification: this is a MISSING-UPDATE case (the CRM has OLD but not WRONG data, an insert-style upsert corrects it, non-destructive), so it qualifies for automated repair: a targeted, idempotent upsert of exactly those 340 records, throttled to a rate the CRM's own API rate limits comfortably accommodate, logged with full before/after values for each of the 340 records. The payments gateway, checked the same day, shows zero divergence; no action, no wasted repair cycles on a system that is already consistent.
Trade-offs and pitfalls
- Common mistake: running key-level diffs as the FIRST and only detection layer, "to be thorough." At 100M records/day across multiple downstream systems, this is prohibitively expensive to run continuously; the layered cost structure (cheap checks first, expensive checks only on flagged ranges) is what makes continuous reconciliation at this scale affordable at all.
- Common mistake: uniform automation policy across destructive and non-destructive repairs. As the worked example's insert-only CRM case shows, automating a safe, additive fix is a very different risk profile from automating an overwrite/delete; a single "auto-repair: yes/no" toggle for the whole pipeline either over-automates the risky cases or under-automates the safe, high-volume ones.
- Owner assignment matters as much as detection. A reconciliation pipeline that detects divergence perfectly but routes every alert to one central team (rather than the actual owning team per downstream system) creates a bottleneck and a team without the domain context to correctly judge many of the flagged mismatches.
- This design's throttling discipline exists specifically because the reconciliation pipeline is often a GUEST on infrastructure it does not own. Forgetting this (running repair writes at whatever rate is convenient for the reconciliation job itself) risks the reconciliation system becoming the CAUSE of an incident on a downstream system it was only supposed to be fixing.
Architect a transactional outbox pattern for reliably publishing domain events when committing a write to the primary database. Include the outbox table schema, the reader design (and how you'd compare a polling reader against a change-data-capture-based reader), ordering guarantees, idempotency handling on the consumer side, and how you would scale the reader for high throughput.
Sample Answer
Direct answer: A production-grade transactional outbox service has three pieces: the application's database with an outbox table written in the same local transaction as the business change, a relay/reader that publishes unpublished rows to the broker (polling or CDC-based, CDC meaning change-data-capture), and enough retry/dedup discipline on both sides that the whole thing delivers at-least-once without ever silently losing an event.
Structured elaboration
Outbox table schema. At minimum: id (primary key, also usable as an idempotency/dedup token), aggregate_id (what business entity this event is about, often used as the broker partition key to preserve per-entity ordering), event_type, payload (serialized event body), created_at, and published (boolean, or a published_at timestamp, null until published). An index on (published, created_at) supports the "give me the oldest unpublished rows" query the reader needs.
Reader design: polling vs streaming. A polling reader periodically queries for published = false rows, simple to build and reason about, but adds latency bounded by the poll interval and puts a steady, small query load on the database. A CDC-based (streaming) reader instead taps the database's write-ahead log or replication stream (e.g. via Debezium) to be notified of new outbox rows as they're written, giving near-real-time delivery with no polling load, at the cost of running and operating CDC infrastructure and a slightly more complex failure story (the CDC connector itself can fall behind or need to resume from a checkpoint).
Ordering guarantees. If per-entity ordering matters (e.g. all events for order 501 must be delivered in the order they were created), the reader must publish using aggregate_id as the partition/routing key, so a partitioned broker (like Kafka) preserves order within that key even while allowing parallelism across different keys. Global ordering across all entities is usually not worth the throughput cost and isn't needed by most consumers.
Idempotency handling on the consumer side. Since the relay guarantees only at-least-once delivery, every event's payload includes a stable ID (the outbox row's id, or a domain-level event ID) that consumers use to deduplicate, typically via a small "seen event IDs" store with a bounded retention window matched to how long redelivery could realistically be delayed.
Scaling the reader for high throughput. A single polling reader eventually becomes a bottleneck; horizontal scaling requires either sharding the outbox table (e.g. by a hash of aggregate_id) with one reader instance per shard, or, for a CDC-based reader, letting the CDC connector's own partitioning handle parallelism. Batching reads and publishes (rather than one row per query/publish round-trip) is usually the first and cheapest throughput lever before reaching for sharding.
Worked example. An orders platform doing 2,000 writes/sec needs its outbox reader to keep pace. A single polling reader batching 200 rows per poll every 200ms caps out at 200 / 0.2s = 1,000 rows/sec, below the required rate regardless of how the rest of the system is tuned. Moving to a CDC-based reader (Debezium tailing the outbox table's WAL, write-ahead log) removes the poll-interval ceiling entirely, since new rows are picked up as they're written to the log rather than on a fixed cadence, at the cost of adding a Kafka Connect cluster and its own on-call burden that didn't exist with the simpler polling design; the actual sustained throughput and delivery latency the CDC path achieves would need to be measured against the real database's write-ahead log volume and Kafka Connect's own configured parallelism, not assumed from the pattern alone.
Trade-offs and pitfalls. Teams often under-invest in the outbox table's own cleanup: published rows accumulate forever unless there's a retention/archival job, which eventually degrades both the outbox query performance and, for CDC-based readers, the size of the write-ahead log the CDC connector has to process on any resume-from-checkpoint scenario.
Unlock Full Question Bank
Get access to all Data Consistency and Distributed Transactions interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.