Skip to content

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 NN 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 O(log⁡n)O(\log n) 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, L=∫ab1+f′(x)2 dxL = \int_a^b \sqrt{1 + f'(x)^2}\,dx for y=f(x)y = f(x), or ∫ab(dx/dt)2+(dy/dt)2 dt\int_a^b \sqrt{(dx/dt)^2 + (dy/dt)^2}\,dt 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 K/(N+1)K/(N+1) keys, all to the new node, where hash mod N moves 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 ⌈c⋅(m+1)/n⌉\lceil c \cdot (m+1)/n \rceil and prove that the bounded walk always ends.

The notation for this section:

SymbolMeaningType
h(x)h(x)the ring’s hash of a byte string, a position in [0,264)[0, 2^{64})uint64
NNnumber of member nodes (engines)integer
VVvirtual nodes per member (vnodes)integer, 160 in the gateway
KKnumber of keys (requests)integer
pjp_jthe fraction of the ring that node jj owns (its arc share)real, ∑jpj=1\sum_j p_j = 1

Treat [0,264)[0, 2^{64}) as a circle. Node engine-a with VV virtual nodes sits at the VV positions h(engine-a#0),…,h(engine-a#(V−1))h(\texttt{engine-a\#0}), \dots, h(\texttt{engine-a\#}(V-1)). A key xx belongs to the node of the first position ≥h(x)\ge h(x); if h(x)h(x) is past the largest position, it wraps around to the smallest. Node jj 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 pjp_j. With V=1V = 1 the arcs are very uneven; with VV positions per node the shares concentrate around 1/N1/N, with a spread that shrinks roughly like 1/V1/\sqrt{V}.

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 1469598103934665603714695981039346656037, and for each byte xor it in, then multiply by 10995116282111099511628211 modulo 2642^{64}.

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:

z←(z⊕(z≫30))⋅0xbf58476d1ce4e5b9,z←(z⊕(z≫27))⋅0x94d049bb133111eb,z←z⊕(z≫31).z \leftarrow (z \oplus (z \gg 30)) \cdot \texttt{0xbf58476d1ce4e5b9},\quad z \leftarrow (z \oplus (z \gg 27)) \cdot \texttt{0x94d049bb133111eb},\quad z \leftarrow z \oplus (z \gg 31).

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.

This is the property that gives consistent hashing its name. Add node N+1N+1. Its VV 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 K⋅pN+1K \cdot p_{N+1}, about K/(N+1)K/(N+1).

Compare hash mod N. Going from 8 to 9 buckets keeps a key only when h mod 8=h mod 9h \bmod 8 = h \bmod 9, which holds for about 1/91/9 of keys, so 8/98/9 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.

Minimal movement keeps caches warm, but it does nothing for a hot key. Let mm be the number of keys already placed (for the gateway: requests in flight plus queue depth, summed over nodes) and c≥1c \ge 1 a slack factor (affinity_load_factor, default 1.25). The capacity for placing one more key is

cap=⌈c⋅m+1n⌉.\mathrm{cap} = \left\lceil c \cdot \frac{m+1}{n} \right\rceil.

To place key xx, walk clockwise from h(x)h(x) and take the first distinct node whose load is below cap. Because the loads sum to mm and n⋅cap≥c(m+1)>mn \cdot \mathrm{cap} \ge c(m+1) > m, some node is below cap, so the walk always ends. The +1+1 counts the key being placed: without it, an empty ring has cap=0\mathrm{cap} = 0 and no node qualifies.

The guarantee, placing KK keys one by one, is that every node ends with at most ⌈cK/n⌉\lceil c K / n \rceil. 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.

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:

Labela#0b#0c#0a#1b#1c#1
position103050608095

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:

KeyhhFirst point ≥h\ge hOwner
k15a#0 at 10a
k255a#1 at 60a
k385c#1 at 95c
k497none, wrap to a#0 at 10a
k530b#0 at 30 (equal counts)b

Now apply bounded loads with c=1.25c = 1.25 and current loads a = 2, b = 0, c = 1. Then m=3m = 3, n=3n = 3, so cap=⌈1.25⋅4/3⌉=⌈1.667⌉=2\mathrm{cap} = \lceil 1.25 \cdot 4 / 3 \rceil = \lceil 1.667 \rceil = 2. 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.

package ring // import "tinyllm/ds/ring"
func FNV1a64(b []byte) uint64 // FNV-1a 64
func Mix64(z uint64) uint64 // SplitMix64 finalizer
func Hash64(b []byte) uint64 // Mix64(FNV1a64(b)): the default hash
func 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 panics
func (r *Ring) Add(node string) // idempotent
func (r *Ring) Remove(node string) // a non-member is a no-op
func (r *Ring) Len() int
func (r *Ring) Nodes() []string // sorted
func (r *Ring) Get(key []byte) (node string, ok bool) // ok false on an empty ring
func Capacity(total, n int, c float64) int // ceil(c*(total+1)/n); 0 when n <= 0
func (r *Ring) GetBounded(key []byte, load func(node string) int, c float64) (node string, ok bool) // c < 1 acts as 1

The 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.

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.

  1. Membership changes must move as few keys as possible. hash mod N ties every key to NN. 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.
  2. One position per node gives very uneven arcs, so each node gets VV positions (virtual nodes) and its share concentrates near 1/N1/N. The data structure is then a sorted array of points, and a lookup is a binary search for the first point at or after h(x)h(x), wrapping to index 0.
  3. 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).
  4. A hot key must not overload its owner. Placing one more key when mm are placed, no node should exceed ⌈c(m+1)/n⌉\lceil c(m+1)/n \rceil. A key whose owner is at the cap walks clockwise to the next distinct node below it. Since loads sum to m<n⋅capm < n \cdot \mathrm{cap}, such a node exists for c≥1c \ge 1, so the walk terminates within nn distinct nodes. In the worked example, cap is 2, a holds 2, so k1 moves on to b.
  5. When nobody is loaded the cap does not bind, so bounded lookup equals plain lookup and affinity is kept until it costs something.

Each is one or two lines and matches the formulas above; Go’s uint64 multiply is already mod 2642^{64}.

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 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
}

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
}

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
}

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.

