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.
Implement (pseudocode is fine) the leader election portion of Raft: the election timeout, candidate state, and vote counting. Explain how the algorithm avoids split votes, and discuss the trade-off between a short and a long election timeout.
Sample Answer
Raft's leader election works by giving every follower a randomized election timeout; whichever follower's timeout fires first becomes a candidate, bumps the term number, votes for itself, and asks every other node for its vote. Randomizing the timeout is what keeps split votes rare: it makes it unlikely that two followers time out at nearly the same instant and both start competing candidacies in the same term. A short timeout detects a dead leader faster but risks more split votes and RPC churn; a long timeout is calmer but leaves the cluster leaderless longer after a real crash.
Approach
Implement the state machine directly: a follower's only action is to reset its timer whenever it hears from a leader or grants a vote. When the timer fires with no such contact, it becomes a candidate, increments its term, votes for itself, and fires RequestVote RPCs at every peer in parallel. It counts granted votes as they arrive; on a majority, it becomes leader. Any RPC response or incoming request carrying a higher term makes it step down to follower immediately; this term-monotonicity is what prevents two nodes from believing they are both leader for the same term.
type Server struct {
mu sync.Mutex
id int
peers []int
currentTerm int
votedFor *int
state string // "follower", "candidate", "leader"
votes int
electionTimer *Timer
}
func (s *Server) onElectionTimeout() {
s.mu.Lock()
defer s.mu.Unlock()
if s.state == "leader" {
return // leaders don't run elections; they send heartbeats instead
}
s.startElectionLocked()
}
func (s *Server) startElectionLocked() {
s.state = "candidate"
s.currentTerm++
s.votedFor = &s.id
s.votes = 1 // vote for self
term := s.currentTerm
s.resetElectionTimer()
for _, peer := range s.peers {
go func(peer int) {
resp := sendRequestVote(peer, s.id, term, s.lastLogIndex(), s.lastLogTerm())
s.mu.Lock()
defer s.mu.Unlock()
if resp.Term > s.currentTerm {
s.currentTerm = resp.Term
s.becomeFollowerLocked()
return
}
if s.state != "candidate" || term != s.currentTerm {
return // stale response from a prior term, or we already moved on
}
if resp.VoteGranted {
s.votes++
if s.votes > (len(s.peers)+1)/2 {
s.becomeLeaderLocked()
}
}
}(peer)
}
}
func (s *Server) resetElectionTimer() {
d := randomDuration(electionTimeoutMin, electionTimeoutMax)
s.electionTimer.Reset(d)
}
func (s *Server) onAppendEntries(args AppendEntriesArgs) AppendEntriesReply {
s.mu.Lock()
defer s.mu.Unlock()
if args.Term >= s.currentTerm {
s.currentTerm = args.Term
s.becomeFollowerLocked()
s.resetElectionTimer() // heard from a valid leader, don't start a new election
}
// log-matching and append logic omitted here
return AppendEntriesReply{Term: s.currentTerm}
}
Key points
- Persist currentTerm and votedFor to stable storage before replying to any RPC. A node that crashes and restarts without doing this could grant a second vote in a term it already voted in, which is a real safety violation, not just a liveness inconvenience.
- A candidate only votes for itself and only requests votes once it becomes a candidate; a follower that already voted for someone else this term must refuse any other RequestVote for that same term.
- Majority is computed against the full cluster size n, including the leader itself, not just the peers list:
majority=⌊n/2⌋+1
Complexity
- Message complexity: one election attempt sends O(n) RequestVote RPCs, one per peer, linear in cluster size per attempt.
- State per node is O(1) beyond the log itself: a handful of integers and a timer.
- The number of election attempts before success is not bounded in the worst case, repeated collisions are theoretically possible forever, but the randomized timeout range makes the expected number of retries small in practice, since each retry independently redraws a new random timeout, making the same two nodes colliding again increasingly unlikely round over round.
Worked example: split vote and recovery, printed trace
Three nodes N1, N2, N3, currently term 0, no leader. Each node draws its election timeout independently from the same range.
Case A, no collision, the common case: N2 draws the shortest timeout and fires first. It becomes a candidate for term 1, votes for itself, and sends RequestVote(term=1) to N1 and N3. Neither has timed out or voted this term, so both grant their vote. N2 now has 3 of 3 votes, itself plus two grants, exceeding the majority threshold of 2, so N2 becomes leader for term 1. N1 and N3 reset their timers on granting the vote, so neither starts its own candidacy.
Case B, a genuine split vote: suppose instead N1, N2, and N3 all draw timeouts close enough together that all three fire before any RequestVote arrives. Each becomes a candidate for term 1, votes for itself, and requests votes from the other two. Because each node already voted for itself in term 1 before any request from a peer arrived, each rejects the other two's requests, having already voted this term. No candidate reaches a majority: N1 has 1 vote, N2 has 1 vote, N3 has 1 vote. All three time out again and start a new election for term 2, each independently drawing a fresh random timeout. Because these new timeouts are drawn independently, the chance that all three collide again is much lower than the first time, and typically one of them fires meaningfully before the others and wins term 2 uncontested.
Edge cases
- A network partition splits the cluster into a majority side and a minority side: the minority side's nodes keep timing out and calling elections forever, incrementing the term each time, but can never reach a majority, so they correctly never elect a leader. This is deliberate: it is what prevents split-brain, at the cost of the minority side being unavailable for writes until the partition heals.
- A node that crashes and restarts must reload currentTerm and votedFor from stable storage before participating again; skipping this can let it vote twice in a term it already voted in before crashing.
- A slow node, a garbage-collection pause or a disk stall, is indistinguishable from a crashed node from its peers' point of view; both simply stop sending heartbeats, and the same election timeout mechanism reacts to both identically, which can trigger an unnecessary election when a node was merely paused, not dead.
- Election timeouts are purely local, measured intervals, a node's own clock counting elapsed time, so cross-machine clock skew, which matters a great deal for wall-clock timestamp ordering elsewhere in this topic, does not matter here.
Trade-off: short vs long election timeout
- A short timeout detects a genuinely dead leader faster, a shorter unavailability window, but increases both the chance of a split vote and the RPC and CPU overhead from repeated election attempts under network jitter.
- A long timeout keeps the cluster calmer, fewer accidental elections during transient network hiccups, at the direct cost of a longer window with no leader after a real crash, since followers simply wait longer before noticing.
- In practice the timeout range is chosen relative to the network's expected round-trip time: long enough that a heartbeat reliably beats the timeout under normal jitter, short enough that a real leader loss is noticed promptly. There is no universal constant; it has to be tuned to the deployment's actual network characteristics.
stateDiagram-v2
Follower --> Candidate: election timeout fires
Candidate --> Candidate: split vote, retry next term
Candidate --> Leader: receives majority of votes
Candidate --> Follower: sees higher term or valid leader
Leader --> Follower: discovers higher term
Design a CRDT suitable for a real-time collaborative text editor where multiple users can type and delete concurrently without a central lock. Describe the data structure, how concurrent operations from different users merge deterministically, and the practical cost (metadata growth, garbage collection of tombstones) of the approach.
Sample Answer
A text editor where users type and delete concurrently without a lock needs a sequence CRDT (a Conflict-free Replicated Data Type: a data structure whose merge operation is commutative, associative, and idempotent, so concurrent replicas always converge to the same state without coordination). Each character gets a globally unique, immutable identifier, deletions mark a tombstone instead of physically removing the character, and a deterministic tie-break rule orders characters that were inserted concurrently at the same position. The design pays for this with permanent per-character metadata and a garbage-collection problem for tombstones.
Data structure
- Represent the document as an ordered sequence of atoms:
{ id: (site, counter), char, prev_id, tombstone }. idis globally unique because it pairs a site identifier (one per editing client) with that site's own monotonically increasing counter.prev_idrecords which atom this one was inserted immediately after, at the moment of insertion. That is what preserves each user's actual intent (insert right after the character I was looking at), even if other edits land nearby before this one is delivered.
Concurrent insert resolution
- Insert(id, prev_id, char) is broadcast to every replica.
- When two inserts share the same prev_id, both intended the same insertion point, that shared prev_id is exactly what concurrency looks like here. A deterministic comparator orders competing children of the same prev_id by site identifier (higher-precedence site placed first), so every replica, regardless of arrival order, produces the same final sequence.
Deletion and tombstones
- Delete(id) sets tombstone=true on that atom. The atom stays in the structure, because its ordering role must persist: a later, concurrently-arriving insert may still reference it as prev_id and needs it to resolve correctly.
- A tombstoned atom cannot be physically removed until every replica has definitely applied it.
Garbage collection of tombstones
- Replicas exchange a version vector (one counter per site, the highest counter from that site each replica has durably applied) during anti-entropy (a periodic background exchange where replicas compare state and reconcile any differences, rather than waiting for a live update to arrive).
- The element-wise minimum across all replicas' version vectors is the causal stability frontier: any tombstone at or below that frontier has been seen everywhere and can be physically purged.
- Cost: computing and propagating that frontier needs periodic all-to-all or gossip-based exchange, and a replica that stays offline indefinitely blocks compaction for everyone unless it is explicitly evicted from the version-vector set.
Worked example: two concurrent inserts at the same position
Both replicas have already converged on a one-character document containing 'X', a single atom with id (A,1). Two users, on different replicas, both position their cursor right after 'X' at the same time:
- Site A's user types 'p': op1 = Insert(id=(A,2), prev=(A,1), char='p')
- Site B's user types 'q': op2 = Insert(id=(B,1), prev=(A,1), char='q')
Both operations reference prev=(A,1): that shared reference is the concurrency. The merge rule for atoms competing for the same prev is order competing children by site identifier, descending, so a child from site B is placed before a child from site A when both point at the same prev.
- At replica A: op1 applies locally first, giving 'Xp'. When op2 arrives, it is spliced into the children of (A,1) and re-sorted by the rule above, giving order [op2, op1], so the document becomes 'Xqp'.
- At replica B: op2 applies locally first, giving 'Xq'. When op1 arrives, the same re-sort rule applies, again giving [op2, op1], so the document becomes 'Xqp'.
Both replicas land on 'Xqp' even though they applied the two operations in opposite order. That is what merging deterministically means in practice: the comparator, not arrival order, decides the final sequence.
graph LR
X["X (id A,1)"] --> Q["q (id B,1)"]
Q --> P["p (id A,2)"]
Now say 'q' is later deleted by its author. Atom (B,1) is not removed, only flagged tombstone=true, so the document reads 'Xp', but the underlying structure still holds three atoms, two live and one tombstone, until compaction runs.
Trade-offs & pitfalls
- Metadata growth: every character carries an id pair, a prev pointer, and (once deleted) a tombstone bit; on a long-lived, heavily-edited document the tombstone count can exceed the live character count, so uncompacted storage is proportional to live plus deleted atoms rather than just live ones.
- The same observed-remove technique (adding creates a fresh tag, removing targets only the tags actually observed) applies directly to a shared wishlist service: adding an item is an add-tag, removing it is a remove-tag scoped to the tags a client has actually seen, and the tombstone-compaction and consistent-read story are identical to the text editor's, just at item granularity instead of character granularity.
- Formatting spans (bold, italic) and structural moves (relocate a paragraph) do not compose as cleanly as single-character insert and delete; a naive extension can lose the same intention-preservation guarantee, which is why production collaborative-editing CRDTs spend real engineering effort specifically on this.
- Common wrong turn: implementing deletion by removing the atom outright instead of tombstoning it. That breaks any concurrent insert whose prev_id pointed at the now-missing atom, since there is nothing left to splice after.
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.
Design a membership and failure-detection scheme for a cluster of several thousand nodes, where a fixed health-check threshold is too crude. Walk through how a Phi Accrual-style failure detector produces a continuous suspicion level instead of a binary up/down verdict, and why that matters at this scale.
Sample Answer
At a handful of nodes a fixed heartbeat timeout works fine: miss N beats, declare the node down. At several thousand nodes spread across racks and regions, the same fixed threshold produces both false positives (a node under scheduling pressure or behind a congested link gets marked down while still alive) and slow true detections (a threshold loose enough to avoid those false positives takes too long to catch a real failure), because network and scheduling jitter is not uniform across the cluster. A Phi Accrual failure detector replaces the single global timeout with a statistical model of each node's own recent heartbeat behavior, so the question becomes how improbable this silence is given what has actually been observed from that specific node, rather than whether more than T seconds have passed, and it outputs a continuously increasing suspicion level, phi, instead of a binary up-or-down verdict.
Membership and probing, before the suspicion model
- Partial views and gossip: each node keeps a small, mostly random subset of the membership rather than the full list, and periodically gossips membership updates and heartbeats to a few random peers, so state propagation stays cheap instead of all-to-all.
- Direct and indirect probing (SWIM-style; SWIM: a gossip-based membership protocol combining direct pings with an indirect fallback): a node pings a random peer directly, and if it gets no acknowledgment, asks a handful of other random members to ping that peer on its behalf, since one lossy path between two specific nodes should not be read as evidence the target itself is down.
- A minimal membership-manager state machine per monitored node: ALIVE, SUSPECT, DEAD. Failed direct-plus-indirect probes move a node from ALIVE to SUSPECT rather than straight to DEAD, and the suspicion is gossiped with an incarnation number, so a node that is actually alive can refute it by re-announcing itself with a higher incarnation before it is declared DEAD and dropped from membership.
From a binary probe result to a continuous suspicion level
Probing only tells you whether a heartbeat arrived, which is still binary. Phi accrual sits on top of that: instead of one global timeout, each node keeps a short sliding window of the actual inter-arrival times it has observed from a given peer, uses that history to estimate how spread out that peer's heartbeats normally are, and converts the elapsed time since the last heartbeat into a suspicion level using roughly:
ϕ(t)=−log10(Plater(t))where Plater(t) is the estimated probability, given that peer's own recent history, that a heartbeat still arrives more than t time units after the previous one. As t grows past what the peer's history says is normal, Plater(t) shrinks and phi grows smoothly and without bound, instead of snapping from 0 to 1 at one fixed cutoff.
Why this matters at thousands of nodes: a peer on a congested cross-region link naturally has wider jitter in its own history, so it takes a longer silence to reach the same phi value as a peer on a quiet local link, without anyone hand-tuning a per-peer timeout. It also lets different consumers of the same signal act at different confidence levels: something that only needs to stop routing traffic to a possibly-dead node can act at a low phi and cheaply reverse course if the node turns out fine, while something that removes a node from a lock's quorum permanently can wait for a much higher phi, all from the same underlying measurement.
Worked example: computing phi from a pinned heartbeat history
Take a 6-sample sliding window of observed inter-arrival times, in milliseconds, for one peer: [1000, 1300, 700, 1100, 900, 1200].
Mean μ=1033.33 ms, population standard deviation σ=197.2 ms.
Approximating the interval distribution as Normal(μ,σ2), so that Plater(t)=21erfc(σ2t−μ) (erfc is the complementary error function, a standard tool for turning a distance from the mean into the probability mass remaining in the distribution's tail beyond that point), gives:
| Elapsed since last heartbeat | phi |
|---|---|
| 1000 ms | 0.25 |
| 1500 ms | 2.05 |
| 2500 ms | 13.29 |
| 3500 ms | 35.47 |
Tracing the 1500 ms row end to end: standardize the elapsed time against this peer's own mean and spread, z=(1500−1033.33)/(197.2×2)=466.67/278.88≈1.673; convert that into a tail probability, Plater(1500)=21erfc(1.673)≈21×0.0180≈0.00898; then take −log10 of that probability, ϕ(1500)=−log10(0.00898)≈2.05. The other three rows fall out of the same three steps with a different elapsed time plugged in.
At t = 1000 ms, right around this peer's own mean, phi stays near zero: nothing unusual. At t = 1500 ms, phi crosses 2, a mild anomaly worth noting but not worth acting on for most purposes. By t = 2500 ms, phi is in the double digits, meaning the observed silence is astronomically improbable given this specific peer's recent behavior, which is enough statistical confidence for even a conservative consumer to move the node to SUSPECT, or to DEAD if it was already SUSPECT and never refuted with a higher incarnation.
Trade-offs and pitfalls
Phi is not a probability itself, it is a log-scaled confidence score, and reading a given phi value as a direct percentage chance of failure is a common misunderstanding; the number only means something relative to whatever threshold a given consumer chooses. A second pitfall is picking one global phi threshold across a heterogeneous fleet, which reintroduces the exact problem this design was meant to solve, since the entire benefit comes from calibrating to each peer's own recent history rather than from a smarter constant. Third, phi accrual detects the absence of a heartbeat; it cannot distinguish a genuinely dead node from a network partition dropping every packet between two specific nodes while both are alive and healthy elsewhere, so membership decisions that need to be safe, like removing a node from a lock's quorum, still need a consensus-backed or fencing mechanism layered on top of the suspicion signal, not phi alone.
Implement a small vector clock library with an increment operation (for a given node), a merge operation (combining two clocks on message receipt), and a compare operation that returns whether one clock happened-before, happened-after, or is concurrent with another.
Sample Answer
A vector clock is a dictionary from node id to an integer counter, used to capture happens-before ordering across replicas without relying on synchronized wall-clock time. increment(node) bumps that node's own counter for a local event. merge(other) folds in a remote clock by taking the elementwise maximum, which is what happens when a message carrying a remote clock is received. compare(other) derives happens-before, happens-after, or concurrent by checking, across every node id either clock has ever mentioned, whether one clock is entrywise less-than-or-equal, greater-than-or-equal, or neither.
Approach
- Represent a clock as a plain map from node id to a non-negative integer; a missing entry is implicitly zero.
incrementonly ever touches the caller's own entry.mergetakes the elementwise maximum against another clock's entries, never an overwrite, since an overwrite would discard causal information the receiver already had that the sender does not.comparewalks the union of both node-id sets (not the intersection), tracking whether self is ever strictly behind and whether self is ever strictly ahead; both true means concurrent, only behind means before, only ahead means after, neither means the clocks are equal.
Implementation
from typing import Dict
class VectorClock:
def __init__(self, clock: Dict[str, int] = None):
self.clock = dict(clock) if clock else {}
def increment(self, node_id: str) -> None:
"""Bump this node's own counter for a local event."""
self.clock[node_id] = self.clock.get(node_id, 0) + 1
def merge(self, other: "VectorClock") -> None:
"""Fold in another clock's knowledge (elementwise max), e.g. on message receipt."""
for node, count in other.clock.items():
if count > self.clock.get(node, 0):
self.clock[node] = count
def compare(self, other: "VectorClock") -> str:
"""Return 'before', 'after', 'concurrent', or 'equal' relative to other."""
self_behind = False
self_ahead = False
for node in set(self.clock) | set(other.clock):
a = self.clock.get(node, 0)
b = other.clock.get(node, 0)
if a < b:
self_behind = True
elif a > b:
self_ahead = True
if self_behind and self_ahead:
return "concurrent"
if self_behind:
return "before"
if self_ahead:
return "after"
return "equal"
def copy(self) -> "VectorClock":
return VectorClock(self.clock)
Worked example (traced against the code above)
Three nodes, A, B, and C, start with empty clocks.
A.increment('A'): A's clock becomes{A: 1}.- A sends a message to B, attaching a copy of its clock,
{A: 1}. - B receives the message:
B.merge({A: 1})gives B{A: 1}; because receiving a message is itself an event for B,B.increment('B')follows, giving B's clock{A: 1, B: 1}. - Concurrently and independently,
C.increment('C'): C's clock becomes{C: 1}.
Running the code on these clocks: B.compare(C) returns "concurrent". On entry A, B has 1 and C has 0 (B ahead); on entry C, B has 0 and C has 1 (B behind). Since B is ahead on one entry and behind on another, neither clock dominates, correctly reflecting that C's event never observed A's or B's. A.compare(B) returns "before": A's clock is less-than-or-equal to B's on every entry and strictly less on B's own entry, so A happened-before B, matching the real causal chain where A's event produced the message that produced B's receive event.
Generalizing beyond one clock per node
The same increment/merge/compare triad generalizes to per-key state: a system merging timestamped feature updates across regions, or reconciling model-parameter dictionaries updated independently by different regions, attaches one vector clock per key (or per parameter) instead of one global clock, and uses compare to decide whether an incoming update for that key is newer (after, apply it), already reflected (before, drop it), or a genuine conflict (concurrent, requiring an explicit merge rule such as last-writer-wins by node id or a domain-specific reducer).
Complexity
increment: O(1).merge: O(m), where m is the number of distinct node ids in the incoming clock.compare: O(u), where u is the size of the union of node ids across both clocks.- Space: O(n) per clock, where n is the number of distinct nodes that have ever contributed an entry the clock has observed.
Edge cases
- Equal clocks should not be reported as concurrent; the implementation above returns a distinct
"equal"only when self is neither behind nor ahead on any entry, since callers that treat equal as concurrent may re-run merge logic on a message a node has already fully seen. - Disjoint node sets (a clock that has never heard of a node the other clock has) must be treated as an implicit zero for the missing entry, not skipped: skipping those entries would limit the check to keys both clocks happen to have, and when that limited set of keys looks tied, the result comes back as a false "equal" verdict, even though the full comparison, including the entries only one side has, would show a genuine before or after relationship.
- Unbounded growth: a node that permanently leaves the cluster still occupies an entry forever unless clocks are pruned, and pruning is unsafe to do unilaterally, since dropping an entry a peer still relies on for comparison can turn a real before relationship into a false concurrent one.
- Clock skew is a non-issue by construction, since a vector clock never reads wall-clock time, but that is also its limitation: it says nothing about real elapsed time between concurrent events, only about causal order.
Unlock Full Question Bank
Get access to all 34 Distributed Systems Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.