Video in progress
How do you write consistent hashing in Java, and why are virtual nodes needed?
I place the nodes on a hash ring, a TreeMap<Long, Node>. For a key, ceilingEntry(hash) gives the first node clockwise. When a node is added or removed, only the keys in the neighboring range move. Virtual nodes spread the load evenly.
📖 Answer
With a plain hash(key) % N, when N changes almost every key moves to a different node; for a cache, that means everything misses at once. With consistent hashing, only about 1/N of the keys move.
final class HashRing<N> {
private final TreeMap<Long, N> ring = new TreeMap<>();
private final int replicas;
HashRing(int replicas) { this.replicas = replicas; }
void add(N node) {
for (int i = 0; i < replicas; i++) ring.put(hash(node + "#" + i), node);
}
void remove(N node) {
for (int i = 0; i < replicas; i++) ring.remove(hash(node + "#" + i));
}
N nodeFor(String key) {
if (ring.isEmpty()) throw new IllegalStateException("bo'sh halqa");
Map.Entry<Long, N> e = ring.ceilingEntry(hash(key));
return (e != null ? e : ring.firstEntry()).getValue(); // the ring wraps around
}
private static long hash(String s) {
byte[] d;
try { d = MessageDigest.getInstance("MD5").digest(s.getBytes(StandardCharsets.UTF_8)); }
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
return ByteBuffer.wrap(d).getLong();
}
}
Without virtual nodes, 3 nodes land at random places on the ring, and one of them can take 60% of it. If you place 100-200 virtual points per node, the distribution evens out a lot. You can also give a stronger server more virtual nodes to give it more weight.
Don't use String.hashCode(): it's 32 bits and the distribution is poor. MD5 is here not for cryptographic purposes but only for good spreading; if you need speed, use Murmur3 or xxHash.
Two more variants worth knowing:
- Rendezvous (HRW) hashing: for each key you compute
hash(key, node)over all nodes and pick the largest. There's no ring and the code is simpler, but it's O(N); - Jump consistent hash: it uses no memory at all and is very fast, but nodes can only be added and removed at the end.
In practice you see this in systems like Cassandra and DynamoDB and in client-side sharding. Redis Cluster does it differently: 16384 fixed slots.
Sign up to mark studied questions and save your progress.