Skip to content

perf(mesh-dns): pool upstream UDP sockets on the forward path instead of dialing per query (#674) - #676

Merged
bpalermo merged 2 commits into
mainfrom
fix/674-mesh-dns-forward-pool
Sep 4, 2026
Merged

bpalermo merged 2 commits into
mainfrom
fix/674-mesh-dns-forward-pool

Conversation

@bpalermo

@bpalermo bpalermo commented Sep 4, 2026 •

Copy link
Copy Markdown
Owner

The measured cause

Continuous profiling of the standalone mesh-DNS daemon (2026-09-04 pass) put
net.(*Dialer).DialContext at 20.97% of its CPU — more than the Exchange it
exists to serve (18.47%)
, inside a exchange frame totalling 39.68%.

miekg/dns's Client.Exchange dials, exchanges and closes on every call
(client.go:169). So each forwarded query paid a dialer allocation, resolveAddrList,
an netFD + pollDesc, socket/connect/setsockopt, two epoll_ctls and a
close — on a process the CNI DNATs every managed pod's :53 to.

The design

K (default 8) independent connected UDP sockets per upstream, round-robin.

  • sync.Mutex.TryLock only, never Lock. A query walks the slots, skips any that
    is 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 Lock would put another
    query's 2s forwardTimeout wait directly into this query's path, which is the exact
    regression the change exists to avoid. TestConcurrentForwardsDoNotSerialise and
    TestPoolFallbackWhenAllSlotsBusy pin both halves.
  • No ID demux. One query at a time per socket, so ExchangeWithConn's packet-conn
    path (which already drains replies until the transaction ID matches,
    client.go:218-226) is exactly the right primitive. An ID-demux design would need a
    reader 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-critical daemon,
    for 21% of a minor consumer. Wrong trade.
  • Retire on ANY exchange error. Only a successful reply keeps a socket. Worst case
    is one extra dial.
  • The pool registry lives under its own RWMutex, never s.mu (which guards the
    record table and is read by the OTel gauge callback); the open-socket gauge is an
    atomic.Int64 folded into the existing observe callback, not a second
    RegisterCallback.
  • selfcheck.go is untouched: the watchdog probes the authoritative path, which is
    never 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.

  1. Volume is negligible — only TCP-arriving queries and TC=1 truncation retries.
  2. On a stream conn ExchangeWithConnContext does not drain mismatched IDs; it
    returns ErrId (client.go:227-230). A late reply left on a pooled TCP socket would
    poison the next query on it.

TestTCPForwardStillDialsPerQuery pins this for both the TCP-originated query and the
truncation retry: the answer is correct and forward_conn_dials_total does not move.

Things checked and deliberately NOT done

  • ndots is already 2, not 5 (controller/internal/cmd/root.go:90 sets ndots:2 for
    the mesh domain), so it already saves 4-6 upstream queries per external name. It is
    not the available lever here.
  • SingleInflight is a deprecated no-op in miekg/dns v1.1.72 (client.go:65-71).
    Dropped from scope.
  • A negative/positive answer cache is a larger lever but changes answer semantics.
    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:

instrument kind attributes
aether.mesh_dns.forward_conn_dials_total counter reason ∈ {pool_fill, fallback}
aether.mesh_dns.forward_conn_recycles_total counter reason ∈ {error, rotated}
aether.mesh_dns.forward_conn_pool_open gauge none
# dials per forwarded query: 1.0 -> < 0.01
sum(rate(aether_mesh_dns_forward_conn_dials_total[5m]))
  / sum(rate(aether_mesh_dns_queries_total{result="forwarded"}[5m]))

# flat at K x upstreams
aether_mesh_dns_forward_conn_pool_open

# THE REAL GATE — must not regress
histogram_quantile(0.99, sum by (le) (rate(aether_mesh_dns_query_duration_bucket{result="forwarded"}[5m])))

# ~0 at steady state
rate(aether_mesh_dns_forward_conn_recycles_total{reason="error"}[5m])

Pyroscope: {service_name="aether-mesh-dns"} diff against 2026-09-04 07:05-07:30Z.
Expect DialContext 20.97% → well under 1%, and exchange 39.68% → ~19%.

Denominator artifact warning. The authoritative path will appear to go from
~3% to ~6% of daemon CPU in that diff. It is doing the same absolute work — the
denominator shrank. Do not read it as a regression.

Flag surface

--forward-pool-size (default 8, 0 disables → dial-per-query) is plumbed through the
mesh-dns daemon, the chart template and values.yaml as
agent.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 / maxQueries stay
unexported.

The template guard is an explicit kindIs "invalid" nil-check rather than {{- with }},
precisely so 0 renders. 0 is falsy to Helm, so with would have rendered nothing
and left the pool ON — the one failure an operator reaching for the kill switch must
never hit. --set agent.meshDnsDaemon.forwardPoolSize=0 disables pooling.

Rendered args verified for all four cases:

values rendered
unset (default) (no arg)
--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

  • 8 new tests in 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 are
    timing-shaped). Also 10/10 clean under --@rules_go//go/config:race.
  • The four forward-path regression tests (TestServeNonMeshForwards,
    TestForwardTCPQueryUsesTCP, TestForwardTruncatedUDPReplyRetriesOverTCP,
    TestForwardTruncatedRetryFailureKeepsTruncatedReply) pass unchanged.
  • helm lint clean; template verified for all four value cases in the table above.
  • golangci-lint -E gocognit over both packages: clean, no findings.
  • Chart version 0.91.3 → 0.91.5 (0.91.4 and 0.92.0 are claimed by other
    in-flight PRs). Whoever merges later will need to re-bump.

CI

The test job is currently red, and it is not caused by this change. It fails on
a gocognit violation in //agent/internal/cni/server:server — newCNIMetrics at
16, 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-existing
on main
and was reproduced on a clean tree at cf68f1b, the commit this branch is
based on. It is fixed by the standalone #678. Once #678 lands, merging origin/main
into this branch will turn this PR green; no change is needed here.

Closes #674

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

… 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
bpalermo force-pushed the fix/674-mesh-dns-forward-pool branch from 8380942 to 4c571bd Compare September 4, 2026 21:04
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
bpalermo merged commit 623c254 into main Sep 4, 2026
16 checks passed
@bpalermo
bpalermo deleted the fix/674-mesh-dns-forward-pool branch September 4, 2026 21:24
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]>
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.

mesh-dns: forwarded path is ~93% of CPU and dials a fresh UDP socket per query (DialContext 20.97% > Exchange 18.47%)

1 participant