Consistent Hashing for Load Balancing
Learn how consistent-hash rings, virtual nodes, and bounded-load policies reduce reassignment, and when sticky sessions still make sense.
Learn how consistent-hash rings, virtual nodes, and bounded-load policies reduce reassignment, and when sticky sessions still make sense.
Consistent Hashing for Load Balancing
Consistent hashing maps a stable key, such as a tenant ID or cache key, to a backend. When a backend joins or leaves, the mapping changes for part of the key space instead of being recalculated across the whole pool. That can reduce cache churn and make ownership more stable.
The mapping alone does not guarantee that every backend receives the same number of requests. Request frequency, connection duration, backend health, and key popularity still shape the load. Health checks and overload handling need their own rules.
How a hash ring maps keys
Imagine a range of hash values arranged in a circle. Hash each backend identity to one or more positions on the ring, then hash each key into the same range. A key goes to the first backend position clockwise from its hash. If the key falls after the last position, wrap around to the first.
from bisect import bisect_left
def choose_backend(key, ring_tokens, stable_hash):
"""ring_tokens is sorted as (token_hash, backend_id) pairs."""
if not ring_tokens:
raise ValueError("the ring has no backends")
token = stable_hash(key)
index = bisect_left(ring_tokens, (token, ""))
if index == len(ring_tokens):
index = 0
return ring_tokens[index][1]
The ring must use a stable hash function and a consistent representation of keys and backend IDs. If two clients serialize the same key differently or build different ring versions, they can send it to different backends. The lookup uses binary search over the sorted token list; keeping that list sorted is part of the ring’s setup work.
When a backend is added, it takes keys from the clockwise interval between its new position and the preceding position. Removing a backend moves its keys to the next backend on the ring. Most keys keep their previous assignment, though the exact fraction depends on token placement and backend weights. Google Cloud documents consistent hashing as a way to reduce mapping disruption when eligible backends or weights change in its regional external passthrough Network Load Balancer documentation.
Virtual nodes reduce placement gaps
With one position per backend, a hash can leave uneven gaps around the ring. A backend with a large interval receives more keys than one with a small interval. Virtual nodes give each physical backend several positions, usually by hashing an identity such as backend-a:0, backend-a:1, and backend-a:2.
More positions tend to smooth the distribution of keys across equivalent backends. They also increase ring size and setup work, and they do not ensure equal request traffic. A tenant with unusually popular keys can still overload its assigned backend. Weighted pools need token placement that reflects backend capacity, and operators should measure actual traffic before changing weights.
Google’s Maglev network load balancer combines consistent hashing with connection tracking so packets from an established connection continue to reach the selected service endpoint while that endpoint remains usable. Other ring-based systems can select endpoints differently. See the Maglev paper for its design and operating constraints.
Consistent hashing and sticky sessions solve different problems
Consistent hashing assigns a key to a backend. The key might be a cache key, tenant, or shard identifier. Sticky sessions instead try to send a client’s later requests to the same backend, often using a cookie or a hash of network fields.
IP-based affinity can skew traffic when many clients share an address behind a corporate proxy, carrier gateway, or NAT. Google Cloud warns that an intermediate NAT or proxy can change the apparent source IP and that many clients sharing one effective source address can concentrate traffic on a subset of backends. Client IP affinity can also break when a backend becomes unhealthy or leaves the pool. It should not be used for authentication or as a substitute for storing session state safely. See Google’s client IP affinity guidance.
If any application instance can read session state from a shared store, such as Redis, routing can move freely without pinning a client to one process. Use affinity only when the application has a concrete reason for it and the loss of affinity has a defined recovery path. The load-balancing decision guide compares affinity with other routing choices, and load balancing fundamentals covers L4 and L7 responsibilities.
Bounded load adds a capacity rule
Basic consistent hashing limits how much key ownership changes when the pool changes, but its distribution is similar to random assignment. Some backends can receive many more keys than average, especially in smaller or changing pools. Virtual nodes help with placement variance; they do not impose a hard capacity ceiling.
Bounded-load consistent hashing adds a capacity limit to the assignment process. In a simplified model, each backend gets a limit based on its capacity and the average number of assigned keys. If the first clockwise backend has reached that limit, the allocator continues around the ring until it finds one with room. Google’s research describes a formal algorithm that balances limited reassignment with a bound on assigned load under its stated model. The exact guarantees depend on the algorithm’s assumptions; a short “skip full servers” loop is not a replacement for that analysis.
This rule limits the number of assigned keys, not the number of requests or the work those keys generate. A single hot key can still dominate a backend. Bounded assignment also needs consistent capacity data and a coordinated view of ownership. It is a better fit for shard or cache ownership than for a request proxy that must make a stateless choice from live health and connection data.
The Google research paper on consistent hashing with bounded loads explains the trade-off: the algorithm constrains maximum assignment load while keeping the number of moved clients small as clients or servers change. Those guarantees depend on that algorithm and its stated model.
When to use it
Consistent hashing is useful when a stable key should usually land on the same backend and moving it has a cost. Common examples include cache placement, partition ownership, and connection routing. It is less useful when requests are stateless and backend work varies sharply by request; round robin or least-request policies may use capacity more directly.
Before adopting it, decide what the key represents, how membership changes are published, how unhealthy backends leave the ring, and what happens to keys that move. Then test the actual key distribution and request volume. If one tenant or cache key is much hotter than others, a stable mapping can preserve that hotspot as reliably as it preserves the mapping.
Conclusion
Consistent hashing reduces reassignment when backend membership changes. Virtual nodes can smooth key placement, while bounded-load algorithms add an explicit capacity constraint. Neither guarantees balanced request volume, so measure the real workload and keep health and overload handling in the routing design.
Category
Related Posts
Load Balancing Algorithms: Workloads and Benchmarks
Compare round robin, least-connections, and two-choice routing under mixed request durations with a reproducible workload and operational trade-offs.
API Clients, Servers, and Network Boundaries Explained
Understand what API clients and servers each own, how network boundaries fail, and how timeouts, retries, and trust boundaries shape reliable integrations.
Asynchronous Replication: Lag, Failover, and Freshness
Learn how asynchronous database replication affects read freshness, failover data loss, lag monitoring, and recovery choices during network partitions.