Get is O(log⁡(NV))O(\log(NV)), a binary search over NVNV points. GetBounded adds O(N)O(N) to sum the loads and walks at most until NN distinct nodes are seen, typically a few points. Add is O(NVlog⁡(NV))O(NV \log(NV)) for the re-sort and Remove is O(NV)O(NV); both are rare (membership changes) next to lookups. Memory is NVNV points.

The alternatives each miss something. hash mod N has O(1)O(1) lookup, but a membership change remaps about (N−1)/N(N-1)/N of keys and empties every prefix cache at once. Rendezvous (highest random weight) hashing has the same minimal movement and no vnodes, but costs O(N)O(N) hashes per lookup, and with bounded loads it also needs a full ranking per key. Jump consistent hash and Maglev give O(1)O(1) 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.

A correct ring handles every case below, including a golden key-to-node map from the Python reference:

CaseKind of checkChecksWhy it matters downstream
The hand exampleunitowners of k1 to k5, the wrap, a key exactly on a positionthe definition the gateway and the Python reference share
The hand example’s bounded spillunitk1 skips the full a for b; k3 staysthe spill rule that protects a hot engine
Capacityunit⌈c(m+1)/n⌉\lceil c(m+1)/n \rceil on six cases, including n=0n = 0the bound every placement uses
Hash vectorsunitFNV-1a vectors, Mix64, Hash64, VnodeLabelPython and Go place nodes identically
An empty ringboundaryok = false from both lookups, before and after the last Removea gateway with no healthy worker answers 503, not a panic
Zero vnodesboundaryNew(0, nil) panicsa member with no position would never get a key
Add and Remove are idempotentunita repeated Add and a stranger’s Remove change no key; Len, sorted Nodesheartbeats re-announce workers every 2 s
Collisions break ties by nameboundaryequal positions go to the smaller name in either join orderreplicas agree on the ring
Insertion order is irrelevantproperty2000 keys map the same for two join ordersthe same
Add moves keys only to the new nodeproperty, statisticalmoved keys all go to the new node; their count is within 4 sd of KpnewK p_{\text{new}}; pnewp_{\text{new}} near 1/91/9caches stay warm when an engine joins
Remove moves only its keyspropertyonly the removed node’s keys movecaches stay warm when an engine dies
Keys spread by arc lengthstatisticalkey counts fit the arc shares: chi-square below 24.32 (7 df, p=10−3p = 10^{-3})the hash spreads keys uniformly
Bounded never exceeds capacitypropertydistinct keys, one hot key, three hot keys, c∈{1,1.25,2}c \in \{1, 1.25, 2\}: no node above ⌈cK/n⌉\lceil cK/n \rceilthe guarantee the gateway relies on
Bounded equals Get when unloadedpropertywith zero loads bounded and plain lookup agreeaffinity is kept until it costs something
Bounded clamps cc below oneboundaryc=0.5c = 0.5 places exactly like c=1c = 1a misconfigured factor cannot make placement impossible
Golden key-to-node mapgoldenevery 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; c<1c < 1 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:

PitfallSymptomHow the solution avoids it
no wrap: a key past the last position gets the last nodekeys near the top all pile on one nodefirst returns 0 when the search falls off the end
> instead of >= in the searcha key exactly on a position goes to the next nodefirst searches for pos >= x
capacity without the +1+1, <= instead of <, or dividing by vnodes instead of nodesan empty ring has capacity 0, or a node ends one key over the boundCapacity uses total+1 and divides by len(r.nodes); GetBounded requires load < limit and clamps c to 1
sorting by position onlytwo replicas that heard workers in a different order route a colliding key differentlyless breaks ties by node name, then copy index
Remove that forgets the member but keeps its positionskeys still route to a dead engineRemove filters the node’s points out of r.points
FNV-1 instead of FNV-1a, labels from 1, or no finalizerpositions 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 guarda panic when the last engine is evictedGet 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.

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:

  • 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 ⌈c(m+1)/n⌉\lceil c(m+1)/n \rceil 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.
  • 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 K/(N+1)K/(N+1) of KK keys, and every moved key goes to the new node; removing a node moves only its own keys.
  • Bounded loads cap every node at ⌈c⋅(m+1)/n⌉\lceil c \cdot (m+1)/n \rceil: 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#7 make 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.
  1. Why does the capacity formula have m+1m + 1 and not mm?
    AnswerThe 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.
  2. 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.
  3. Why does GetBounded skip points of nodes it has already seen?
    AnswerA 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.
  4. What exactly moves when a ninth node joins an eight-node ring, and why does nothing move between old nodes?
    AnswerOnly 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.
  5. Why finalize FNV-1a with Mix64 instead of using FNV-1a directly?
    AnswerLabels 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$.