Sub topic 10
Hash-based balancing and consistent hashing
This chapter assumes you know the balancing algorithms from the earlier chapters (round robin, weighted, least connections) and the difference between Layer 4 and Layer 7. It also assumes you can read a short Python script and an NGINX or HAProxy configuration file.
Why hash at all
Round robin and least connections ignore who is asking. Each request goes wherever there is room, so two requests from the same client usually land on different servers. That is fine for stateless backends. It is a problem when a server holds something worth reusing:
- An in-memory cache, where a repeated key should hit the server that already has it.
- A per-user or per-tenant working set, such as an open file or a loaded model.
- A connection-oriented session you would rather not pin with cookies.
Hash-based balancing picks the backend from a value in the request. The load balancer computes a hash of a chosen key and maps the result to a server. The same key gives the same server as long as the pool does not change. No table of sessions is stored, so the balancer stays nearly stateless and a second balancer computes the same answer.
Common keys:
| Key | Layer | Typical use |
|---|---|---|
| Client source IP | L4 or L7 | Crude stickiness without cookies |
| Request URI | L7 | Cache servers, so each object is cached on one node |
| A header, such as a tenant ID or API key | L7 | Per-tenant isolation |
| A cookie value | L7 | Stickiness driven by the application |
| Connection 4-tuple | L4 | Spreading flows evenly, as routers do with ECMP |
The simple approach: hash modulo N
The obvious mapping is server = servers[hash(key) % N], where N is the number of servers. It is fast and spreads keys evenly. Its weakness appears when N changes.
Suppose you have 3 servers and add a fourth. A key's index is now hash % 4 instead of hash % 3. For most hash values those two results differ. On average about 75% of keys move to a different server when going from 3 to 4. More generally, going from N to N+1 moves about N/(N+1) of the keys.
For a cache pool this is bad. Most cached objects suddenly sit on the wrong server, so the hit rate collapses. The misses all go to the origin database, which may overload exactly when you were trying to add capacity. A server crash causes the same problem, because N shrinks.
Consistent hashing
Consistent hashing is designed so that changing the pool moves only a small share of keys. The idea:
- Imagine the hash space as a circle (a ring). Hash values run from 0 to the maximum and wrap around.
- Hash each server's name onto the ring. Each server owns a point.
- To place a key, hash it onto the ring and walk clockwise until you reach a server's point. That server owns the key.
When you add a server, it takes over only the keys between its point and the previous point on the ring. Every other key stays where it was. When a server is removed, only its keys move, and they go to the next server clockwise. On average, adding or removing one of N servers moves about 1/N of the keys, instead of nearly all of them.
Virtual nodes
With one point per server, the arcs between points have uneven lengths. One server may own 50% of the ring and another 10%. When a server leaves, its entire load falls on a single neighbor.
The fix is virtual nodes. Each physical server is placed on the ring many times, for example 100 to 200 points, by hashing names like 10.0.0.11:8080#0, 10.0.0.11:8080#1, and so on. The arcs average out, so load is more even. A removed server's keys scatter across all the remaining servers instead of landing on one. Weights fit in naturally: give a larger server more virtual nodes.
The cost is memory and a slightly slower lookup, since the ring has servers × vnodes points. A binary search keeps lookups at O(log n), which is negligible for a pool of tens of servers.
Measuring the difference in code
This script builds a ring with virtual nodes and compares how many keys move under modulo hashing and under consistent hashing when a fourth server is added.
import bisect
import hashlib
def h(value):
return int(hashlib.md5(value.encode()).hexdigest(), 16)
class Ring:
def __init__(self, servers, vnodes=100):
self.vnodes = vnodes
self.points = [] # sorted hash positions
self.owner = {} # position -> server name
for server in servers:
self.add(server)
def add(self, server):
for i in range(self.vnodes):
position = h(f"{server}#{i}")
self.owner[position] = server
bisect.insort(self.points, position)
def remove(self, server):
for i in range(self.vnodes):
position = h(f"{server}#{i}")
del self.owner[position]
self.points.remove(position)
def get(self, key):
index = bisect.bisect(self.points, h(key)) % len(self.points)
return self.owner[self.points[index]]
def modulo_pick(servers, key):
return servers[h(key) % len(servers)]
keys = [f"user-{i}" for i in range(10000)]
before = ["s1", "s2", "s3"]
after = ["s1", "s2", "s3", "s4"]
moved_modulo = sum(
modulo_pick(before, k) != modulo_pick(after, k) for k in keys
)
ring = Ring(before)
placement = {k: ring.get(k) for k in keys}
ring.add("s4")
moved_ring = sum(placement[k] != ring.get(k) for k in keys)
print(f"modulo hashing moved {moved_modulo / len(keys):.0%} of keys")
print(f"consistent hashing moved {moved_ring / len(keys):.0%} of keys")Expect modulo hashing to move roughly 75% of the keys and the ring to move roughly 25%. The exact numbers vary slightly with the hash function and the number of virtual nodes. With the ring, every key that moved went to s4, and no key moved between the old servers.
Configuring it in NGINX and HAProxy
In NGINX the hash directive selects the key. Adding consistent switches from modulo to a ketama-style ring.
upstream cache {
hash $request_uri consistent;
server 10.0.0.21:8080;
server 10.0.0.22:8080;
server 10.0.0.23:8080;
}
server {
listen 80;
location / {
proxy_pass http://cache;
proxy_set_header Host $host;
}
}Without consistent, this upstream uses modulo hashing. Any change to the server list then reshuffles most URIs. The key can be any NGINX variable or text, such as $http_x_tenant_id or $remote_addr.
HAProxy chooses the key with the balance keyword and the mapping with hash-type.
backend cache
mode http
balance uri
hash-type consistent
option httpchk GET /healthz
server c1 10.0.0.21:8080 check weight 100
server c2 10.0.0.22:8080 check weight 100
server c3 10.0.0.23:8080 check weight 200Here balance uri hashes the request path. Other choices are balance source, balance hdr(X-Tenant-Id) and balance url_param user. The default hash-type is map-based, which is the modulo behavior described earlier. Setting hash-type consistent uses a ring, and the weights then control how many points each server gets. Server c3 takes about twice the share of keys.
Edge cases and failure modes
Health checks interact with hashing
When a server fails its health check, the balancer removes it from the pool. With a consistent ring, only the keys it owned move, and they go to its clockwise neighbors. When it recovers, those keys move back. During a flapping failure, those keys bounce between servers. This is another reason to require several consecutive successful checks before reinstating a server, as covered in the health checks chapter.
With map-based hashing, a single server going down can shift most keys. For cache pools, always use the consistent variant.
Hot keys and uneven load
Hashing balances keys, not load. If one URL or tenant receives 40% of the traffic, the single server that owns it takes 40% of the load, however many servers you add. Consistent hashing cannot fix that. Options include:
- Hash on a finer-grained key, such as URI plus a request-specific part.
- Cache the hot object in front of the balancer.
- Use bounded-load hashing. HAProxy's
hash-balance-factorcaps how far a server's load may exceed the average. When a server is over the cap, the request goes to the next server on the ring. NGINX has no direct equivalent in its open source edition.
Source-IP hashing behind NATs and proxies
Hashing on the client IP is a poor key when many users share one address, as with a corporate NAT or a mobile carrier gateway. All of them land on one server. If the balancer sits behind another proxy, it sees the proxy's address for every request. Hash on a forwarded header only when you trust whoever sets it, because a client can send a forged X-Forwarded-For to steer its own traffic.
Hash stickiness is not a guarantee
Hash-based routing is stable only while the pool is stable. Pool changes, even with a ring, move some keys. Do not store anything on a backend that you cannot afford to lose or rebuild. For state that must survive, use the persistence guidance from the session persistence chapter, or keep the state in a shared store.
Different balancers disagree
Two balancers in a high-availability pair route the same key identically only if they use the same algorithm, hash function, server names and order, and weights. NGINX and HAProxy use different ring layouts, so mixing them in one tier gives different mappings for the same pool. Keep the configuration for that tier identical, and generate it from one source.
Summary of when to choose what
| Situation | Choice |
|---|---|
| Stateless web or API tier | Round robin or least connections |
| Cache pool where hit rate matters | URI hash with consistent hashing |
| Per-tenant isolation or locality | Header hash with consistent hashing |
| Simple stickiness, trusted unique client IPs | Source hash, preferably consistent |
| Pool that never changes | Modulo hashing works, but consistent costs little |
Exercise
A cache tier of 4 servers uses hash $request_uri; in NGINX (no consistent). You add a fifth server and the cache hit rate drops sharply for several minutes. Explain why, estimate what share of keys moved, and give the one-line configuration change that reduces the effect next time.
Show answer
Without consistent, NGINX computes the hash modulo the number of servers. Going from 4 to 5 servers changes the divisor, so most keys map to a different server. The expected share moved is about N/(N+1) = 4/5, or roughly 80%. Those keys are now routed to servers that have not cached them, so the requests miss and go to the origin until the caches warm up. Change the line to hash $request_uri consistent;. With a ring, adding the fifth server moves only about 1/5 (20%) of the keys, all of them to the new server, and the rest of the cache stays valid.