Skip to content

reverseproxy: reduce lock contention in dynamic SRV and A upstreams - #7949

Merged
steadytao merged 5 commits into
caddyserver:masterfrom
faiyazrahmann:fix/7946-srv-lookup-lock-contention
Nov 3, 2026
Merged

steadytao merged 5 commits into
caddyserver:masterfrom
faiyazrahmann:fix/7946-srv-lookup-lock-contention

Conversation

@faiyazrahmann

@faiyazrahmann faiyazrahmann commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7946

The shared SRV and A/AAAA upstream caches held a global write lock for the whole DNS lookup. A slow or timing-out lookup for one record therefore blocked GetUpstreams for every unrelated dynamic upstream.

Changes (in modules/internal/network, where #7790 moved this code):

  • DNS lookups now run without the cache lock held. Concurrent callers for the same key share one lookup via singleflight.
  • Each cache entry stores a per-key generation (so the cache's 100-entry cap also bounds it), and each cache has an epoch. Both are part of the singleflight key and are checked before a result is written back. As a result, ResetSRV/ResetAllSRV invalidate in-flight lookups, and callers that arrive after a reset never join a lookup that started before it.
  • The shared lookup is detached from the request that started it, so cancelling that request doesn't fail it for the others. Its own 30s timeout bounds it, and each caller still returns as soon as its own context is done.
  • A gate shared by SRV and A caps distinct in-flight lookups at 64 running and 256 queued. Beyond that, lookups are shed. When a grace period is set and a stale SRV entry is cached, that entry is served; otherwise the lookup fails with an error.
  • SRV and A share one cache implementation in cache.go. dynamicupstreams.go keeps the SRV/A API.

Behavior change: AUpstreams now implements CachingUpstreamSource (via new network.ResetA/network.ResetAllA). Retries now clear its cache entry, as SRVUpstreams already did, which costs one extra DNS lookup per retry. The gate above bounds that cost.

Tests cover: slow lookups not blocking other keys, cancelling the first caller, targeted and full resets during a lookup, a stale lookup not overwriting a newer result, gate saturation, recovery after saturation and shedding. go test -race and golangci-lint pass.

Assistance Disclosure

I authored and coded the solution and unit tests; I used AI to generate in-code documentation and comments for the tests I wrote.

Rebase: after #7790 moved this code into modules/internal/network, a maintainer rebased the PR with AI assistance (Claude Code, Claude Opus 5.5). The rebase ported the design above into that package, merged the SRV and A code paths into one shared cache, and trimmed the tests.

Copilot AI lite review requested due to automatic review settings August 20, 2026 17:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

GitHub Copilot (agent) review: This PR improves reverse proxy dynamic upstream resolution by reducing mutex contention during SRV and A/AAAA DNS lookups, preventing slow DNS queries for one key from blocking unrelated upstream keys.

Changes:

  • Reworks SRV and A/AAAA upstream caches to avoid holding the global cache lock across DNS lookups, using singleflight to dedupe concurrent lookups per key.
  • Adds per-key generation/epoch tracking to avoid cache repopulation when ResetCache() happens during in-flight lookups.
  • Adds concurrency-focused unit tests covering slow lookups and cache resets during in-flight resolution.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
modules/caddyhttp/reverseproxy/upstreams.go Refactors SRV and A/AAAA dynamic upstream caching/lookup to reduce lock contention and dedupe per-key lookups.
modules/caddyhttp/reverseproxy/upstreams_test.go Adds regression tests for slow-lookups-not-blocking and reset-during-lookup behavior.
Suppressed comments (1)

modules/caddyhttp/reverseproxy/upstreams.go:235

  • After successfully writing the refreshed SRV result to the cache, srvGen[suAddr] is left in the map indefinitely. Since generation values are only needed to detect concurrent resets, consider deleting srvGen[suAddr] on successful cache write so srvGen doesn't accumulate keys over time.
		srvs[suAddr] = srvLookup{
			srvUpstreams: su,
			freshness:    time.Now(),
			upstreams:    upstreams,
		}

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@faiyazrahmann

Copy link
Copy Markdown
Contributor Author

@steadytao whenever you get a chance, could you take a look at this? wanted to make sure the implementation lines up with what we discussed.

side note, the lint ci job are failing but its on files i didnt touch (fileloader.go, folderloader.go, pemloader.go, caddytest.go) - looks like pre-existing gofumpt/staticcheck stuff unrelated to this PR, just flagging this in case.

@steadytao

Copy link
Copy Markdown
Member

@steadytao whenever you get a chance, could you take a look at this? wanted to make sure the implementation lines up with what we discussed.

Bit busy this weekend. Will review when available but from a snappy look the shape is alright.

side note, the lint ci job are failing but its on files i didnt touch (fileloader.go, folderloader.go, pemloader.go, caddytest.go) - looks like pre-existing gofumpt/staticcheck stuff unrelated to this PR, just flagging this in case.

gofumpt complaints drift a lot, ill fix that later if not addressed.

@faiyazrahmann

Copy link
Copy Markdown
Contributor Author

Sounds good. Ive got some free time this week, so i might dig into the gofumpt issues and see if i can clean those up...

@steadytao steadytao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking mostly good just a relatively large change so I will give a thorough review after we fix the smaller issue.

@steadytao

Copy link
Copy Markdown
Member

Bit irrelevant but I will resolve gofumpt in ~16 hours if not done already, unless you are resolving. I am no longer as busy.

@faiyazrahmann

Copy link
Copy Markdown
Contributor Author

Bit irrelevant but I will resolve gofumpt in ~16 hours if not done already, unless you are resolving. I am no longer as busy.

im working on it as well. its been delayed a bit, but i will get it sorted and keep you posted.

@faiyazrahmann
faiyazrahmann force-pushed the fix/7946-srv-lookup-lock-contention branch from f86af66 to 876e525 Compare August 24, 2026 17:10

@steadytao steadytao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just some lifecycle issues. Thank you for your work thus far.

@faiyazrahmann
faiyazrahmann force-pushed the fix/7946-srv-lookup-lock-contention branch 2 times, most recently from a8436fb to 74cfd92 Compare August 25, 2026 05:54
@faiyazrahmann

faiyazrahmann commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Just some lifecycle issues. Thank you for your work thus far.

@steadytao fixed all three

  • srvGen/aGen are gone, gen now lives on the cache entry itself so it's bounded by the same 100 entry cap as the rest of the cache, no more unbounded growth.
  • same fix on the A/AAAA side.
  • lookup now runs on context.WithoutCancel(r.Context()) so a cancelled leader request doesn't kill the lookup for other waiters sharing the same flight.
  • added the mentioned regression for both srv and A.

one thing to flag, context.WithoutCancel needs go 1.21+, lmk if that's an issue for the supported toolchain range.

ready for another look whenever you have time.

@faiyazrahmann
faiyazrahmann force-pushed the fix/7946-srv-lookup-lock-contention branch 2 times, most recently from bb84b2e to c8ac015 Compare August 25, 2026 11:41
@faiyazrahmann
faiyazrahmann force-pushed the fix/7946-srv-lookup-lock-contention branch from c8ac015 to 1fcb875 Compare August 28, 2026 09:31
@faiyazrahmann

Copy link
Copy Markdown
Contributor Author

ci lint failure is unrelated to my recent changes, golangci-lint 2.13.2 flags 6 pre-existing issues on master in untouched files. looks like the same issue as #7958.

@steadytao

Copy link
Copy Markdown
Member

I can already seem some unbounded memory concerns. Will return tomorrow.

@steadytao

Copy link
Copy Markdown
Member

ci lint failure is unrelated to my recent changes, golangci-lint 2.13.2 flags 6 pre-existing issues on master in untouched files. looks like the same issue as #7958.

I know :) Fixed in #7964 already

@faiyazrahmann

faiyazrahmann commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor Author

I can already seem some unbounded memory concerns. Will return tomorrow.

guess what, i overwrote my own fix -_-, i was working from two machines and forgot to pull, which brought back the memory issue you caught with the uncapped srvGen side map. which was causing the unbounded memory concerns. restored it now, with the generation living on the cache entry and the shared lookup getting its own 30s deadline.

next push will replace your merge commit, aghh. truly elite git craftsmanship on my part -_-

@faiyazrahmann
faiyazrahmann force-pushed the fix/7946-srv-lookup-lock-contention branch from 6c39fe7 to 702ed3d Compare August 28, 2026 10:40
@faiyazrahmann

Copy link
Copy Markdown
Contributor Author

I can already seem some unbounded memory concerns. Will return tomorrow.

guess what, i overwrote my own fix -_-, i was working from two machines and forgot to pull, which brought back the memory issue you caught with the uncapped srvGen side map. which was causing the unbounded memory concerns. restored it now, with the generation living on the cache entry and the shared lookup getting its own 30s deadline.

next push will replace your merge commit, aghh. truly elite git craftsmanship on my part -_-

@steadytao gentle ping! the code is ready for review when you have a cycle...

@steadytao steadytao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The retained cache is bounded but outstanding work is not. Distinct request-expanded keys create distinct singleflight entries and detached DNS lookups lasting up to 30 seconds. A hostile request stream can create unbounded concurrent resolver work. Add a shared concurrency bound for unique in-flight lookups and test saturation, cancellation and recovery.

@steadytao

Copy link
Copy Markdown
Member

Apologies for the delay. Very busy lately. Overall looking quite nice.

@faiyazrahmann
faiyazrahmann force-pushed the fix/7946-srv-lookup-lock-contention branch from 1711f70 to 2fcd074 Compare September 3, 2026 09:16
@faiyazrahmann

Copy link
Copy Markdown
Contributor Author

thanks for taking the time to review this so patiently, especially with your busy schedule. really appreciate it!

added a shared gate for the lookups. its a semaphore with 64 slots plus a wait queue of 256, shared by both SRV and A, so total resolver work stays capped no matter how many distinct keys come in. requests that join a lookup already in flight don't count against it.

if the queue is full the lookup gets shed instead of parking another goroutine for 30s. on SRV, if a grace period is set and there's something cached, it serves that stale entry instead of failing. A has no grace period so it just errors.

tests cover saturation, cancellation while queued, recovery once slots free up, and both shed cases.

@steadytao steadytao left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest changes address the outstanding bounded-work concern and CI is green. However, this has now become a fairly substantial cache and concurrency redesign though with new global limits, request shedding, stale fallback, singleflight generations and reset semantics across two implementations. I want to give the final state another careful pass before merging rather than treating the previous individual fixes as proof that the complete interaction is correct - probably a second maintainer too.

-- tests are probably a bit much too and can likely be reduced, at minimum without significantly reducing coverage

@steadytao

steadytao commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

@mholt @mohammed90 @francislavoie Bump for each of you, if you would like to take a look.

…addyserver#7946)

The shared SRV and A/AAAA caches held a global write lock across the DNS
lookup, so one slow or timing-out record blocked every unrelated
upstream source.

Lookups now run without the cache lock held, deduplicated per key with
singleflight. A per-key generation (stored on the cache entry, so it is
bounded by the cache cap) and a cache-wide epoch keep a lookup that was
in flight during ResetSRV/ResetAllSRV from writing its result back, and
are part of the singleflight key so callers after a reset do not join a
pre-reset lookup.

The shared lookup is detached from the request that started it and
bounded by its own 30s timeout; each caller still returns as soon as its
own context is done. Distinct lookups across both caches are capped by a
shared gate (64 running, 256 queued); beyond that they are shed, serving
a stale SRV entry if a grace period is set and one is cached.

SRV and A now share one cache implementation. AUpstreams also implements
CachingUpstreamSource (via new ResetA/ResetAllA), so retries purge its
cache entry like SRVUpstreams already did.

Rebased onto the move of this code into modules/internal/network (caddyserver#7790,
caddyserver#8252).

Fixes caddyserver#7946

Co-authored-by: Francis Lavoie <lavofr@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@francislavoie
francislavoie force-pushed the fix/7946-srv-lookup-lock-contention branch from 2fcd074 to 1b1dc95 Compare November 3, 2026 07:02
@francislavoie francislavoie added the optimization 📉 Performance or cost improvements label Nov 3, 2026
@francislavoie francislavoie added this to the v2.12.0 milestone Nov 3, 2026

@francislavoie francislavoie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 This review was written by an AI agent (Claude Code, Claude Opus 5.5) operating on behalf of a maintainer.

I rebased this onto current master and force-pushed. Since this branch was opened, #7790 moved the SRV/A discovery and caching code out of reverseproxy/upstreams.go and into modules/internal/network/dynamicupstreams.go, and #8252 made that cache resolver-aware. The original changes no longer applied there, so this is a port of the same design into the new package, not a textual rebase. The previous head was 2fcd0747.

Kept as-is from the PR's design

  • The DNS lookup runs without the cache lock held, and concurrent callers for the same key share one lookup via singleflight.
  • Resets use a per-key gen stored on the cache entry (so the cap bounds it) plus a cache-wide epoch. Both are part of the singleflight key and are checked before writing a result back.
  • The shared lookup is detached from the request that started it, with its own 30s timeout. Each caller still returns as soon as its own context is done.
  • One shared lookup gate (64 running, 256 queued) sits across SRV and A. Beyond that, lookups are shed; SRV with a grace period serves a stale entry if one is cached.

Changed while porting

  • SRV and A now share a single cache implementation instead of two copies of the logic.
  • AUpstreams.ResetCache uses the new network.ResetA / network.ResetAllA.
  • Tests are much smaller (about 280 new lines instead of about 1150), following the earlier "tests are probably a bit much" note. Shared behavior is tested once through SRV, and A has a test for reset and one for shedding. I also updated the existing network tests for the new cache type.
  • lookupGate.release is now a plain receive. Its only caller runs right after a successful acquire.

go build ./..., golangci-lint and go test -race pass for the reverseproxy and network packages. The new concurrency tests also passed 50 repeated runs under -race.

Worth a look before merging

  1. Behavior change: AUpstreams now implements CachingUpstreamSource, so each retry clears its cache entry, as SRVUpstreams already does. That costs one extra DNS lookup per retry. During a retry storm, the gate bounds this and may shed lookups, which falls back to static upstreams. That seems reasonable, but the PR description doesn't mention it yet.
  2. Rare stale write-back: a targeted reset leaves an empty entry with a bumped gen in the cache. If more than 100 other keys evict that entry while a lookup that started before the reset is still running, that lookup's gen check passes and it can write its result back. The worst case is one refresh interval of a DNS answer up to about 30s old, so I left it.
  3. The PR description should be updated for the new file layout and point 1.

As steadytao requested earlier, this still needs a second maintainer pass.

francislavoie and others added 3 commits November 3, 2026 02:16
…efresh

On Windows two close time.Now() calls can report no elapsed time, so an
entry seeded with a 1ns refresh could still be fresh and skip the shed
path entirely.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dynamicupstreams.go keeps the SRV/A API; the generic cache, its
singleflight/generation handling and the lookup gate are not specific to
either record type. No functional change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@steadytao
steadytao enabled auto-merge (squash) November 3, 2026 08:30
@steadytao
steadytao merged commit bbea66f into caddyserver:master Nov 3, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimization 📉 Performance or cost improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use sync.Map instead of mutex for caching to speed up dynamic SRV lookups of slow queries

4 participants