Java Design Program · CD27
Implement Consistent Hashing in Java
With hash(key) % n, adding one server changes n and almost every key moves. Consistent hashing places servers and keys on a ring, so a new server only takes keys from its neighbours.
Problem Statement
Build a ring with addNode(name), removeNode(name) and nodeFor(key). A key belongs to the first server position at or after the key's own position, wrapping around at the end.
Each server is placed at 100 positions (virtual nodes) so the keys spread evenly. Show that adding or removing a server moves only the keys it gains or loses.
Input/Output Examples
10,000 keys on A, B, C; add DOutput2,479 keys move, all to DExplanation: about 1/4, the share D should own.remove B from A, B, C, DOutput2,486 keys move, all from BExplanation: only B's keys need a new home.hash % 3 changed to hash % 4Output7,464 keys moveExplanation: about 3/4 of all keys, which floods a cache with misses.Visual Explanation
- RingpositionsABCABCeach node appears many times
- Lookupkeyk→Bfirst node clockwise
- Add DpositionsADBCDAD takes the arcs before its points
- Other keysownersunchangedonly keys landing on D's arcs move about 1/4
- Doneminimal key movement
Virtual nodes are what make the split fair: with a single point per server, the arcs between points can differ hugely in size.
Approaches
Both approaches give the same owner for every key, checked on 300 random sequences of node changes. The first stores the ring in a TreeMap; the second in sorted arrays.
Approach 1: TreeMap Ring (Recommended)
Idea: map each virtual node's hash to its server in a TreeMap; ceilingEntry(hash(key)) finds the owner, and firstEntry() handles the wrap-around.
- For each server, put
hash(name + "#" + i)for 100 values ofi. - To find a key's server, call
ceilingEntry(hash(key)). - If it returns
null, the key is past the last point, so usefirstEntry(). - To remove a server, remove its 100 points.
Time: O(log p) · Space: O(p). per lookup; p is the number of points (servers × virtual nodes).
Approach 2: Sorted Arrays and Binary Search
Idea: keep the point positions in a sorted long[] with a parallel array of owners, and find a key's owner with Arrays.binarySearch().
- On every node change, rebuild and sort the list of (position, node) pairs.
- Binary-search the key's hash; a negative result gives the insertion point.
- If the insertion point is past the end, wrap to index 0.
Time: O(log p) · Space: O(p). per lookup; a node change costs O(p log p).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: TreeMap Ring (Recommended)
The standard answer: adding or removing a server costs only O(v log p) for its v points.
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class ConsistentHashTreeMap {
// The ring is a sorted map from position (hash) to node. A key belongs to the first node
// at or after its own position, wrapping around to the start of the ring.
static class Ring {
private final TreeMap<Long, String> ring = new TreeMap<>();
private final int virtualNodes;
Ring(int virtualNodes) { this.virtualNodes = virtualNodes; }
void addNode(String node) {
for (int i = 0; i < virtualNodes; i++) ring.put(hash(node + "#" + i), node);
}
void removeNode(String node) {
for (int i = 0; i < virtualNodes; i++) ring.remove(hash(node + "#" + i));
}
String nodeFor(String key) {
Map.Entry<Long, String> e = ring.ceilingEntry(hash(key));
return (e != null ? e : ring.firstEntry()).getValue(); // past the last point: wrap around
}
}
// The first 8 bytes of MD5 give a well-spread, stable 64-bit position: the same on every run and JVM
static long hash(String s) {
try {
byte[] d = MessageDigest.getInstance("MD5").digest(s.getBytes(StandardCharsets.UTF_8));
long h = 0;
for (int i = 0; i < 8; i++) h = (h << 8) | (d[i] & 0xFF);
return h;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e); // every JDK is required to provide MD5
}
}
public static void main(String[] args) {
int keys = 10_000;
Ring ring = new Ring(100); // 100 virtual nodes per server
for (String node : List.of("A", "B", "C")) ring.addNode(node);
Map<String, String> before = assign(ring, keys);
System.out.println("3 nodes, keys per node: " + count(before));
ring.addNode("D");
Map<String, String> afterAdd = assign(ring, keys);
int moved = 0;
boolean allToD = true;
for (String k : before.keySet()) {
if (!before.get(k).equals(afterAdd.get(k))) {
moved++;
allToD &= afterAdd.get(k).equals("D");
}
}
System.out.println("add D, keys per node: " + count(afterAdd));
System.out.println("keys moved: " + moved + " of " + keys + ", all of them to D: " + allToD);
ring.removeNode("B");
Map<String, String> afterRemove = assign(ring, keys);
int movedR = 0;
boolean onlyFromB = true;
for (String k : afterAdd.keySet()) {
if (!afterAdd.get(k).equals(afterRemove.get(k))) {
movedR++;
onlyFromB &= afterAdd.get(k).equals("B");
}
}
System.out.println("remove B, keys moved: " + movedR + ", all of them from B: " + onlyFromB);
int movedModulo = 0; // the naive scheme for comparison
for (int i = 1; i <= keys; i++) {
long h = hash("user-" + i);
if (Math.floorMod(h, 3) != Math.floorMod(h, 4)) movedModulo++;
}
System.out.println("hash % n would move: " + movedModulo + " of " + keys + " when going from 3 to 4 nodes");
}
static Map<String, String> assign(Ring ring, int keys) {
Map<String, String> owner = new HashMap<>();
for (int i = 1; i <= keys; i++) owner.put("user-" + i, ring.nodeFor("user-" + i));
return owner;
}
static Map<String, Integer> count(Map<String, String> owner) {
Map<String, Integer> c = new TreeMap<>();
owner.values().forEach(n -> c.merge(n, 1, Integer::sum));
return c;
}
}
3 nodes, keys per node: {A=3196, B=3424, C=3380}
add D, keys per node: {A=2556, B=2486, C=2479, D=2479}
keys moved: 2479 of 10000, all of them to D: true
remove B, keys moved: 2486, all of them from B: true
hash % n would move: 7464 of 10000 when going from 3 to 4 nodes
Time complexity: O(log p) · Space complexity: O(p).
Approach 2: Sorted Arrays and Binary Search
Compact and cache-friendly for read-heavy systems where servers change rarely.
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
public class ConsistentHashSortedArray {
// The same ring stored as two parallel sorted arrays; lookups use binary search.
// Changing the node list rebuilds the arrays, which is fine because lookups are far more common.
static class Ring {
private final int virtualNodes;
private final List<String> nodes = new ArrayList<>();
private long[] points = new long[0];
private String[] owners = new String[0];
Ring(int virtualNodes) { this.virtualNodes = virtualNodes; }
void addNode(String node) { nodes.add(node); rebuild(); }
void removeNode(String node) { nodes.remove(node); rebuild(); }
private void rebuild() {
int n = nodes.size() * virtualNodes;
long[][] pairs = new long[n][2]; // {position, index of the node}
int p = 0;
for (int j = 0; j < nodes.size(); j++) {
for (int i = 0; i < virtualNodes; i++) pairs[p++] = new long[]{hash(nodes.get(j) + "#" + i), j};
}
Arrays.sort(pairs, (x, y) -> Long.compare(x[0], y[0]));
points = new long[n];
owners = new String[n];
for (int i = 0; i < n; i++) {
points[i] = pairs[i][0];
owners[i] = nodes.get((int) pairs[i][1]);
}
}
String nodeFor(String key) {
int i = Arrays.binarySearch(points, hash(key));
if (i < 0) i = -i - 1; // insertion point = first position after the key
return owners[i == points.length ? 0 : i]; // wrap around
}
}
// The first 8 bytes of MD5 give a well-spread, stable 64-bit position: the same on every run and JVM
static long hash(String s) {
try {
byte[] d = MessageDigest.getInstance("MD5").digest(s.getBytes(StandardCharsets.UTF_8));
long h = 0;
for (int i = 0; i < 8; i++) h = (h << 8) | (d[i] & 0xFF);
return h;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e); // every JDK is required to provide MD5
}
}
public static void main(String[] args) {
int keys = 10_000;
Ring ring = new Ring(100); // 100 virtual nodes per server
for (String node : List.of("A", "B", "C")) ring.addNode(node);
Map<String, String> before = assign(ring, keys);
System.out.println("3 nodes, keys per node: " + count(before));
ring.addNode("D");
Map<String, String> afterAdd = assign(ring, keys);
int moved = 0;
boolean allToD = true;
for (String k : before.keySet()) {
if (!before.get(k).equals(afterAdd.get(k))) {
moved++;
allToD &= afterAdd.get(k).equals("D");
}
}
System.out.println("add D, keys per node: " + count(afterAdd));
System.out.println("keys moved: " + moved + " of " + keys + ", all of them to D: " + allToD);
ring.removeNode("B");
Map<String, String> afterRemove = assign(ring, keys);
int movedR = 0;
boolean onlyFromB = true;
for (String k : afterAdd.keySet()) {
if (!afterAdd.get(k).equals(afterRemove.get(k))) {
movedR++;
onlyFromB &= afterAdd.get(k).equals("B");
}
}
System.out.println("remove B, keys moved: " + movedR + ", all of them from B: " + onlyFromB);
int movedModulo = 0; // the naive scheme for comparison
for (int i = 1; i <= keys; i++) {
long h = hash("user-" + i);
if (Math.floorMod(h, 3) != Math.floorMod(h, 4)) movedModulo++;
}
System.out.println("hash % n would move: " + movedModulo + " of " + keys + " when going from 3 to 4 nodes");
}
static Map<String, String> assign(Ring ring, int keys) {
Map<String, String> owner = new HashMap<>();
for (int i = 1; i <= keys; i++) owner.put("user-" + i, ring.nodeFor("user-" + i));
return owner;
}
static Map<String, Integer> count(Map<String, String> owner) {
Map<String, Integer> c = new TreeMap<>();
owner.values().forEach(n -> c.merge(n, 1, Integer::sum));
return c;
}
}
3 nodes, keys per node: {A=3196, B=3424, C=3380}
add D, keys per node: {A=2556, B=2486, C=2479, D=2479}
keys moved: 2479 of 10000, all of them to D: true
remove B, keys moved: 2486, all of them from B: true
hash % n would move: 7464 of 10000 when going from 3 to 4 nodes
Time complexity: O(log p) · Space complexity: O(p).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| TreeMap Ring | O(log p) | O(p) |
| Sorted Arrays and Binary Search | O(log p) | O(p) |
Both rings answer a lookup with a binary search over p points. The TreeMap updates in place when a server joins or leaves; the arrays are rebuilt, which is cheap because it happens rarely.
Interview Tips and Recommended Approach
- Start with the problem: going from
nton + 1servers with modulo hashing moves aboutn / (n + 1)of the keys. - Explain virtual nodes; they even out the load and spread a failed server's keys over all the others.
- Use a well-spread hash, such as MD5 or MurmurHash.
String.hashCode()clusters similar names. - Name real uses: distributed caches, sharded databases such as Cassandra and DynamoDB, and load balancers.
Recommended Approach: TreeMap Ring
Why: the TreeMap gives the clockwise lookup in one call and lets servers join or leave without rebuilding the whole ring.