Sub topic 2
Replicating Each Key to N Nodes
Assume you know hash rings, RPC, and basic Python. A replica is a copy of a key's value stored on another node. The replication factor, N, is the number of replicas for each key.
Preference Lists and Replication
A key is hashed to a position on the cluster's hash ring. Starting there, the system walks clockwise and selects the first N distinct physical nodes. This ordered list is the key's preference list.
def preference_list(points, hashes, key_hash, n):
start = bisect.bisect(hashes, key_hash) % len(points)
result = []
for offset in range(len(points)):
node = points[(start + offset) % len(points)][1]
if node not in result:
result.append(node)
if len(result) == n:
break
return resultReplication improves durability and availability. If one node fails, another replica can serve the key. It also increases write traffic, storage use, and the chance that replicas temporarily disagree.
Consistency and Trade-offs
A consistency model defines what a read is allowed to return after writes. Strong consistency makes recent writes visible predictably. Eventual consistency allows temporary disagreement but can reduce latency and keep serving requests during failures.
CAP says that during a network partition, a distributed system must choose between:
- Consistency: every successful read sees the latest accepted value.
- Availability: every request receives a successful response.
PACELC adds another choice: even without a partition, a system chooses between lower latency and stronger consistency. Replicas may need coordination before responding.
Read and Write Quorums
A write quorum, W, is the number of replicas that must acknowledge a write. A read quorum, R, is the number that must answer a read. With N replicas, R + W > N guarantees that the read and write sets overlap.
For example, with N = 3, W = 2, and R = 2, at least one read replica belongs to the successful write set. This improves the chance of reading the newest value, but it does not by itself guarantee linearizability.
Tracking Causality
A vector clock records how many updates each node has observed. If one clock is less than or equal to another in every component, the first update happened before the second. If neither clock dominates, the updates are concurrent.
Concurrent values must be resolved. Common strategies include last-write-wins, application-defined merging, or keeping both values as siblings until a client resolves them.
def compare(a, b):
keys = set(a) | set(b)
a_before = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
b_before = all(b.get(k, 0) <= a.get(k, 0) for k in keys)
if a_before and b_before:
return "equal"
if a_before:
return "before"
if b_before:
return "after"
return "concurrent"Exercise
For N = 5, does R = 2 and W = 3 guarantee quorum overlap?
Show answer
Yes. Since R + W = 5 is not greater than N, no. The guarantee requires R + W > N, so one quorum must increase.