From 8ac33515949ceabb623ac25fed9667a72e2ec957 Mon Sep 17 00:00:00 2001 From: jvoisin Date: Mon, 29 Jun 2026 15:16:34 +0200 Subject: [PATCH] reverseproxy: use xxhash.Sum64String in load balancer hashing The hash helper used by hostByHashing (ip_hash, header, cookie, and query hashing policies) created a new xxhash.Digest and converted the input to []byte on every call, i.e. per upstream per request. Replace it with the stateless xxhash.Sum64String, which hashes the string in a single pass. Adds a BenchmarkHostByHashing benchmark, as per policy, even though it's a tad silly. The only change is sec/op (484.2n -> 407.3n (-15.87%)) from skipping the digest struct initialization and Write bookkeeping. Allocations are unchanged, since escape analysis already stack-allocated the Digest and the []byte conversion. --- .../caddyhttp/reverseproxy/hash_bench_test.go | 18 ++++++++++++++++++ .../reverseproxy/selectionpolicies.go | 4 +--- 2 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 modules/caddyhttp/reverseproxy/hash_bench_test.go diff --git a/modules/caddyhttp/reverseproxy/hash_bench_test.go b/modules/caddyhttp/reverseproxy/hash_bench_test.go new file mode 100644 index 000000000..7b94dc34e --- /dev/null +++ b/modules/caddyhttp/reverseproxy/hash_bench_test.go @@ -0,0 +1,18 @@ +package reverseproxy + +import ( + "strconv" + "testing" +) + +func BenchmarkHostByHashing(b *testing.B) { + pool := make(UpstreamPool, 0, 8) + for i := 0; i < 8; i++ { + pool = append(pool, &Upstream{Host: new(Host), Dial: "10.0.0." + strconv.Itoa(i) + ":8080"}) + } + const key = "192.168.1.100" + b.ReportAllocs() + for b.Loop() { + _ = hostByHashing(pool, key) + } +} diff --git a/modules/caddyhttp/reverseproxy/selectionpolicies.go b/modules/caddyhttp/reverseproxy/selectionpolicies.go index cc42b7a3b..392e2b1ee 100644 --- a/modules/caddyhttp/reverseproxy/selectionpolicies.go +++ b/modules/caddyhttp/reverseproxy/selectionpolicies.go @@ -869,9 +869,7 @@ func hostByHashing(pool []*Upstream, s string) *Upstream { // hash calculates a fast hash based on s. func hash(s string) uint64 { - h := xxhash.New() - _, _ = h.Write([]byte(s)) - return h.Sum64() + return xxhash.Sum64String(s) } func loadFallbackPolicy(d *caddyfile.Dispenser) (json.RawMessage, error) {