Sub topic 12
Routing requests: coordinators and client-side routing
This chapter assumes you know how a consistent-hash ring and preference lists work, and that you have seen gossip-based membership. It covers a narrower question: when a client sends get or put for a key, which machine receives it, and what does that machine do?
The routing problem
Every node in the cluster can own some keys. A client holding user:42 does not know which nodes store it. Someone has to map the key to its preference list (the N nodes that hold replicas) and then contact those nodes. Two designs exist, and many systems combine them.
- Server-side routing. The client sends the request to any node. That node forwards it to the right place.
- Client-side routing. The client keeps a copy of the ring and sends the request directly to a node in the key's preference list.
The node that handles a request on behalf of the client is the coordinator. It talks to the replicas, collects their responses, applies the quorum rule, and replies to the client. The coordinator for a key is usually one of the key's replicas, but it does not have to be.
The coordinator's job
For a put, the coordinator does these steps:
- Hash the key and compute its preference list from the ring.
- Generate a new version for the value, for example by incrementing its own counter in the vector clock.
- Send the write to all N replicas in parallel.
- Wait for W acknowledgements, then reply success.
For a get, it does the following:
- Compute the preference list.
- Send read requests to the replicas.
- Wait for R responses.
- Compare the versions. Return the newest one, or all concurrent siblings.
- Trigger read repair in the background if some replicas returned stale data.
Note that the coordinator sends to all N replicas, not only to R or W of them. It simply stops waiting once the quorum is met. The slower replicas still receive the write, which keeps them closer to current.
import bisect
import hashlib
def h(key: str) -> int:
return int.from_bytes(hashlib.md5(key.encode()).digest()[:8], "big")
class Ring:
def __init__(self, nodes, vnodes=64):
self._points = sorted(
(h(f"{node}#{i}"), node) for node in nodes for i in range(vnodes)
)
self._hashes = [p[0] for p in self._points]
def preference_list(self, key: str, n: int):
start = bisect.bisect(self._hashes, h(key)) % len(self._points)
result = []
for i in range(len(self._points)):
node = self._points[(start + i) % len(self._points)][1]
if node not in result:
result.append(node)
if len(result) == n:
break
return result
def handle_request(self_node: str, ring: Ring, key: str, n: int = 3):
"""Decide whether this node coordinates the request or forwards it."""
replicas = ring.preference_list(key, n)
if self_node in replicas:
return ("coordinate", replicas)
return ("forward", replicas[0])
ring = Ring(["node-a", "node-b", "node-c", "node-d", "node-e"])
for node in ["node-a", "node-b", "node-c", "node-d", "node-e"]:
print(node, handle_request(node, ring, "user:42"))Nodes in the preference list coordinate the request. Any other node forwards it to the first replica. That forwarding costs one extra network hop.
Server-side routing through any node
In the simplest design, clients treat the cluster as a pool behind a load balancer. The load balancer sends each request to a random node. That node checks the ring, then either coordinates or forwards.
Advantages:
- Clients stay simple. They need no ring logic and no membership updates.
- Ring changes are invisible to clients.
- Works with any language or client library.
Costs:
- When the random node is not a replica, the request takes an extra hop. With N=3 on a 100-node cluster, about 97% of requests take that hop.
- The load balancer is another component that can fail and add latency.
Client-side routing
A partition-aware client downloads the ring, or a compact form of it, from any node. It then hashes keys itself and sends each request straight to a replica in the preference list. This removes the extra hop and the load balancer.
Advantages:
- Lower latency, because the request goes to the right node the first time.
- Less load on the cluster, since no node spends time forwarding.
Costs:
- Every client library must implement the hashing and ring logic correctly, in every supported language. A bug causes silent misrouting.
- Clients need fresh membership data. A stale ring sends requests to the wrong nodes.
- Many clients means many connections and many ring copies to keep consistent.
The Dynamo paper describes both modes. It reports that client-driven coordination gave lower latency at the 99.9th percentile than server-driven coordination, but at the price of pushing the complexity into the client.
Stale rings and what happens
A client's ring will sometimes be out of date: a node joined, left, or failed after the client last refreshed. The system must stay correct in that case. Correctness should never depend on the client being right.
The usual approach is that the receiving node always validates. If node X receives a request for a key and is not in the preference list, it does not process the request as coordinator. It forwards the request to the correct replica. Optionally it also returns the current ring version so the client can refresh.
def route_with_version(self_node, ring, ring_version, key, client_version, n=3):
replicas = ring.preference_list(key, n)
if self_node not in replicas:
return {"action": "forward", "to": replicas[0], "ring_version": ring_version}
response = {"action": "coordinate", "replicas": replicas}
if client_version != ring_version:
response["ring_version"] = ring_version # hint: refresh your ring
return responseThis turns the client's ring into a performance hint. A wrong hint costs one extra hop and never gives a wrong answer.
Choosing the coordinator
When several replicas could coordinate, the choice matters.
| Strategy | How it works | Trade-off |
|---|---|---|
| First in preference list | Always use replica 1 | Simple. Gives that node more coordination load and serializes writes per key on one node. |
| Random replica | Client or load balancer picks any replica | Spreads load. Different coordinators may write the same key concurrently, so vector clocks matter more. |
| Least loaded or lowest latency | Pick by recent response time | Reduces tail latency. Needs latency tracking. |
| Last writer's node | Prefer the node that served the previous write for this key | Helps read-your-writes. Narrow benefit and complex to maintain. |
With a single fixed coordinator per key, one node assigns each version, so the vector clock grows by only one entry per key. With random coordinators, multiple nodes increment their own entries, and the clock can grow. Systems that allow any replica to coordinate often truncate old clock entries, which risks false conflicts.
Coordinators and failures
The coordinator can fail halfway through a request. Several cases follow.
- Coordinator dies before sending anything. The client times out and retries, ideally against a different node.
- Coordinator dies after some replicas stored the write. The client sees a timeout but the write may exist on some replicas. The client cannot tell whether it succeeded.
- Replicas do not respond. The coordinator reaches its timeout with fewer than W acknowledgements and returns an error. The write may still be on some replicas.
Because of these cases, retries must be safe. A put of the same value with a new version is not a problem, since it simply creates another version. Operations such as "append" or "increment" are not idempotent and need extra care, such as a unique request ID that replicas use to drop duplicates.
Sloppy quorums and the coordinator
When a replica in the preference list is down, the coordinator uses the next healthy node on the ring to hold a hinted write. The coordinator relies on its membership view from gossip to decide which nodes to skip. A coordinator with a stale view may wait on a dead node until timeout, or skip a node that has recovered. Neither breaks correctness, but both add latency or repair work.
Request flow
Choosing between the designs
| Question | Favors server-side | Favors client-side |
|---|---|---|
| Many languages and third-party clients? | Yes | No |
| Tight tail-latency target? | No | Yes |
| Ring changes often? | Yes | No |
| Can you ship and maintain client libraries? | No | Yes |
A common middle path is a thin client that sends to any node and caches which node answered as a replica, or a client that learns routing hints from response headers. Cassandra drivers are an example of token-aware clients that route to a replica but fall back gracefully to any node.
Common mistakes
- Treating the client's ring as authoritative. Servers must verify and forward.
- Retrying non-idempotent writes without a request ID.
- Letting every node forward without a hop limit. Two nodes with different ring views can bounce a request back and forth, so include a hop count and fail after one or two forwards.
- Forgetting that the coordinator waits for W or R responses but still sends to all N replicas.
Exercise
A cluster has 50 nodes, N=3, and clients send each request to a random node. Roughly what fraction of requests need a forwarding hop, and why is it safe for a client to use a stale ring if the servers check the preference list?
Show answer
About 94% (47 of 50 nodes are not replicas of a given key) need a forwarding hop. A stale ring is safe because a node that receives a request for a key it does not own forwards it to a correct replica instead of coordinating it, so the stale ring only costs an extra hop and never causes a wrong result.
Exercise
Why should forwarded requests carry a hop count?
Show answer
If two nodes hold different ring views, each can believe the other owns the key and forward the request back and forth. A hop limit, such as two, makes the request fail with an error instead of looping forever.