15.9 A consistent hash ring with bounded loads
The gateway in Worker registry, routing, cascades, failover in AI Engineering talks to more than one engine. Every engine keeps a prefix cache (Radix prefix cache in AI Engineering): when two requests start with the same system prompt, the second one skips recomputing that prefix, but only if it lands on the same engine. Round robin scatters them, so each engine recomputes every prefix. A plain hash(prefix) mod N keeps them together until an engine dies or joins; then changes and almost every prefix moves, emptying every cache at once.
Concepts from other sections (11)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Prefix cache: a map from token prefixes of past prompts to the KV blocks already computed for them. Read more: 21.4 A radix prefix cache in AI Engineering
- tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot in AI Engineering
- Binary search: a search that keeps an interval known to contain the answer and halves it with one comparison per step, taking steps; it needs a monotonic predicate, not necessarily a sorted array. Read more: Chapter 5: Binary search
- FNV-1a: a byte-at-a-time hash that XORs each byte in and then multiplies by a prime. Read more: 15.8 A Bloom filter
- SplitMix64 finalizer (mix64): a bijection on 64-bit words that mixes every input bit into every output bit. Read more: 15.8 A Bloom filter
- Block hash: a hash over token ids chained with the parent hash, independent of the payload format. Read more: 12.5 The KV format v2 migration in Systems Engineering
- SplitMix64: the mixer used to derive child seeds that depend only on the seed and the purpose. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python in Mathematics
- Total order: an order in which any two distinct elements compare one way or the other; here, by value and then by index. Read more: 15.4 Heap top-k in C
- Membership change: adding or removing replicas, which must not happen while the cluster is partitioned. Read more: 12.13 A Raft partition (optional) in Systems Engineering
- Arc length: the length of a curve, for , or for a parametric curve: the integral of speed. Read more: Chapter 8: Calculus 2 in Mathematics
- Load balancer: a component that spreads traffic across instances of a service by round-robin, least connections, or consistent hashing, at layer 4 (TCP) or layer 7 (HTTP). Read more: Chapter 1: System Design in Systems Engineering
Routing also has to survive a hot prefix. If half the traffic shares one system prompt, the engine that owns it saturates while the others idle. This section builds the data structure that solves all three problems: a consistent hash ring with bounded loads. It places every node at many pseudo-random positions on a ring, gives each key to the next node clockwise, and caps every node’s load so that a hot key spills over to its neighbours instead of melting one replica.
You will need the Go primer from Programming and Algorithms and the balls-into-bins problems in Mathematics. There is no separate interface file: the API given below, its hash vectors, and its tie rule are what every implementation (Go, and the Python reference that generated the golden key-to-node map) must reproduce. The solution is ring.go.
Learning objectives
- Place nodes on a ring with virtual nodes and find a key’s owner by binary search, with wrap-around.
- Show that adding a node moves only about keys, all to the new node, where
hash mod Nmoves almost all of them.- Explain why bare FNV-1a clusters on vnode labels and how the SplitMix64 finalizer fixes it.
- Make the ring a function of its member set alone by ordering points totally.
- Cap every node at and prove that the bounded walk always ends.
Positions on a ring
Section titled “Positions on a ring”The notation for this section:
| Symbol | Meaning | Type |
|---|---|---|
| the ring’s hash of a byte string, a position in | uint64 | |
| number of member nodes (engines) | integer | |
virtual nodes per member (vnodes) | integer, 160 in the gateway | |
| number of keys (requests) | integer | |
| the fraction of the ring that node owns (its arc share) | real, |
Treat as a circle. Node engine-a with virtual nodes sits at the positions . A key belongs to the node of the first position ; if is past the largest position, it wraps around to the smallest. Node therefore owns the arcs that end at its positions, and if keys hash uniformly, the expected fraction of keys it receives is its arc share . With the arcs are very uneven; with positions per node the shares concentrate around , with a spread that shrinks roughly like .
The hash
Section titled “The hash”The ring needs a hash that any language can reproduce exactly, because the Go ring must place every key exactly as a Python reference does. So it starts from FNV-1a 64, the same function as the KV block hash: start at , and for each byte xor it in, then multiply by modulo .
FNV-1a is weak on short inputs that differ only in their last bytes. engine-0#7 and engine-0#8 differ in one byte, which the final multiply spreads over only part of the word, and the positions cluster: measured on 8 nodes and 160 vnodes, shares range from 3.6% to 22%. So the ring finalizes the hash with the SplitMix64 mix from Modular arithmetic, hashing, and PCG32:
Hash64(b) = Mix64(FNV1a64(b)) is the default hash for both labels and keys.
Two positions can be equal, through a collision or a deliberately coarse test hash. The ring orders points by (position, node name, copy index), so the result never depends on the order in which nodes were added. Two gateway replicas that heard the heartbeats in a different order still agree on every key.
What moves when membership changes
Section titled “What moves when membership changes”This is the property that gives consistent hashing its name. Add node . Its new positions cut existing arcs; a key moves exactly when its hash falls into one of the new node’s arcs, and then it moves to the new node. No key moves between two old nodes. The expected number of moved keys is , about .
Compare hash mod N. Going from 8 to 9 buckets keeps a key only when , which holds for about of keys, so of the caches go cold. Removing a node from the ring is the mirror image of adding one: only its keys move, each to the next position clockwise.
Bounded loads
Section titled “Bounded loads”Minimal movement keeps caches warm, but it does nothing for a hot key. Let be the number of keys already placed (for the gateway: requests in flight plus queue depth, summed over nodes) and a slack factor (affinity_load_factor, default 1.25). The capacity for placing one more key is
To place key , walk clockwise from and take the first distinct node whose load is below cap. Because the loads sum to and , some node is below cap, so the walk always ends. The counts the key being placed: without it, an empty ring has and no node qualifies.
The guarantee, placing keys one by one, is that every node ends with at most . This is the balls-into-bins bound turned into a rule. When loads are all zero, bounded and plain lookup agree, so affinity is kept until it actually costs something.
Working it by hand
Section titled “Working it by hand”Take three nodes a, b, c with two virtual nodes each, and a hash given as a table so every number is checkable on paper:
| Label | a#0 | b#0 | c#0 | a#1 | b#1 | c#1 |
|---|---|---|---|---|---|---|
| position | 10 | 30 | 50 | 60 | 80 | 95 |
Sorted, the ring reads a 10, b 30, c 50, a 60, b 80, c 95, then wraps to a 10. Five keys find their owners like this:
| Key | First point | Owner | |
|---|---|---|---|
k1 | 5 | a#0 at 10 | a |
k2 | 55 | a#1 at 60 | a |
k3 | 85 | c#1 at 95 | c |
k4 | 97 | none, wrap to a#0 at 10 | a |
k5 | 30 | b#0 at 30 (equal counts) | b |
Now apply bounded loads with and current loads a = 2, b = 0, c = 1. Then , , so . Key k1’s owner a has load 2, not below 2, so the walk continues clockwise from a#0 at 10 to b#0 at 30: b has load 0, so GetBounded(k1) = b. Key k3’s owner c has load 1 < 2 and keeps it.
The interface
Section titled “The interface”package ring // import "tinyllm/ds/ring"
func FNV1a64(b []byte) uint64 // FNV-1a 64func Mix64(z uint64) uint64 // SplitMix64 finalizerfunc Hash64(b []byte) uint64 // Mix64(FNV1a64(b)): the default hashfunc VnodeLabel(node string, idx int) []byte // "<node>#<idx>", idx from 0
type Ring struct{ /* unexported */ }func New(vnodes int, h func([]byte) uint64) *Ring // h nil = Hash64; vnodes < 1 panicsfunc (r *Ring) Add(node string) // idempotentfunc (r *Ring) Remove(node string) // a non-member is a no-opfunc (r *Ring) Len() intfunc (r *Ring) Nodes() []string // sortedfunc (r *Ring) Get(key []byte) (node string, ok bool) // ok false on an empty ringfunc Capacity(total, n int, c float64) int // ceil(c*(total+1)/n); 0 when n <= 0func (r *Ring) GetBounded(key []byte, load func(node string) int, c float64) (node string, ok bool) // c < 1 acts as 1The hash vectors every implementation must match are FNV1a64("") = 0xcbf29ce484222325, FNV1a64("a") = 0xaf63dc4c8601ec8c, and FNV1a64("foobar") = 0x85944171f73967e8. The ring is not safe for concurrent use; the gateway holds its own lock around it. The implementation uses only the standard library.
Building it step by step
Section titled “Building it step by step”Read the solution in the order it was designed: the hashes (checked against the vectors above), then Add and Get on the worked example, then GetBounded. Five observations get you there.
- Membership changes must move as few keys as possible.
hash mod Nties every key to . Placing nodes and keys in one hash space and giving each key to the next node clockwise ties a key only to its neighbourhood: adding a node steals only the arcs its positions cut. - One position per node gives very uneven arcs, so each node gets positions (virtual nodes) and its share concentrates near . The data structure is then a sorted array of points, and a lookup is a binary search for the first point at or after , wrapping to index 0.
- Every gateway replica must compute the same ring, whatever order it heard about nodes. The hash is fixed (FNV-1a for portability, finalized with SplitMix64 because bare FNV-1a clusters on labels that differ in their last byte), the labels are fixed (
node#idx, idx from 0), and equal positions are ordered by (node name, copy index). - A hot key must not overload its owner. Placing one more key when are placed, no node should exceed . A key whose owner is at the cap walks clockwise to the next distinct node below it. Since loads sum to , such a node exists for , so the walk terminates within distinct nodes. In the worked example, cap is 2,
aholds 2, sok1moves on tob. - When nobody is loaded the cap does not bind, so bounded lookup equals plain lookup and affinity is kept until it costs something.
The hashes
Section titled “The hashes”Each is one or two lines and matches the formulas above; Go’s uint64 multiply is already mod .
const ( fnvOffset uint64 = 14695981039346656037 fnvPrime uint64 = 1099511628211)
func FNV1a64(b []byte) uint64 { h := fnvOffset for _, c := range b { h ^= uint64(c) // xor first: FNV-1a, not FNV-1 h *= fnvPrime } return h}
func Mix64(z uint64) uint64 { z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9 z = (z ^ (z >> 27)) * 0x94d049bb133111eb return z ^ (z >> 31)}
func Hash64(b []byte) uint64 { return Mix64(FNV1a64(b)) } // spreads FNV's clustered outputs
// "engine-a#0", "engine-a#1", ...: copies numbered from 0, in decimal.func VnodeLabel(node string, idx int) []byte { return []byte(node + "#" + strconv.Itoa(idx))}The ring’s state
Section titled “The ring’s state”The ring is a sorted slice of points and a set of members. less is the total order that makes the slice independent of insertion order.
type point struct { pos uint64 node string idx int}
type Ring struct { vnodes int h Hash points []point // sorted by (pos, node, idx) nodes map[string]bool // the members}
func less(a, b point) bool { if a.pos != b.pos { return a.pos < b.pos } if a.node != b.node { return a.node < b.node // a collision goes to the smaller name, on every replica } return a.idx < b.idx}Membership
Section titled “Membership”Add is idempotent through the member set (heartbeats repeat), and re-sorts with the total order. Remove must drop the points as well as the member, or keys would still route to a dead engine; it filters in place.
func (r *Ring) Add(node string) { if r.nodes[node] { return // re-announced: nothing changes } r.nodes[node] = true for i := 0; i < r.vnodes; i++ { r.points = append(r.points, point{pos: r.h(VnodeLabel(node, i)), node: node, idx: i}) } sort.Slice(r.points, func(i, j int) bool { return less(r.points[i], r.points[j]) })}
func (r *Ring) Remove(node string) { if !r.nodes[node] { return } delete(r.nodes, node) kept := r.points[:0] // reuse the backing array; order is preserved, so no re-sort for _, p := range r.points { if p.node != node { kept = append(kept, p) } } r.points = kept}Lookup
Section titled “Lookup”sort.Search finds the first point with pos >= x; >= (not >) is what makes a key exactly on a position belong to that position, as k5 does in the worked example. Falling off the end wraps to 0.
func (r *Ring) first(x uint64) int { i := sort.Search(len(r.points), func(i int) bool { return r.points[i].pos >= x }) if i == len(r.points) { return 0 // past the largest position: wrap around } return i}
func (r *Ring) Get(key []byte) (node string, ok bool) { if len(r.points) == 0 { return "", false // no healthy worker: the caller answers 503 } return r.points[r.first(r.h(key))].node, true}Bounded loads
Section titled “Bounded loads”The cap divides by members, not points, and counts the key being placed. The walk skips points of nodes already checked, and stops once every member has been seen.
func Capacity(total, n int, c float64) int { if n <= 0 { return 0 } return int(math.Ceil(c * float64(total+1) / float64(n))) // +1: the key being placed}
func (r *Ring) GetBounded(key []byte, load func(node string) int, c float64) (node string, ok bool) { if len(r.points) == 0 { return "", false } if c < 1 { c = 1 // below 1 no node may be below the cap: placement would be impossible } total := 0 for n := range r.nodes { total += load(n) } limit := Capacity(total, len(r.nodes), c) start := r.first(r.h(key)) seen := make(map[string]bool, len(r.nodes)) for k := 0; k < len(r.points) && len(seen) < len(r.nodes); k++ { p := r.points[(start+k)%len(r.points)] // clockwise, wrapping if seen[p.node] { continue // a node is judged once, at its first point on the walk } seen[p.node] = true if load(p.node) < limit { // strictly below: placing makes it at most the cap return p.node, true } } // Unreachable for c >= 1 (some node is below the average); keep the // plain owner rather than failing a request. return r.points[start].node, true}The full solution is ring.go.
Why this design
Section titled “Why this design”Get is , a binary search over points. GetBounded adds to sum the loads and walks at most until distinct nodes are seen, typically a few points. Add is for the re-sort and Remove is ; both are rare (membership changes) next to lookups. Memory is points.
The alternatives each miss something. hash mod N has lookup, but a membership change remaps about of keys and empties every prefix cache at once. Rendezvous (highest random weight) hashing has the same minimal movement and no vnodes, but costs hashes per lookup, and with bounded loads it also needs a full ranking per key. Jump consistent hash and Maglev give lookups from a table, but jump hash only supports removing the last bucket, and Maglev’s table must be rebuilt on every change; neither has a natural clockwise walk for the bounded-loads spill. Inserting points with a binary-search insert instead of re-sorting would be asymptotically better for Add, but sort.Slice over a few thousand points takes microseconds and keeps the code obviously correct.
Three tradeoffs are accepted. The ring is not safe for concurrent use; the gateway holds its own lock. GetBounded calls load once per member to sum loads, so the load function must be cheap. And the final fallback returns the plain owner instead of an error, which only matters if a caller passes inconsistent loads.
Testing it and what can go wrong
Section titled “Testing it and what can go wrong”A correct ring handles every case below, including a golden key-to-node map from the Python reference:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| The hand example | unit | owners of k1 to k5, the wrap, a key exactly on a position | the definition the gateway and the Python reference share |
| The hand example’s bounded spill | unit | k1 skips the full a for b; k3 stays | the spill rule that protects a hot engine |
| Capacity | unit | on six cases, including | the bound every placement uses |
| Hash vectors | unit | FNV-1a vectors, Mix64, Hash64, VnodeLabel | Python and Go place nodes identically |
| An empty ring | boundary | ok = false from both lookups, before and after the last Remove | a gateway with no healthy worker answers 503, not a panic |
| Zero vnodes | boundary | New(0, nil) panics | a member with no position would never get a key |
| Add and Remove are idempotent | unit | a repeated Add and a stranger’s Remove change no key; Len, sorted Nodes | heartbeats re-announce workers every 2 s |
| Collisions break ties by name | boundary | equal positions go to the smaller name in either join order | replicas agree on the ring |
| Insertion order is irrelevant | property | 2000 keys map the same for two join orders | the same |
| Add moves keys only to the new node | property, statistical | moved keys all go to the new node; their count is within 4 sd of ; near | caches stay warm when an engine joins |
| Remove moves only its keys | property | only the removed node’s keys move | caches stay warm when an engine dies |
| Keys spread by arc length | statistical | key counts fit the arc shares: chi-square below 24.32 (7 df, ) | the hash spreads keys uniformly |
| Bounded never exceeds capacity | property | distinct keys, one hot key, three hot keys, : no node above | the guarantee the gateway relies on |
| Bounded equals Get when unloaded | property | with zero loads bounded and plain lookup agree | affinity is kept until it costs something |
| Bounded clamps below one | boundary | places exactly like | a misconfigured factor cannot make placement impossible |
| Golden key-to-node map | golden | every case of a golden map generated by the Python reference (plain, removals, bounded with load feedback) | any implementation of the ring routes identically |
A model test suite in package ring_test (the owner is the first point clockwise and wraps; an empty ring says nobody; Remove moves only its keys; the capacity formula; bounded placement respects capacity with a hot key; acts as 1; ties go to the smaller name; the hash is FNV-1a then SplitMix) is in ring_learner_test.go.
The pitfalls are mostly off-by-one choices with large consequences:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| no wrap: a key past the last position gets the last node | keys near the top all pile on one node | first returns 0 when the search falls off the end |
> instead of >= in the search | a key exactly on a position goes to the next node | first searches for pos >= x |
capacity without the , <= instead of <, or dividing by vnodes instead of nodes | an empty ring has capacity 0, or a node ends one key over the bound | Capacity uses total+1 and divides by len(r.nodes); GetBounded requires load < limit and clamps c to 1 |
| sorting by position only | two replicas that heard workers in a different order route a colliding key differently | less breaks ties by node name, then copy index |
| Remove that forgets the member but keeps its positions | keys still route to a dead engine | Remove filters the node’s points out of r.points |
| FNV-1 instead of FNV-1a, labels from 1, or no finalizer | positions differ from the Python reference; with bare FNV the shares range from 4% to 22% | FNV1a64 xors before multiplying, VnodeLabel counts from 0, Hash64 applies Mix64 |
indexing an empty slice, or no vnodes guard | a panic when the last engine is evicted | Get and GetBounded return ok = false on an empty ring; New panics on vnodes < 1 |
Warning: Sorting points by position alone works on one machine and fails in production: two gateway replicas that learned about engines in different orders will disagree about colliding keys, and the same prefix will warm two caches.
Where this leads
Section titled “Where this leads”In Worker registry, routing, cascades, failover, route_policy = "affinity" keys GetBounded by the first prompt block, with load equal to requests in flight plus queue depth. That is what lets the multi-engine gateway keep prefix caches warm.
Production systems that use these ideas:
- Envoy’s
ring_hashload balancer adds a minimum ring size, per-host weights, and hash policies on headers; see Envoy load balancers (free). - HAProxy’s
hash-balance-factorand Google Cloud Pub/Sub have run the bounded-loads rule in production since 2017; see Vimeo engineering: Improving load balancing with a new consistent-hashing algorithm (free). - Maglev hashing and jump consistent hash give lookups from a precomputed table with no memory for vnodes; see Maglev (NSDI 2016) (free).
- The llm-d inference scheduler and the SGLang router use KV-cache-aware scoring instead of a hash of the prefix; see llm-d (free).
Further reading
Section titled “Further reading”- Karger et al., Consistent Hashing and Random Trees (STOC 1997).
- Mirrokni, Thorup, Zadimoghaddam, Consistent Hashing with Bounded Loads (SODA 2018).
Key terms
Section titled “Key terms”- Consistent hashing: placing nodes and keys in one hash space so that a membership change moves only nearby keys.
- Virtual node (vnode): one of a node’s many positions on the ring, used to even out arc shares.
- Arc share: the fraction of the ring a node owns, and so the expected fraction of keys it receives.
- Bounded loads: a cap of per node, with over-cap keys walking clockwise to the next node below it.
- Affinity routing: sending requests with the same prefix to the same engine so its prefix cache stays warm.
Summary
Section titled “Summary”- A ring places every node at many pseudo-random positions (virtual nodes) and gives a key to the first position at or clockwise after the key’s own hash; past the top it wraps.
- Adding a node moves only the keys that land in its new arcs, about of keys, and every moved key goes to the new node; removing a node moves only its own keys.
- Bounded loads cap every node at : a key whose owner is full walks clockwise to the next node below the cap, so a hot prefix spills over instead of melting one replica.
- Short labels such as
engine-0#7make bare FNV-1a cluster; finalizing with the SplitMix64 mix spreads them, and ties between equal positions go to the smaller node name, so every gateway replica computes the same ring.
Review questions
Section titled “Review questions”- Why does the capacity formula have and not ?
Answer
The cap is for placing one more key. With $m$, an empty ring would have $\mathrm{cap} = 0$ and no node would be "below cap", so nothing could be placed. With $m + 1$, $n \cdot \mathrm{cap} \ge c(m+1) > m$ for $c \ge 1$, so the loads (which sum to $m$) cannot all be at the cap: some node is below it and the walk ends. - Why are points ordered by (position, node, index) and not just by position?
Answer
`sort.Slice` is not stable, and even a stable sort would keep whatever order nodes were added in. Two gateway replicas that heard heartbeats in different orders would then disagree on which node owns a key that hashes to a collided position, and the same prefix would go to different engines depending on which replica handled it. A total order on points makes the ring a function of the member set alone. - Why does
GetBoundedskip points of nodes it has already seen?Answer
A node's load does not change between its points; if it was at the cap at its first point on the walk, it is at the cap at all of them. Skipping keeps the walk to at most $N$ distinct checks and makes "the next node clockwise" mean the next *different* node, which is the rule the bounded-loads definition states. - What exactly moves when a ninth node joins an eight-node ring, and why does nothing move between old nodes?
Answer
Only keys whose hash falls in one of the new node's arcs, the stretches just before each of its $V$ new positions, move, and they move to the new node. For every other key, the first point at or after its hash is unchanged, because the new points are not between that hash and its old owner's point. That is about $K/9$ keys, against about $8K/9$ for `hash mod N` going from 8 to 9. - Why finalize FNV-1a with
Mix64instead of using FNV-1a directly?Answer
Labels like `engine-0#7` and `engine-0#8` differ in one late byte, and FNV-1a's last multiply spreads that difference over only part of the word, so the positions of one node's vnodes cluster. Measured on 8 nodes with 160 vnodes, bare FNV gives shares from 3.6% to 22%. SplitMix64 makes every input bit affect every output bit, so the positions spread and shares concentrate near $1/N$.