Topic B9
Consistent hashing
Splitting keys across servers so that adding a server moves only a few keys.
Watch: when a fourth server is added, count the data that changes place. The second method moves far less.
- being checked
- passed / marked
- finished / the result
Why modulo is a problem
With 3 servers, a key whose hash is 10 goes to server 10 % 3 = 1. Add a server: 10 % 4 = 2. Almost every key gets a different remainder. In a cache cluster, that means nearly the whole cache suddenly misses and every request falls through to the database at once, exactly when you're adding a server because load is high.
The circle
Picture a clock face numbered 0 to 2³² − 1. Each server is hashed to a point on it, and so is each key. To find a key's owner, walk clockwise from the key until you meet the first server. A new server only "takes" the keys between itself and the server before it; every other key stays put. Finding the next server on the circle is a binary search over the sorted list of server positions.
Code, for programmersA ring with virtual nodes
class Ring {
constructor(servers, vnodes = 100) {
this.points = []; // [position, server], sorted
for (const s of servers)
for (let v = 0; v < vnodes; v++) this.points.push([hash(`${s}#${v}`), s]);
this.points.sort((a, b) => a[0] - b[0]);
}
owner(key) {
const h = hash(key);
let lo = 0, hi = this.points.length; // first point at or after h
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (this.points[mid][0] < h) lo = mid + 1; else hi = mid;
}
return this.points[lo % this.points.length][1]; // wrap around past the top
}
}Virtual nodes
With one point per server, the gaps between servers on the circle can be very uneven: one server might own half of it. The fix: put each server at many points (100 to 200 virtual nodes). The split evens out, and when one server dies its keys spread over many servers instead of piling onto one neighbour.
Quiz
With hash(key) % N, servers go from 4 to 5. Roughly what share of keys move?
With consistent hashing, a 5th server is added. Which keys move?
What are virtual nodes for?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.