Exercise — Load Balancing Strategies: implement consistent hashing for sticky routing.
Topic: microservices, Infrastructure. Level: Hard.
Answer
Place nodes on a hash ring (with virtual nodes for even spread); route a key to the first node clockwise from the key's hash. Adding/removing a node only remaps keys near it, preserving most affinity — unlike `hash % N`, which remaps almost everything.
```java
class ConsistentHashRing {
private final TreeMap<Integer, String> ring = new TreeMap<>();
ConsistentHashRing(List<String> nodes, int vnodes) {
for (String n : nodes)
for (int i = 0; i < vnodes; i++)
ring.put((n + "#" + i).hashCode(), n); // virtual nodes
}
String route(String key) {
var e = ring.ceilingEntry(key.hashCode());
return (e != null ? e : ring.firstEntry()).getValue(); // wrap around
}
}
```