Scrivio Interview library
CodingFoundations8 min read · updated 12 November 2026

Implement a simple consistent hash ring in Java that maps String keys to node names, supporting addNode, removeNode and getNode, with virtual nodes. Give the data structure and complexity.

We keep a TreeMap<Long, String> from positions on the ring to node names, and insert V virtual points per node at hash(node + "#" + i). getNode(key) hashes the key and takes ceilingEntry(h), wrapping to firstEntry() when there is no larger point. With a well-distributed 64-bit hash such as the first 8 bytes of MD5, lookups cost O(log(N*V)) and adding or removing a node costs O(V log(N*V)); for safe concurrent use we build a new immutable ring and swap a volatile reference.

Why this question is asked

Consistent hashing shows up everywhere we spread keys over servers: cache clusters, sharded databases, load balancers with sticky routing. Writing one in an interview tests whether we know the idea and can pick the right Java data structure, and the follow-up questions about hash quality, virtual nodes and concurrency separate a working toy from something we could run. In this answer, we will recap the ring idea, choose the data structure, write the class, check the hash function, work out the complexity, and see why virtual nodes and an immutable snapshot matter.

1A Quick Recap of the Hash Ring

Imagine all possible 64-bit hash values arranged in a circle. Each node is placed on the circle at the hash of its name. To find the node for a key, we hash the key to a position on the circle and walk clockwise until we meet the first node; that node owns the key. When a node is added, it takes over only the keys between itself and the previous node, and when a node is removed, its keys pass to the next node clockwise. Every other key stays where it was, which is the whole point compared with hash(key) % N.

2Choosing the Data Structure

The operation we need is 'find the smallest position greater than or equal to h, or wrap around to the smallest position'. A sorted map does exactly that. In Java, TreeMap<Long, String> is a red-black tree with ceilingEntry(h), which returns the entry with the smallest key at or above h, and firstEntry(), which returns the smallest entry for the wrap-around. Both run in logarithmic time.

With one point per node, the arcs between nodes are random in length, so one node can own far more of the ring than another. Virtual nodes fix this: each node is placed at V points, for example at hash("cache-a#0"), hash("cache-a#1") and so on up to V - 1. With 100 or more points per node, each node's total share is close to 1/N.

3Writing the Ring

Here is the class. It keeps the current ring in a volatile field that always points to an unmodifiable map, and membership changes build a new map and swap the reference.

