Repository navigation
perf(mesh-dns): pool upstream UDP sockets on the forward path instead of dialing per query (#674) - #676
Merged
Conversation
… of dialing per query (#674) Continuous profiling put net.(*Dialer).DialContext at 20.97% of the standalone mesh-DNS daemon's CPU — MORE than the exchange it exists to serve (18.47%). miekg/dns's Client.Exchange dials, exchanges and closes on every call, so every forwarded query paid a full socket setup on a process that sits on the critical path of every managed pod's DNS. The forward path now keeps K (default 8) already-connected UDP sockets per upstream. A query takes a slot with sync.Mutex.TryLock and never Lock: a busy slot is skipped, and an all-busy pool falls back to exactly the pre-#674 cold dial. The pool can therefore only ever remove work from a query's path, never add tail latency to it. One query at a time per socket, so ExchangeWithConn's packet-conn ID drain is the right primitive and no ID demultiplexing of our own is needed. Any exchange error retires the socket; only a success keeps it. Two independent rotation budgets (a jittered ~30s, or 1000 queries) bound both the source-port reuse window and the lifetime of a conntrack entry pinning the kube-dns ClusterIP to one backend pod — a backend roll black-holes datagrams with no ICMP at all. The TCP leg is deliberately untouched: negligible volume, and on a stream conn ExchangeWithConn returns ErrId instead of draining a mismatched transaction ID, so a late reply on a pooled TCP socket would poison the next query on it. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
bpalermo
force-pushed
the
fix/674-mesh-dns-forward-pool
branch
from
September 4, 2026 21:04
8380942 to
4c571bd
Compare
bpalermo
added a commit
that referenced
this pull request
Sep 4, 2026
newCNIMetrics has been at cognitive complexity 16 against the lint limit of 15 since #672 (cf68f1b) added the prune_breaker_engaged and storage.stale_pods gauges as its fifteenth and sixteenth sequential error-checked registrations. That PR's CI test job passed, so the violation stayed dormant on main until any PR that put //agent/internal/cni/server back in the bazel-diff impact set — which is exactly what #676 (mesh-dns) and the #667 branch now do, and both go red on it. Pure mechanical extraction into registerSweepInstruments (ghost-sweep counters and the prune-breaker gauge) and registerLifecycleInstruments (the unmeshed and storage gauges, liveness instruments, identity-override counter). No metric names, descriptions, units or registration order change. Verified with fail_on_violation on //agent/internal/cni/server/... and the package tests. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
bpalermo
added a commit
that referenced
this pull request
Sep 4, 2026
newCNIMetrics is at cognitive complexity 16 against the lint limit of 15 on main, and no PR ever failed CI for it. #671 (763f5b3) added the fifteenth registration; #672 was branched before #671 merged, added two more to a file it saw at 13, and its CI head (f5d540a) honestly measured 15 and passed. The squash of #672 onto main produced the sixteenth. Nothing lints main after a merge, so the violation surfaced only when #676 and the #667 branch put //agent/internal/cni/server back into a PR's bazel-diff impact set. Pure mechanical extraction into registerSweepInstruments (ghost-sweep counters and the prune-breaker gauge) and registerLifecycleInstruments (the unmeshed and storage gauges, liveness instruments, identity-override counter). No metric names, descriptions, units or registration order change. Verified with fail_on_violation on //agent/internal/cni/server/... and the package tests. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
bpalermo
added a commit
that referenced
this pull request
Sep 4, 2026
#678) newCNIMetrics is at cognitive complexity 16 against the lint limit of 15 on main, and no PR ever failed CI for it. #671 (763f5b3) added the fifteenth registration; #672 was branched before #671 merged, added two more to a file it saw at 13, and its CI head (f5d540a) honestly measured 15 and passed. The squash of #672 onto main produced the sixteenth. Nothing lints main after a merge, so the violation surfaced only when #676 and the #667 branch put //agent/internal/cni/server back into a PR's bazel-diff impact set. Pure mechanical extraction into registerSweepInstruments (ghost-sweep counters and the prune-breaker gauge) and registerLifecycleInstruments (the unmeshed and storage gauges, liveness instruments, identity-override counter). No metric names, descriptions, units or registration order change. Verified with fail_on_violation on //agent/internal/cni/server/... and the package tests. Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr Co-authored-by: Claude Fable 5.1 <[email protected]>
…ard-pool # Conflicts: # charts/aether/Chart.yaml
bpalermo
added a commit
that referenced
this pull request
Sep 5, 2026
…efore merging (#679) (#685) PR CI validates a PR head against that PR's merge-base, and nothing validated main after a merge. Two PRs that each pass against their own base can combine into a state neither was ever tested in — #671 and #672 each added CNI metric registrations against a base without the other, and the second squash put newCNIMetrics at gocognit 16/15 on main, surfacing days later on the unrelated PRs #676/#677. Add .github/workflows/main.yaml (`main-post-merge`): on every push to main it runs the same build+lint+unit-test leg ci.yaml runs, with the bazel-diff impact set computed as the merge commit vs its first parent (HEAD^), falling back to a full //... build+test when bazel-diff cannot compute it. --config=ci implies --config=remote, which pins TestRunner to the local strategy, so tests stay local exactly as they are on the PR path. The pull_request path is untouched and `ci` remains the only required status check. ci-impacted-targets.sh never assumed a PR merge-base functionally, but its docs did; retitle them for the two callers and add the new workflow to the seed-file list so editing it forces a full run. The preventive half — branch protection required_status_checks.strict — is a repo settings change applied alongside this PR, not code. Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr Co-authored-by: Claude Fable 5.1 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The measured cause
Continuous profiling of the standalone mesh-DNS daemon (2026-09-04 pass) put
net.(*Dialer).DialContextat 20.97% of its CPU — more than theExchangeitexists to serve (18.47%), inside a
exchangeframe totalling 39.68%.miekg/dns's
Client.Exchangedials, exchanges and closes on every call(
client.go:169). So each forwarded query paid a dialer allocation,resolveAddrList,an
netFD+pollDesc,socket/connect/setsockopt, twoepoll_ctls and aclose— on a process the CNI DNATs every managed pod's:53to.The design
K (default 8) independent connected UDP sockets per upstream, round-robin.
sync.Mutex.TryLockonly, neverLock. A query walks the slots, skips any thatis busy, and if all K are busy it does a cold dial — which is precisely the
pre-mesh-dns: forwarded path is ~93% of CPU and dials a fresh UDP socket per query (DialContext 20.97% > Exchange 18.47%) #674 behaviour. This is the load-bearing property: the pool cannot add tail
latency by construction, only remove work. A blocking
Lockwould put anotherquery's 2s
forwardTimeoutwait directly into this query's path, which is the exactregression the change exists to avoid.
TestConcurrentForwardsDoNotSerialiseandTestPoolFallbackWhenAllSlotsBusypin both halves.ExchangeWithConn's packet-connpath (which already drains replies until the transaction ID matches,
client.go:218-226) is exactly the right primitive. An ID-demux design would need areader goroutine per conn, an ID→waiter map, ID rewriting (client transaction IDs
are attacker-chosen and collide), waiter eviction and unpack error handling —
several hundred lines of concurrency-critical code in a
system-node-criticaldaemon,for 21% of a minor consumer. Wrong trade.
is one extra dial.
RWMutex, nevers.mu(which guards therecord table and is read by the OTel gauge callback); the open-socket gauge is an
atomic.Int64folded into the existing observe callback, not a secondRegisterCallback.selfcheck.gois untouched: the watchdog probes the authoritative path, which isnever forwarded, so the pool is correctly invisible to it.
Port-rotation trade-off
Each slot carries two independent budgets — a jittered ~30s (±20%) age and 1000
queries, whichever expires first. Dial-per-query gave every query a fresh random
source port, i.e. the full ~2^32 (port × transaction ID) guessing space; a socket reused
for a 30s window collapses that to ~2^19 for the queries in the window.
That trade is acceptable here and only here because the socket is connected: the
kernel drops any datagram whose source is not the upstream's exact (IP, port), so an
off-path attacker cannot land a spoofed answer at all — they would have to forge the
kube-dns ClusterIP as a source address into the node's host netns, past netfilter and
rp_filter. The upstream is an in-cluster resolver, not an internet-facing recursor. The
30s cap plus per-slot jitter bounds the window regardless. This is stated in the doc
comment on the constants.
Why bounded lifetime matters independently: the conntrack black-hole
The upstream is a ClusterIP. Connecting a UDP socket to it creates a conntrack entry
that pins DNAT to one kube-dns backend pod. When that backend rolls, the entry
survives still pointing at a dead pod and datagrams are black-holed with no ICMP at
all — the socket only ever shows a read timeout. Retire-on-error catches that on the
first failed query, but the age budget is what guarantees a bounded self-heal even for a
socket nobody touches again, and what keeps a long-lived socket from pinning this node's
whole forward load onto a single kube-dns replica. Called out in code and in the runbook.
Why TCP is not pooled
Both TCP call sites keep
exchangeWith(s.tcpClient, ...), unchanged.ExchangeWithConnContextdoes not drain mismatched IDs; itreturns
ErrId(client.go:227-230). A late reply left on a pooled TCP socket wouldpoison the next query on it.
TestTCPForwardStillDialsPerQuerypins this for both the TCP-originated query and thetruncation retry: the answer is correct and
forward_conn_dials_totaldoes not move.Things checked and deliberately NOT done
controller/internal/cmd/root.go:90setsndots:2forthe mesh domain), so it already saves 4-6 upstream queries per external name. It is
not the available lever here.
SingleInflightis a deprecated no-op in miekg/dns v1.1.72 (client.go:65-71).Dropped from scope.
Filed as a separate follow-up issue rather than folded in here.
Metrics + post-deploy gate
Three new instruments, 5 series per node, closed value sets:
aether.mesh_dns.forward_conn_dials_totalreason∈ {pool_fill,fallback}aether.mesh_dns.forward_conn_recycles_totalreason∈ {error,rotated}aether.mesh_dns.forward_conn_pool_openPyroscope:
{service_name="aether-mesh-dns"}diff against 2026-09-04 07:05-07:30Z.Expect
DialContext20.97% → well under 1%, andexchange39.68% → ~19%.Flag surface
--forward-pool-size(default 8,0disables → dial-per-query) is plumbed through themesh-dns daemon, the chart template and
values.yamlasagent.meshDnsDaemon.forwardPoolSize(default unset, which emits no arg).This adds one flag, which cuts against proposal 031's flag-surface reduction. It is
carried deliberately as an escape hatch, not a tuning knob: pooling changes the
resolver's on-wire source-port behaviour against an upstream we do not control, and the
one-line rollback matters more than the flag costs.
maxAge/maxQueriesstayunexported.
The template guard is an explicit
kindIs "invalid"nil-check rather than{{- with }},precisely so
0renders.0is falsy to Helm, sowithwould have rendered nothingand left the pool ON — the one failure an operator reaching for the kill switch must
never hit.
--set agent.meshDnsDaemon.forwardPoolSize=0disables pooling.Rendered args verified for all four cases:
--set agent.meshDnsDaemon.forwardPoolSize=16- "--forward-pool-size=16"--set agent.meshDnsDaemon.forwardPoolSize=0- "--forward-pool-size=0"--set-string agent.meshDnsDaemon.forwardPoolSize=0- "--forward-pool-size=0"Testing
agent/internal/meshdns/forwardpool_test.go, all unit, all pass under--test_arg=-test.short.bazel test //agent/internal/meshdns:meshdns_test --test_arg=-test.short --runs_per_test=20→ 20/20 PASS (the concurrency and upstream-restart tests aretiming-shaped). Also 10/10 clean under
--@rules_go//go/config:race.TestServeNonMeshForwards,TestForwardTCPQueryUsesTCP,TestForwardTruncatedUDPReplyRetriesOverTCP,TestForwardTruncatedRetryFailureKeepsTruncatedReply) pass unchanged.helm lintclean; template verified for all four value cases in the table above.golangci-lint -E gocognitover both packages: clean, no findings.0.91.3→0.91.5(0.91.4and0.92.0are claimed by otherin-flight PRs). Whoever merges later will need to re-bump.
CI
The
testjob is currently red, and it is not caused by this change. It fails ona
gocognitviolation in//agent/internal/cni/server:server—newCNIMetricsat16, over the limit of 15. That target is pulled into this PR's impact set only
transitively, via
xds/cache; nothing here touches it. The violation is pre-existingon
mainand was reproduced on a clean tree atcf68f1b, the commit this branch isbased on. It is fixed by the standalone #678. Once #678 lands, merging
origin/maininto this branch will turn this PR green; no change is needed here.
Closes #674
🤖 Generated with Claude Code
https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr