Sub topic 10
Hash-based balancing and consistent hashing
This chapter assumes you know how round robin and least connections work, what a backend pool is, and why session persistence matters. You should be comfortable reading NGINX and HAProxy configuration.
Why hash instead of rotate
Round robin and least connections ignore who the client is. Two requests from the same user can land on different servers. Hash-based balancing instead computes a number from a request attribute, called the key, and maps that number to a backend. The same key always goes to the same server while the pool stays unchanged.
Common keys are the client IP address, a user ID in a header, a cookie value, or the request URI. Hashing on the URI helps caches: the same URL always reaches the same cache server, so each server stores a distinct slice of the content.
Hashing gives you session persistence without the balancer storing any state. The trade-off is uneven load. If one key is very busy, one server absorbs it.
Simple modulo hashing and its flaw
The simplest approach hashes the key and takes the remainder when dividing by the number of servers:
import zlib
def pick(key, servers):
return servers[zlib.crc32(key.encode()) % len(servers)]
keys = [f"user{i}" for i in range(1000)]
before = ["a", "b", "c"]
after = ["a", "b", "c", "d"]
moved = sum(1 for k in keys if pick(k, before) != pick(k, after))
print(f"{moved} of {len(keys)} keys moved")Adding one server changes the divisor from 3 to 4. Most keys now map somewhere else, typically about three quarters of them here. For a cache pool, that means most cached entries are suddenly in the wrong place and requests miss the cache all at once. For sticky sessions, most users lose their server.
Consistent hashing
Consistent hashing limits that damage. Imagine a circle of hash values. Each server is hashed onto one or more points on the circle. To place a key, hash it onto the circle and walk clockwise to the first server point you meet.
When a server is added, it takes over only the keys between it and its counterclockwise neighbor. When one is removed, only its keys move to the next server. On average, adding a server to a pool of N moves about 1/(N+1) of the keys, instead of most of them.
Virtual nodes
With one point per server, the arcs between points are uneven, so some servers own much more of the circle. The fix is virtual nodes: each server is hashed at many points, often 100 to 200. Arcs average out and load spreads more evenly. Weights also become easy, since a stronger server gets more points.
import bisect
import zlib
def h(s):
return zlib.crc32(s.encode())
def build_ring(servers, vnodes=100):
ring = sorted((h(f"{s}#{i}"), s) for s in servers for i in range(vnodes))
return [p for p, _ in ring], [s for _, s in ring]
def pick(key, points, owners):
i = bisect.bisect(points, h(key)) % len(points)
return owners[i]
keys = [f"user{i}" for i in range(1000)]
p1, o1 = build_ring(["a", "b", "c"])
p2, o2 = build_ring(["a", "b", "c", "d"])
moved = sum(1 for k in keys if pick(k, p1, o1) != pick(k, p2, o2))
print(f"{moved} of {len(keys)} keys moved")Run both scripts and compare the counts. The ring version moves roughly a quarter of the keys.
Configuring it
NGINX enables hashing with the hash directive. Adding consistent selects the ring (ketama) method:
upstream app {
hash $request_uri consistent;
server 10.0.0.11:8080;
server 10.0.0.12:8080;
server 10.0.0.13:8080;
}HAProxy uses balance uri or balance hdr(...) with hash-type consistent:
backend cache
mode http
balance uri
hash-type consistent
server c1 10.0.0.21:8080 check
server c2 10.0.0.22:8080 checkCommon errors
- Hashing on client IP behind a proxy or NAT. Many users share one address, so one server gets a large share. Hash on a header such as the user ID instead.
- Forgetting health checks. When a server fails, its keys shift to its neighbor, which can overload it. Plan capacity for that.
- Using a key with few distinct values. Hashing on a field with three possible values can use at most three servers.
- Expecting perfect balance. Hashing is deterministic, not load-aware. Use least connections when balance matters more than affinity.
Exercise
A pool of 4 cache servers uses modulo hashing. You add a fifth server and the cache hit rate drops sharply. What change prevents this, and roughly what fraction of keys should move afterward?
Show answer
Switch to consistent hashing (with virtual nodes). Adding a fifth server then moves only about 1/5 of the keys, so about 80% of cached entries stay where they were.
Exercise
Why are virtual nodes used in a consistent hash ring?
Show answer
With one point per server the arcs are uneven, so load is skewed. Many points per server average out the arc sizes and spread keys more evenly. They also let you weight stronger servers with more points.