Skip to content

fix: make the consistent-hash strategy actually consistent (#131) - #271

Merged
scttfrdmn merged 1 commit into
mainfrom
feat/rendezvous-hashring
Aug 3, 2026
Merged

scttfrdmn merged 1 commit into
mainfrom
feat/rendezvous-hashring

Conversation

@scttfrdmn

Copy link
Copy Markdown
Owner

Closes #131.

The defect

selectConsistentHash was:

func (lb *LoadBalancer) selectConsistentHash(nodes []string, count int) ([]string, error) {
	// Simple consistent hash implementation
	// In practice, you'd use a proper consistent hash ring
	if len(nodes) <= count {
		return nodes, nil
	}
	return nodes[:count], nil
}

nodes arrives from selectTargetNodes, which builds it by ranging c.cluster.GetNodes() — a map,
whose iteration order Go randomizes per call. So the same key reached a different node on each call.
That is the one property consistent hashing exists to provide, and the one a per-node cache needs in
order to hit at all.

The fix

internal/distributed/hashring: rendezvous (HRW) hashing. Score every node against the key with
xxhash(nodeID + "#" + key), take the highest, break ties on node ID. No new go.mod entry —
cespare/xxhash/v2 was already an indirect dependency.

Removing a node moves only the keys that node owned, about 1/n, which is asserted with that bound
rather than described. Lookup is O(n) in nodes; the benchmark settles whether that matters:

BenchmarkLookup100Nodes-16        1533300      1555 ns/op    0 B/op   0 allocs/op
BenchmarkLookupN3Of100Nodes-16     381340      6109 ns/op  2832 B/op   5 allocs/op
BenchmarkLookup8Nodes-16         19270704       124.7 ns/op   0 B/op   0 allocs/op

Three orders of magnitude below the S3 round trip it precedes, so a sorted ring with virtual nodes
would be complexity spent on nothing.

A prerequisite the issue did not mention

LoadBalancer.SelectNodes(availableNodes []string, count int) never received the operation key, so
no implementation behind it could have hashed by key however it was written. It now takes one, which
makes the key mandatory at all five call sites in selectTargetNodes rather than something a
strategy could quietly do without.

selectTargetNodes also sorts its alive-node slice now. The ring sorts internally, so removing that
sort changes nothing a consistent-hash test can observe — verified by removing it — but round-robin
and the least-load tiebreak index the slice positionally, and for those the order the map happened
to be iterated in was the decision.

A test that could not have caught this

TestLoadBalancer_ConsistentHash asserted only the returned count, and its own doc comment described
the defect as the intended behavior: "returns the requested number of nodes from the front of the
list."
A count assertion passes on nodes[:count]. It now asserts that permuting the input does not
change the output, plus an end-to-end selectTargetNodes test that exercises the real randomized map
iteration rather than simulating it.

Verification

Seven mutations, all caught:

mutation caught by
selection reverted to a slice prefix TestLoadBalancer_ConsistentHash, TestSelectTargetNodes_IsOrderIndependent
alive nodes left unsorted TestSelectTargetNodes_SortsAliveNodes
hash separator removed TestSeparatorPreventsBoundaryCollisions
tie-break removed TestOutranksBreaksTiesByNodeID
Remove made a no-op 3 removal/rebalance tests
LookupN sorts by node instead of score TestLookupAgreesWithLookupN
Add made non-idempotent TestAddIsIdempotentAndSorted, FuzzLookupIsStable

Two of the seven were caught only after adding tests, which is the reason for running them rather
than predicting them:

  • The tie-break is unreachable through the public API — it needs a 64-bit score collision — so
    removing it passed every test in the file. sort.Slice is not stable, so on a collision the winner
    without it is whichever element the sort left first, i.e. the input-order dependence this whole
    change removes. Extracted as outranks so the rule is assertable directly, and Lookup now uses
    it too, so the two entry points cannot drift apart on a tie.
  • The sort needed an end-to-end round-robin test; the ring had been hiding its absence.

Gates: go build · go vet · gofmt -l 0 · full suite -race green · coverage gate 35 packages
at or above floor
, hashring at 100% with a floor to match · golangci-lint --new-from-merge-base 0 issues · standalone gosec finds nothing in the new code (the two
G404 hits in consensus.go:856,859 are pre-existing and untouched) · FuzzLookupIsStable 30M
executions clean.

selectConsistentHash was `return nodes[:count]` under a comment saying a real
ring belonged there. Its node slice comes from ranging a map, so the same key
reached a different node on each call — the one property consistent hashing
exists to provide, and the one a per-node cache needs in order to hit.

Replaced with a rendezvous (highest-random-weight) ring in
internal/distributed/hashring: score every node against the key, take the
highest, break ties on node ID. Removing a node moves only the keys it owned,
about 1/n, which is asserted with that bound rather than described. Lookup is
O(n) in nodes; the benchmark settles whether that matters at 1555 ns for 100
nodes and 125 ns for 8, zero allocations, three orders of magnitude under the
S3 round trip it precedes.

The issue's plan had a gap: LoadBalancer.SelectNodes never received the
operation key, so nothing behind it could have hashed by key however it was
implemented. It now takes one, which makes the key mandatory at all five call
sites rather than something a strategy could quietly do without.

selectTargetNodes also sorts its alive-node slice. The ring sorts internally,
so removing that sort changes nothing a consistent-hash test can observe —
verified by removing it — but round-robin and the least-load tiebreak index
positionally, and for those the order the map happened to be iterated in *was*
the decision.

The existing test asserted only the returned count, and its own comment
described the defect ("returns the requested number of nodes from the front of
the list") as the intended behavior. A count assertion cannot tell a ring from
a prefix, so it now asserts that permuting the input does not change the
output, which a prefix fails.

Seven mutations, all caught: slice-prefix selection, unsorted alive nodes,
missing hash separator, missing tie-break, no-op Remove, score-ignoring sort,
non-idempotent Add. Two of the seven were caught only after adding tests —
the tie-break is unreachable through the public API since it needs a 64-bit
score collision, so it is asserted on an extracted comparator; and the sort
needed an end-to-end round-robin test, since the ring had been hiding its
absence.

hashring is at 100% coverage with a floor to match, and FuzzLookupIsStable ran
30M executions clean.
@scttfrdmn
scttfrdmn merged commit 034aa3d into main Aug 3, 2026
24 checks passed
@scttfrdmn
scttfrdmn deleted the feat/rendezvous-hashring branch August 3, 2026 16:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A1-4: Replace fake consistent hash with rendezvous (HRW) hash ring

1 participant