Drafting a distributed hash table explanation
I'm thinking of how to use examples to explain N nodes, each with V virtual nodes, and mention that the number of vnodes could be between 100 and 1000. The ring representation might involve sorting the list of tokens and using binary search. When adding a node, the key movement fraction would be 1/(N+1) and 1/N when removing. I also want to touch on failure handling and suggest including pseudocode while discussing collisions and hash functions. Let's put this draft together!
1) Ring design (the “token space”)
Idea: Map both keys and nodes into the same circular hash space, then assign each key to the first node clockwise from the key’s position.
Token space
- Pick a fixed-size integer space, commonly 0 … 2⁶⁴−1 (or 2¹²⁸−1).
- Use a fast, well-distributed hash (e.g., Murmur3, xxHash, SipHash if you need DoS-resistance).
- Interpret the hash as an unsigned integer; wrap-around creates the “ring”.
Node placement (“tokens”)
- Each physical node is assigned one or more tokens (points on the ring).
- The node is responsible for the interval(s) from the previous token (exclusive) to its token (inclusive).
Lookup
- Compute
t = hash(key) → token.
- Find the smallest node-token ≥ t in a sorted list; if none, wrap to the first token.
- That node owns the key (or the first replica owner).
Data structure in practice:
- Maintain a sorted array / B-tree of
(token -> node) entries.
- Lookup is O(log M) where
M = #tokens (often M = N * V, nodes * virtual-nodes-per-node).
Replication on a ring (common)
- To store
R replicas, walk clockwise selecting the next R distinct physical nodes (skipping tokens that map to the same physical node due to vnodes).
- This avoids placing multiple replicas on the same machine.
2) Virtual nodes (vnodes): why they matter
With one token per node, ring segments can be uneven → uneven key and load distribution. Virtual nodes fix that by giving each physical node many small segments.
How vnodes work
- Each physical node gets V tokens (vnodes), e.g.
V = 64 … 1024.
- Tokens are generated like:
token_i = hash(node_id || i) for i in [0..V-1].
- Ownership becomes the union of those many small intervals.
Benefits
- Smoother key distribution: less variance between nodes.
- Faster, smaller rebalances: adding/removing a node affects many small ranges rather than one big range.
- Capacity weighting: stronger nodes get more vnodes (or larger token share).
Weighted vnodes (heterogeneous clusters)
If node A is 2× as powerful as node B:
- Give A about 2× as many vnodes (or tokens with 2× total share).
- This is the most common practical way to do “weights” on a ring.
3) Key distribution in practice
Expected distribution
If hashing is uniform:
- With N equal nodes and enough vnodes, each gets ~
1/N of keys.
- When you add 1 node, the new node takes about 1/(N+1) of the keyspace (and thus data), taken proportionally from others.
- When you remove 1 node, about 1/N of keys move away from it to neighbors.
Variance and “how many vnodes is enough?”
- With few tokens, you can get large segment-length variance (some nodes own much larger intervals).
- Increasing
V reduces imbalance; many systems land around 128–512 vnodes/node for stable behavior (exact choice depends on cluster size and memory for the token map).
Real world caveat: skew is often not from hashing
Even with perfect key distribution, load can be skewed because:
- some keys are “hot” (popular),
- requests aren’t uniform,
- values differ dramatically in size,
- write amplification differs by key.
So you need hotspot mitigation beyond “more vnodes” (see section 5).
4) Rebalancing strategy (membership changes)
Consistent hashing minimizes movement, but you still need an operational plan: who copies what, when, and how you keep serving traffic safely.
Adding a node (bootstrap)
Typical steps:
- Assign vnodes/tokens to the new node (random/deterministic).
- Publish membership change (via a registry / gossip / config service).
- For each of the new node’s token intervals, identify the previous owner (predecessor on the ring).
- Stream data for those ranges from the old owner(s) to the new node.
- During transfer:
- Serve reads using replication/quorums, or
- Temporarily dual-read (old+new) and dual-write, or
- Use handoff / “pending ranges” until the new node catches up.
- Once caught up, mark ranges as fully owned.
With replication, you typically rebalance replica placement too:
- The new node often becomes a replica for some ranges and may become primary for others (depending on your scheme).
Removing/failing a node
- Planned removal: stream its ranges out first (graceful decommission).
- Failure: neighbors (or next replicas) take over ownership immediately; later, a replacement node can be added and ranges streamed back to restore desired replication.
Controlling the blast radius
Operational safeguards:
- Rate limit streaming (rebalancing can saturate disks/network).
- Move ranges in small batches (vnodes help).
- Prefer off-peak rebalances or adaptive throttling.
- Track per-range progress; make rebalance resumable.
5) Hotspots mitigation (beyond even distribution)
Hotspots typically arise from access skew, not just uneven ring segments. Practical mitigations:
A) Reduce uneven ownership
- Increase vnodes to reduce segment size variance.
- Use weighted vnodes so high-capacity nodes own more ranges.
- Ensure your token generator is well-distributed (avoid correlated tokens).
B) Handle hot keys (popular items)
Even perfect hashing can’t fix “one key gets 10% of traffic”.
Common techniques:
- Caching (local cache, CDN, near-cache): absorb read hotspots.
- Request coalescing: collapse many concurrent misses for the same key into one backend fetch.
- Key splitting / salting (when semantics allow):
- Store
key#0 … key#k-1 and spread writes/reads across shards, then aggregate.
- Often used for counters, rate limits, “likes”, etc.
- Adaptive replication for hot keys:
- Temporarily replicate hot items to more nodes and route reads accordingly.
- More complex but effective when read-heavy.
C) Load-aware routing (advanced)
Plain consistent hashing ignores current load. Options:
- Bounded-load consistent hashing: place keys as usual, but if target node is “too full”, walk to the next node until within a load bound.
- Power of two choices: hash a key to two candidate nodes and choose the less loaded (not purely ring-based, but commonly used in practice for load balance).
D) Avoid correlated failure domains
Hotspots can be amplified if replicas land in the same rack/AZ:
- When picking the next
R replicas on the ring, enforce rack/AZ diversity (skip nodes in the same failure domain).
Putting it together (a typical production recipe)
- Token space: 2⁶⁴, hash with Murmur3/xxHash (SipHash if adversarial keys possible).
- Per physical node: 128–512 vnodes, weighted by capacity.
- Lookup: binary search in sorted
(token -> node) map.
- Replication: walk ring for R distinct nodes, enforce zone diversity.
- Rebalance: streaming by vnode ranges, throttled, with temporary dual-read/dual-write or quorum reads/writes.
- Hotspots: caching + coalescing; salting for shardable keys; optional bounded-load routing for extreme skew.
If you share your constraints (cluster size, replication factor, heterogeneous nodes, failure domains, read/write mix), I can suggest concrete vnode counts, weighting strategy, and a rebalance workflow that matches those assumptions.