Java
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public final class ConsistentHashRing {
private final int virtualNodes;
private volatile NavigableMap<Long, String> ring = Collections.emptyNavigableMap();
public ConsistentHashRing(int virtualNodes) { this.virtualNodes = virtualNodes; }
public synchronized void addNode(String node) {
TreeMap<Long, String> next = new TreeMap<>(ring);
for (int i = 0; i < virtualNodes; i++) next.putIfAbsent(hash(node + "#" + i), node);
ring = Collections.unmodifiableNavigableMap(next); // readers see old or new, never half
}
public synchronized void removeNode(String node) {
TreeMap<Long, String> next = new TreeMap<>(ring);
for (int i = 0; i < virtualNodes; i++) next.remove(hash(node + "#" + i), node); // only our own points
ring = Collections.unmodifiableNavigableMap(next);
}
public String getNode(String key) {
NavigableMap<Long, String> r = ring; // one read of the volatile field
if (r.isEmpty()) throw new IllegalStateException("no nodes");
Map.Entry<Long, String> e = r.ceilingEntry(hash(key));
return (e != null ? e : r.firstEntry()).getValue(); // wrap around the ring
}
static long hash(String s) {
try {
byte[] d = MessageDigest.getInstance("MD5").digest(s.getBytes(StandardCharsets.UTF_8));
return ByteBuffer.wrap(d).getLong(); // first 8 bytes as a signed long
} catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
}
ConsistentHashRing ring = new ConsistentHashRing(100);
ring.addNode("cache-a"); ring.addNode("cache-b"); ring.addNode("cache-c");
ring.getNode("user-42"); // "cache-a"
ring.getNode("user-43"); // "cache-b"
ring.addNode("cache-d");
ring.getNode("user-42"); // "cache-a" unchanged: only keys in cache-d's arcs moved

Notice a few details. putIfAbsent and remove(key, value) protect against the rare case where two virtual points of different nodes hash to the same position: we never overwrite or delete another node's point. getNode reads the volatile field once into a local variable, so a concurrent addNode cannot change the map halfway through the lookup. And the wrap-around matters: a key whose hash is above the highest point belongs to the lowest point, which is what makes the line a circle. Negative long values are fine, because the ring only needs a consistent order, and TreeMap orders signed longs consistently.

4Why Not String.hashCode()?

String.hashCode() returns a 32-bit int computed as s[0]*31^(n-1) + ... + s[n-1]. For similar strings, such as "cache-a#0" to "cache-a#99" or "user-42" and "user-43", the results differ only slightly, so they cluster in a small part of the 32-bit space, and a ring built on them is badly unbalanced. A cryptographic or well-mixed hash spreads similar inputs uniformly over 64 bits. MD5 is fine here because we need distribution, not security; Murmur3 or xxHash from a library such as Guava or Apache Commons Codec is faster for high lookup rates. MessageDigest instances are not thread-safe, which is why the code creates one per call; a ThreadLocal or a non-cryptographic hash avoids that cost.

5Complexity

With N nodes and V virtual points per node, the map holds N*V entries. getNode is one hash plus one ceilingEntry, so O(log(N*V)): with 40 nodes and 160 points each, that is a search among 6,400 entries, about 13 comparisons. In a version that mutates one TreeMap under a lock, addNode and removeNode insert or delete V entries, each in O(log(N*V)), so O(V log(N*V)). The copy-and-swap version above also copies the map, which is O(N*V), but membership changes are rare, a few times a day, while lookups happen millions of times per second, so making lookups lock-free is the better trade. Memory is O(N*V) entries.

Cost of each operation (N nodes, V virtual points)
OperationMutable TreeMap under a lockImmutable copy and swap
getNodeO(log(N*V)) with a read lockO(log(N*V)), no lock
addNodeO(V log(N*V))O(N*V) copy + O(V log(N*V))
removeNodeO(V log(N*V))O(N*V) copy + O(V log(N*V))
MemoryN*V entriesN*V entries (old copy freed after swap)

6Virtual Nodes, Weights and Concurrency

Virtual nodes do more than even out the load. When a node is removed, its many small arcs pass to many different neighbours, so its load spreads across the cluster instead of doubling one neighbour's load. And they let us weight nodes: a server with twice the memory gets 2V points and therefore about twice the keys. In a quick experiment with this ring, 3 nodes with 1 point each split 10,000 keys as 46, 31 and 23 percent; with 100 points each, the split was 35, 34 and 31 percent.

For concurrency, the immutable snapshot plus volatile reference gives readers a consistent ring without any locking: each lookup sees either the whole old ring or the whole new one. The synchronized keyword on the two mutators only stops two membership changes from racing each other and losing one.

7Follow-up questions

How many keys move when a node is added?

About 1/(N+1) of all keys, and they all move to the new node, taken in small pieces from the arcs just before each of its virtual points. In the experiment, adding a fourth node moved 2,683 of 10,000 keys, close to the ideal 25 percent, and every moved key went to the new node. With modulo hashing, going from 3 to 4 nodes would have moved about three quarters of the keys.

How many virtual nodes should we use?

Commonly 100 to 200 per node. More points give a more even split but use more memory and make membership changes slower; the gain flattens after a few hundred.

How would you test the ring?

Check that getNode is deterministic, that adding a node changes the owner only for keys that now map to the new node, that removal sends keys to the remaining nodes, and that the distribution over many random keys stays within a tolerance, for example each node within 10 percent of its fair share.

8Conclusion

In this answer, we built a consistent hash ring in Java with a TreeMap from 64-bit positions to node names, V virtual points per node, and lookups by ceilingEntry with a wrap-around to firstEntry. We used the first 8 bytes of MD5 instead of String.hashCode, which clusters similar strings. Lookups cost O(log(N*V)) and membership changes O(V log(N*V)) plus a copy in the snapshot version, virtual nodes even out load and allow weights, and an immutable ring behind a volatile reference makes concurrent lookups safe without locks.

What to say in the interviewAbout 100 seconds aloud

Open with

I would use a TreeMap from Long to String, where the key is a position on the ring and the value is the node name. For each node I insert V virtual points, at hash of the node name plus hash sign plus i, for i from 0 to V minus one, typically 100 to 200 points.

Then, if they want more

For getNode, I hash the key and call ceilingEntry, which gives the first point at or after it, and if that is null I wrap around with firstEntry. For the hash I would not use String.hashCode, because it is 32 bits and similar strings cluster, so the ring would be unbalanced.

I would take the first 8 bytes of an MD5 digest as a long, or use Murmur3 if lookups are very hot. Complexity: getNode is O(log of N times V); addNode and removeNode insert or remove V points, so O(V log(NV)).

For concurrency, since membership changes are rare and lookups are constant, I would build a new TreeMap on each change, wrap it as unmodifiable and swap it into a volatile field, with the mutators synchronized against each other. Readers then never lock and always see a complete ring.

Virtual nodes also matter beyond balance: when a node leaves, its keys spread over many nodes instead of one neighbour, and I can weight a bigger node by giving it more points. When a node is added, only about 1 over N plus 1 of the keys move, all to the new node.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Implement a simple consistent hash ring in Java that maps String keys to node names...": https://scrivio-interview-library.netlify.app/databases/partitioning-and-sharding/698bfe1313/