Interview conceptCoding & Algorithms

Consistent Hashing For Distributed Caches

Asked of: Software Engineer

Last updated

What's being tested

These problems test implementing and reasoning about consistent hashing with a sorted ring, virtual nodes, collision handling, and wraparound lookup. You must compare it against round-robin, preserve key-to-node ownership when membership changes, and analyze time, space, concurrency, and correctness. Expect debugging around hash/equality contracts, mutable state, and concurrent access.

Patterns & templates

  • Consistent-hash ring: map physical or virtual node tokens to hashes; select the first token >= keyHash, wrapping to the minimum token.

  • Use a sorted map such as `TreeMap`/`SortedMap`; lookup is O(log V), insertion/removal O(log V), and storage O(V) virtual nodes.

  • Add K virtual replicas per server to reduce skew; total ring positions are V = N × K, with larger K improving balance but increasing memory and rebuild cost.

  • Define deterministic hashing and collision behavior; if equal tokens occur, use a composite (hash, nodeId) key or collision bucket rather than overwriting.

  • For round-robin, maintain an atomic counter and choose nodes[counter % nodeCount]; handle empty membership and concurrent updates explicitly.

  • Preserve the hash-map invariant: equal keys must produce equal hashes; resizing must reinsert entries, and collision resolution must remain correct.

  • Test empty rings, one node, wraparound, duplicate nodes, node removal, hash collisions, concurrent reads/writes, and distribution using many keys.

Common pitfalls

Pitfall: Claiming only “one key moves” when adding a node; consistent hashing limits movement to the new node’s successor intervals, not exactly one key.

Pitfall: Forgetting wraparound, so keys larger than the greatest token fail instead of mapping to the smallest token.

Pitfall: Using physical nodes only and concluding distribution is always balanced; sparse tokens can create large ownership gaps and severe load skew.

Practice these

The practice cards below cover the canonical variants — solve all of them and time yourself.

Practice questions

Related concepts