Distributed Systems Fundamentals Questions
Core theory that underpins any multi-node system: the CAP and PACELC theorems, consistency models (strong, causal, eventual), partitioning, replication, and the fundamental tradeoffs between latency, availability, and consistency. Covers how network partitions, clock skew, and partial failure change the reasoning compared to single-node systems. This is the vocabulary layer every distributed design question builds on.
Design an anti-entropy mechanism to reconcile replicas of a large key-value store that have drifted apart. Compare comparing full Merkle trees, range-based comparison, and delta-based synchronization, and discuss the bandwidth and computation cost of each as the dataset grows into the terabytes.
Sample Answer
Direct answer
Anti-entropy is the background process that repairs replicas which have drifted apart by comparing what each replica actually holds and shipping only the differences. Full Merkle trees, range-based comparison, and delta-based synchronization all solve this, but they trade CPU and memory (building or maintaining a comparison structure) against network bytes (what actually gets transferred) in different proportions, and at terabyte scale that trade-off is what decides which one wins.
Full Merkle trees
A Merkle tree is a hash tree: each leaf is the hash of a key-range's contents (or a single key's version), and each internal node is the hash of its children. Two replicas compare root hashes first; if they match, the whole subtree underneath is known to agree and no further comparison is needed; if they differ, both sides recurse into whichever child subtrees disagree, pruning everything else. This localizes a small number of actually-differing keys very cheaply in network terms, but building the tree from scratch means hashing the entire dataset, which for a terabyte-scale store is a full scan whose CPU and I/O cost is proportional to the dataset size, not to how much has actually drifted.
Range-based comparison
Instead of a tree, the keyspace is partitioned into fixed or size-based ranges up front, and each replica computes one summary per range (a checksum, a record count, a max version) and exchanges those directly. A mismatched range is either subdivided further or transferred whole. This skips the recursive tree bookkeeping, at the cost of coarser precision: if a single key differs inside a large range, the whole range still has to move (or be subdivided) rather than just that one key.
Delta-based synchronization
Each write is stamped with a monotonically increasing per-replica version number, and instead of building any hash structure at all, one replica asks the other for everything with a version greater than its own last-synced position (tailing an operation log). This is by far the cheapest in both CPU and network when it applies, because it transfers exactly the changed records and nothing else, but its correctness depends entirely on both sides retaining a comparable version log; if the divergence is older than the retained log window, delta sync cannot answer the request and the system must fall back to a full Merkle or range comparison instead.
Comparison at terabyte scale
| Approach | CPU/memory to prepare | Network when divergence is small | Depends on |
|---|---|---|---|
| Full Merkle tree | High: hashing the entire dataset to build every level | Low: only mismatched leaves transfer | Nothing external; rebuilt purely from current data |
| Range-based comparison | Low to moderate: one checksum per range, no tree | Moderate: an entire mismatched range moves even for one differing key inside it | Nothing external, same as Merkle but coarser |
| Delta-based sync | Very low: no structure built, just an op-log tail | Very low: transfers exactly the changed records | Requires both replicas to retain a comparable version/op log |
Building a full Merkle tree over a terabyte dataset from scratch on every anti-entropy pass is prohibitively expensive; production systems maintain it incrementally as writes happen rather than rebuilding it each run. Range-based comparison avoids that recursive bookkeeping at the cost of transferring more bytes per mismatch, which can be mitigated with adaptive range sizing (smaller ranges where churn is high, larger ranges where data is cold). Delta-based sync is cheapest whenever the version log covers the actual gap, but has an unbounded-retention cost if you want it to always apply.
Recommendation for a large, skewed keyspace: use adaptive, size- or churn-based ranges as the primary mechanism (isolating hot keys into small ranges and cold data into large ones), maintain shallow per-range Merkle hashes to localize differences quickly within a cold range, and prefer delta-based sync wherever the version log still covers the gap, falling back to the range/Merkle comparison only once the log window has been exceeded.
graph TD
RootA[Root hash A] --> BL[Branch Left]
RootA --> BR[Branch Right]
BL --> L1[Leaf: keys 1-1000]
BL --> L2[Leaf: keys 1001-2000]
BR --> L3[Leaf: keys 2001-3000]
BR --> L4[Leaf: keys 3001-4000]
Read repair: fixing staleness at read time
Anti-entropy runs in the background regardless of what's being read right now; read repair instead fixes staleness the moment a client happens to read a key, without adding latency to that client's own request. When a quorum read is served from multiple replicas, the coordinator compares the versions it gets back: suppose replica R1 returns (value=v2, version=7), R2 returns (value=v1, version=5), and R3 returns (value=v2, version=7). The coordinator returns v2 (the version two of three replicas agree on) to the client immediately, and separately, off the client's response path, pushes a repair write of (K, v2, version=7) to R2 in the background. Because this only happens for keys someone actually reads, read repair does nothing for cold keys nobody queries, so background anti-entropy is still needed as the backstop for data that is never read.
Hinted handoff: staying writable through a node outage
When a target replica for a key is unreachable at write time, for example replica R2 is down, a Dynamo-style store stays always-writable by handing that write to a different, healthy node (a hint holder, say R4) along with a hint recording who the write actually belongs to. R4 stores the write plus the hint. Concretely: the replica set for key K is {R1, R2, R3}; R2 is down; a write W(K=v3) arrives; the coordinator writes directly to R1 and R3, and since R2 is unreachable, hands the write to R4 with hint={target: R2, key: K, value: v3}. R2 recovers ten minutes later; R4's health check or gossip layer learns R2 is back; R4 forwards W(K=v3) to R2 and deletes its own hint copy. All three original replicas now hold v3.
Trade-offs & pitfalls
Hinted handoff is a latency and availability optimization, not a substitute for anti-entropy: if the hint holder itself crashes before delivering the handoff, that write is only recoverable through whatever the normal replica quorum still retains, so anti-entropy (or read repair) remains the backstop even when hinted handoff is in use. Read repair only heals keys that get read, so a design that relies on it exclusively can leave cold data permanently drifted. Over-aggressive range subdivision in range-based sync adds coordination overhead without meaningfully reducing transferred bytes unless the workload's skew actually justifies the extra ranges.
What is PACELC, and how does it extend the CAP theorem? Walk through an example decision where PACELC's latency-versus-consistency trade-off matters even when there is no active network partition.
Sample Answer
Direct answer
PACELC, short for "if Partition, Availability vs. Consistency; Else, Latency vs. Consistency", says that CAP's dilemma, choose Consistency or Availability when a network Partition is happening, is only half the story. Even when there is no partition at all, a system still has to choose between Latency and Consistency for every write it replicates, because making a write durable on every replica before acknowledging it takes longer than acknowledging it once it's durable on a single node. PACELC packages this as: if Partition occurs, trade off Availability against Consistency (exactly what CAP already says); Else, meaning no partition, trade off Latency against Consistency.
Restating CAP precisely first
CAP says that during an actual network partition, a distributed system can guarantee only one of Consistency (every read sees the latest completed write) or Availability (every request gets a non-error response) for the nodes on either side of the split, not both. A common misreading treats CAP as "pick two of three, always"; it isn't. CAP's teeth are specifically about behavior during a partition. Most systems are both consistent and available almost all of the time, precisely because a true network partition is a rare event relative to total uptime, not something happening continuously.
flowchart TD
Start[Write occurs] --> P{Partition active?}
P -->|Yes| AC[Choose Availability or Consistency]
P -->|No| LC[Choose Latency or Consistency]
What PACELC adds
PACELC names the trade-off CAP is silent about: during normal operation, with no partition, you still choose between Latency (L) and Consistency (C), because synchronous replication that waits for a majority of replicas costs a round trip before it can acknowledge a write, while asynchronous or single-node-acknowledged replication returns faster but risks a reader seeing stale data, or the acknowledged write being lost outright if that one node fails before it propagates. Systems are commonly labeled by both branches together, for example PA/EL (favor Availability under partition, favor Latency otherwise, the Cassandra/Dynamo-style default) or PC/EC (favor Consistency in both cases, the HBase-style default).
Worked example: a decision with no partition occurring
A write to a piece of user data must be replicated to three nodes: R1 in the local region, and R2, R3 in two remote regions. All three are reachable; no partition is happening anywhere in this example.
- Favor consistency (the "C" side of the Else branch): the write path waits for acknowledgment from a majority, at least two of the three replicas, say R1 and R2, before returning success to the caller. Any subsequent read from a majority quorum is now guaranteed to see this write. Cost: the caller's write waits on the round trip to R2, a remote replica, even though R1, the local one, already has it durably.
- Favor latency (the "L" side of the Else branch): the write path acknowledges as soon as R1 has it durably, and replicates to R2 and R3 asynchronously in the background. Cost: the caller gets a fast, local acknowledgment, but a read served from R2 immediately afterward, before the async replication catches up, will not see the write yet. If R1 crashes before that background replication completes, the already-acknowledged write can be lost entirely, with zero partition ever occurring.
This decision, wait for two of three versus acknowledge on one, is made on every single write regardless of whether any partition is happening, which is exactly the trade-off PACELC's Else branch names and CAP alone has nothing to say about, since CAP only speaks to a system that is not fully connected.
Trade-offs & pitfalls
A common misconception is treating a database's PACELC label as a fixed law of the software rather than a description of its typical default: most systems let you tune the replication wait per request (via quorum size), so "Cassandra is PA/EL" describes its usual configuration, not something it's incapable of changing. It's also easy to blur this Else-branch trade-off with an availability discussion; in the worked example above, no node was ever unreachable, so the trade being made is purely about how long the write path waits before acknowledging, not about surviving an outage, which is a separate concern belonging to the partition branch of the theorem.
Explain the difference between at-least-once, at-most-once, and exactly-once delivery semantics in a streaming system. For each, describe a concrete scenario where you'd end up with a duplicate or a lost record, and what it actually takes at the consumer (idempotent processing, a dedup window, transactional writes) to get exactly-once behavior in practice.
Sample Answer
Direct answer
These three terms describe how many times a record's effect can show up downstream, not how many times it crosses the wire. At-least-once guarantees nothing is silently dropped but tolerates re-delivery, so duplicates are possible. At-most-once guarantees no duplicates but tolerates silent loss. Exactly-once means the record's effect appears exactly once, even though delivery itself is usually still at-least-once under the hood; the "exactly" part is enforced by deduplication or a transactional write, not by literally never redelivering anything.
At-least-once
Mechanism: the consumer commits its read offset only after it has finished processing a record.
Scenario producing a duplicate: a consumer reads offset 100 from a partition and processes it, say incrementing an inventory counter, but crashes before committing that offset. On restart it resumes from the last committed offset, 99, and re-reads and reprocesses offset 100, incrementing the counter a second time. The counter's effect happened twice for one logical record.
At-most-once
Mechanism: the consumer commits its read offset before processing the record.
Scenario producing a loss: a consumer commits offset 100 immediately on receipt, then crashes while processing that record. On restart it resumes from offset 100 onward, since that offset is already committed, so the record at offset 100 is never processed. This is the mirror image of the at-least-once bug: it's the same commit-versus-process ordering, flipped.
Exactly-once: what it actually takes at the consumer
- Idempotent processing: design the effect so applying it twice produces the same result as applying it once, for example replacing "increment counter by 1" with "set counter to max(current, computed value)", or recording each processed key in a table with a uniqueness constraint so a repeat attempt is rejected rather than reapplied.
- Dedup window: a bounded structure, such as a set of recently-processed record ids, that the consumer checks before applying an effect. It must be sized to cover the maximum plausible redelivery delay; if consumer restarts are the main cause of redelivery and offsets commit every 30 seconds, a window covering the last few minutes of ids is enough, but an outage longer than the window falls back on whatever uniqueness constraint the underlying store provides.
- Transactional writes: commit the output write and the offset advance as a single atomic operation, so a crash between "wrote output" and "committed offset" cannot happen. Kafka's transactional producer does this across topic-partitions; a database sink can do the same by writing the output row and a processed-offsets row inside one database transaction.
Worked example: exactly-once via a transactional write
Consumer is at offset 100. It opens a transaction, upserts the inventory row (an idempotent write), writes offset=101 to an offsets table, and commits the transaction atomically.
- If the consumer crashes before the commit: nothing happened; the output was never applied and the offset was never advanced. Re-reading offset 100 next time reproduces the exact same atomic attempt, with no partial effect ever visible in between.
- If it crashes after the commit: offset 101 is already recorded, so the consumer will not re-read offset 100 on restart.
There is no window in which the output exists but the offset doesn't, or vice versa, because both changes are part of one transaction.
Practical guidance
| Semantic | Typical mechanism | Cost | Good fit |
|---|---|---|---|
| At-least-once | Commit offset after processing | Low; occasional downstream duplicates | Most ETL, where the sink can dedup or is naturally idempotent (an upsert) |
| At-most-once | Commit offset before processing | Low; occasional silent loss | Only where loss is acceptable, e.g. sampled telemetry |
| Exactly-once | Idempotent writes, dedup window, or transactional commit of output+offset | Higher; coordination and lookups add latency | Financial correctness, exact counts |
Trade-offs & pitfalls
Exactly-once adds real coordination cost (transactions, dedup lookups), so its throughput and latency are worse than plain at-least-once, which is why it's reserved for cases where correctness genuinely requires it rather than applied everywhere by default. A dedup window sized too small silently degrades to at-least-once during a long outage, without any error being raised. A common interview trap is conflating a broker-level exactly-once guarantee (Kafka's own transactions between its topics) with true end-to-end exactly-once: Kafka's guarantee stops at the Kafka cluster boundary, so if the final effect lands somewhere outside it, an external database or a third-party API, that external system still has to be transactional or idempotent for the guarantee to actually hold all the way through.
Explain how checkpointing works in a stateful stream-processing framework: how a barrier or snapshot marker flowing through the pipeline lets the system capture a consistent point-in-time state across many parallel operators, and how the system uses that checkpoint to restore and resume with exactly-once semantics after a failure.
Sample Answer
Direct answer
A checkpoint barrier is a special marker the coordinator injects into every source stream at a chosen moment. As it flows downstream mixed in with real data, each operator uses its arrival to mark a cut: everything on that input channel before the barrier belongs to checkpoint N, everything after belongs to checkpoint N+1. Once an operator has seen the barrier on all of its input channels, it takes a local snapshot of its own state and forwards the barrier onward. Because every operator's snapshot is cut at the same logical point in the data rather than the same wall-clock instant, the union of all local snapshots plus the recorded source read-positions forms one consistent global snapshot the whole job can be rewound to after a failure.
Barrier injection and alignment
The checkpoint coordinator periodically assigns an increasing checkpoint id and injects a barrier carrying that id into every source partition. Barriers travel with the data on each channel, in order, never overtaking a record. When an operator with multiple input channels receives the barrier on one channel before the others, it stops consuming further records on that channel and buffers them, while continuing to process the channels where the barrier hasn't arrived yet. This buffering-until-all-channels-caught-up step is called alignment; it guarantees the operator's eventual snapshot reflects exactly the same cut point on every input.
Local snapshot and coordinator commit
Once aligned, the operator snapshots its local state (for a keyed aggregation, the current value per key) to durable storage and forwards the barrier to its downstream operators. The coordinator marks a checkpoint complete only once every operator, all the way to the sinks, has acknowledged it, and only then persists the checkpoint's metadata as the new restore point.
Unaligned checkpoints
Alignment can add latency under backpressure or skew, since a fast channel has to wait on a slow one before the operator can snapshot. Unaligned checkpoints avoid this by not waiting at all: the framework snapshots the buffered in-flight records themselves as part of the checkpoint, alongside the operator's own state, trading more storage and I/O for lower checkpoint latency.
Worked example: barrier flow through a keyed aggregation
Job topology: Source -> Map -> KeyedSum -> Sink, with KeyedSum running as two parallel instances, A and B.
sequenceDiagram
participant Coord as Coordinator
participant A as KeyedSum A
participant B as KeyedSum B
participant Sink
Coord->>A: barrier(42) on P0
Coord->>A: barrier(42) on P1
A->>A: snapshot state
A->>Sink: forward barrier(42)
Coord->>B: barrier(42) on P0
Coord->>B: barrier(42) on P1
B->>B: snapshot state
B->>Sink: forward barrier(42)
Sink->>Coord: ack checkpoint 42
- Coordinator starts checkpoint 42 and injects
barrier(42)into the source's two partitions, P0 at read-offset 1000 and P1 at read-offset 850. - Instance A receives input from both P0 and P1 after the shuffle (the keyed redistribution that routes every record for a given key consistently to the same parallel instance).
barrier(42)arrives on A's P0 channel first: A stops consuming new P0 records and buffers them (alignment), while continuing to process P1 records normally, since P1's barrier hasn't arrived yet. barrier(42)arrives on A's P1 channel. A has now seen the barrier on every input channel, so it snapshots its local running sums, say{key=X: 17, key=Y: 42}, to durable storage, forwardsbarrier(42)downstream to the Sink, and unblocks the buffered P0 records, which now belong to checkpoint 43.- Instance B does the same independently for its own keys.
- The Sink receives
barrier(42)from both A and B, snapshots (or, if it's a transactional sink, pre-commits) its own pending output, and acknowledges checkpoint 42 to the coordinator. - Once the coordinator has acknowledgements from the source (offsets P0=1000, P1=850), A, B, and the Sink, checkpoint 42 is marked complete and persisted.
- If the job then crashes after checkpoint 42 completed but before checkpoint 43 finished, restart loads checkpoint 42: sources reset to offsets P0=1000/P1=850, A and B restore their snapshotted key-sums, and the Sink either commits its pre-committed checkpoint-42 output or relies on idempotent writes if it isn't transactional. Processing then resumes from exactly those offsets, so no record before the barrier is reprocessed and no record after it is lost.
End-to-end exactly-once needs the sink to participate
Internal exactly-once state is only as strong as what happens at the external sink. A transactional (two-phase commit, 2PC) sink pattern treats each checkpoint as a transaction boundary: during the checkpoint, the sink prepares and flushes its output but does not commit; once the coordinator marks the checkpoint complete, it tells the sink to commit. On failure, any uncommitted transaction is aborted, so restored state and committed output stay consistent. If a sink can't participate in a transaction this way (for example, one that only supports single-item idempotent writes rather than a cross-partition transaction), the fallback is idempotent writes keyed by (checkpoint_id, record_id), so the same output re-emitted after restoring from checkpoint 42 doesn't double-apply. The same barrier/snapshot mechanism underlies this regardless of what the job is computing: a change-data-capture (CDC) ingestion pipeline, a feature-computation job for machine learning, or an ordinary aggregation are all just other kinds of stateful stream jobs from the checkpoint coordinator's point of view.
Trade-offs & pitfalls
| Aligned checkpoints | Unaligned checkpoints | |
|---|---|---|
| Latency under backpressure/skew | Can stall waiting for the slowest channel | Avoids the wait entirely |
| Storage/I/O overhead | Lower (only operator state is stored) | Higher (in-flight buffered records are stored too) |
| Reasoning simplicity | Simple, single well-defined cut point | More moving parts to restore correctly |
Rescaling (changing parallelism) needs a savepoint, a user-triggered durable checkpoint, plus a defined remapping of keyed state across the new number of instances. The most common pitfall is assuming "exactly-once" automatically covers the whole pipeline: if the sink isn't transactional or idempotent, restoring from a checkpoint after a crash can re-emit output that was already delivered before the crash, turning exactly-once internal state into at-least-once external effects.
What is leader election in a distributed system, and why do some systems need exactly one leader rather than operating leaderlessly? At a high level, contrast the Bully algorithm's approach with a Raft-style election in terms of how each detects a missing leader and picks a replacement.
Sample Answer
Direct Answer
Leader election is the process by which nodes in a distributed system agree on exactly one of themselves to perform a centralizing job, such as serializing writes to a replicated log, granting a lock, or coordinating a membership change, so the system has a single point of authority for that job instead of multiple nodes potentially making conflicting decisions at once. Some systems need exactly one leader because certain coordination problems, like ordering and mutual exclusion, become far simpler with a single serializer; leaderless designs avoid that single point but have to solve conflicts some other way.
Why Some Systems Insist on One Leader
Turning "every node must agree with every other node" into "every node defers to this one node" collapses a lot of coordination overhead: instead of running an agreement protocol on every single write, only the leader needs to decide the order, and everyone else just follows. The cost is that the leader becomes both a bottleneck and a single thing that must be replaced correctly if it fails, which is exactly what leader election solves.
Leaderless systems (gossip-based membership, quorum reads and writes without a fixed leader) avoid that bottleneck and can keep operating on both sides of some partitions, but since there's no natural serializer, they need a different way to resolve conflicting writes, such as version-based reconciliation or last-write-wins policies, and they give up the simplicity of having one place to look for the current order of events.
Bully vs. Raft-Style Election
| Bully algorithm | Raft-style election | |
|---|---|---|
| Detecting a missing leader | A node notices it's stopped hearing from the leader (a missed heartbeat) | A follower notices it's stopped hearing from the leader within a randomized timeout window |
| Who is allowed to become leader | Deterministic: always the highest-ID node still alive | Whichever candidate collects votes from a majority of the cluster first for that term, and only if its log is at least as up to date as a majority's |
| How the replacement is chosen | The node that detects the failure asks every higher-ID node whether it's alive; if none respond, it declares itself leader and tells everyone lower | A candidate increments a term counter, votes for itself, and requests votes from peers; it becomes leader once a majority grants a vote for that term |
| Handling simultaneous detection | Not explicitly modeled; assumes fairly reliable, timely messaging, so races between multiple simultaneous detectors can produce extra election rounds | Explicitly handled: randomized timeouts make simultaneous candidacies unlikely, and if a vote does split, the term simply increments and another round runs |
A Worked Trace of Each
Raft-style, 5 nodes (N1 to N5), N1 is the current leader in term 3. N1 crashes. N3's election timeout fires first: N3 becomes a candidate, increments the term to 4, votes for itself (1 vote), and sends a vote request to N2, N4, and N5. N2 and N4 haven't voted in term 4 yet and grant their votes. N3 now has 3 votes (itself, N2, N4) out of 5 nodes, which is a majority, so N3 becomes the leader for term 4 without needing N5's response at all.
Bully algorithm, 5 nodes ranked by ID (N1=1 lowest through N5=5 highest), N5 is the current leader. N5 crashes. N2 notices its heartbeat check to N5 has timed out and starts an election by messaging every higher-ID node: N3, N4, N5. N3 and N4 respond that they're still around and each, per the algorithm, starts messaging anyone higher than themselves; N4 messages N5, gets no response since N5 is dead, gets no response from anyone higher, and so declares itself leader, broadcasting the result to N1, N2, and N3. N4, the highest surviving ID, is the new leader.
Trade-offs and Pitfalls
- The Bully algorithm implicitly assumes a fairly synchronous network with bounded, predictable message delay. If messages are merely slow rather than lost, you can get a wrong or duplicate leader declared for a short window, since the algorithm has no built-in way to say a later message should override an earlier one. Raft's term numbers solve this directly: any node that sees a higher term than its own always steps down, so even a slow, still-alive old leader will demote itself once it observes a message carrying a later term.
- Leader election by itself does not guarantee the correctness of the data the new leader serves. Raft additionally requires a candidate's log to be at least as up to date as a majority of the cluster before it can win an election; without that check, you could elect a leader that's missing already-committed writes.
- Don't conflate leader election as a consensus-protocol mechanism with using leader election purely to decide which region should serve traffic during a disaster-recovery failover; the algorithmic problem of who gets to be the single serializer, and how a replacement is safely chosen, is the same shape, but the operational failover decision of whether and where to fail over is a different question with its own trade-offs.
Unlock Full Question Bank
Get access to all 33 Distributed Systems Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.