One slow DNS lookup was blocking every request in Caddy. here is how I fixed it.

By Faiyaz Rahman

Someone opened an issue on Caddy with a strange problem. If you have not used it, Caddy is a web server and reverse proxy written in Go, best known for setting up HTTPS automatically.

They had three servers running Docker services. Each server published DNS SRV records for its own services. Caddy sat in front of everything and used those SRV records to find where each service lived. When everything was up, it worked fine.

Then one server went down. Requests to the service on that server got slow, which makes sense. Its DNS lookup took about 3 seconds to time out. But requests to the other services got slow too. Those services were completely healthy, on servers that were still up. They had nothing to do with the dead one.

That is the bug this post is about. It took four rounds of review and about two and a half months before it was merged into Caddy. I want to write down every step, because most of what I learned came from the reviews and not from the first fix.

How Caddy finds upstreams with DNS

Caddy's reverse proxy can get its list of backend servers (upstreams) from DNS instead of a fixed list in the config. You give it a name like _http._tcp.serviceA.foo.lan and it asks DNS for the SRV records. The answer says which hosts and ports serve that service.

Asking DNS on every request would be slow, so Caddy caches the answer. The cache is a map from the name to the list of upstreams, plus a time for when that answer gets old. When the answer is old, the next request does a new lookup and updates the map.

A map that many requests read and write at the same time needs a lock. In Go that is a sync.RWMutex. There was one lock for the whole SRV cache, and another for the A/AAAA cache.

The actual problem

Here is a simplified version of what GetUpstreams did.

upstreams.go (before, simplified)
srvsMu.RLock()
cached, ok := srvs[key]
srvsMu.RUnlock()
if ok && cached.isFresh() {
    return cached.upstreams, nil
}
 
srvsMu.Lock()
defer srvsMu.Unlock()
 
// the DNS lookup happens while the lock is held
_, records, err := resolver.LookupSRV(ctx, service, proto, name)
 
srvs[key] = srvLookup{upstreams: toUpstreams(records), freshness: time.Now()}

Read that again. The write lock is taken before the DNS lookup and released after it. The lookup is a network call. Normally it takes a few milliseconds, so nobody noticed. But if the DNS server is down, the lookup sits there until it times out. 3 seconds in this case.

For those 3 seconds the lock is held. And it is one lock for the whole cache. So any other request whose cache entry is old has to wait for the same lock, even when it is for a totally different service.

One dead service was slowing down everything.

Press play and compare both modes.

Four requests, one slow DNS server

0s1s2s3sserviceCDNS is downdone 3.0sserviceAhealthydone 3.1sserviceC2nd requestdone 3.1sserviceBhealthydone 3.3swaiting for the lockown DNS lookupsharing a lookup / cache

Before: serviceC holds the one lock for its whole 3 second lookup. serviceA and serviceB are healthy, but they sit in line behind it.

The first idea was not enough

The issue title suggested using sync.Map instead of a mutex. A Caddy maintainer pointed out that this would not fix it. sync.Map makes reading and writing the map cheaper. The problem was not the map. The problem was holding a lock while doing slow network work.

I dug into the code and agreed. The same pattern was in two places: SRVUpstreams and AUpstreams. Both took the write lock before the lookup.

The fix we agreed on in the issue was:

  1. Do the DNS lookup with no lock held.
  2. Only take the lock for the quick part: reading the map and writing the result.
  3. Use singleflight so that many requests for the same name share one lookup instead of all asking DNS at once.

The maintainer added one more requirement before I wrote any code. Caddy can reset a cache entry, for example when a retry happens. If a reset happens while a lookup is still running, that old lookup must not write its result back afterwards. Otherwise the reset is silently undone.

This one requirement turned out to be where most of the work went.

What singleflight does

singleflight is a small package from golang.org/x/sync. You give it a key and a function. If nobody is running that key, it runs the function. If someone is already running it, you wait for their result instead of running it again.

var group singleflight.Group
 
v, err, shared := group.Do("serviceC", func() (any, error) {
    return lookupSRV("serviceC")
})

So if 50 requests for serviceC arrive while its DNS is down, there is one lookup, not 50. And requests for serviceA use a different key, so they never wait on serviceC at all.

Version 1

The first version did these three things. It moved the lookup outside the lock and added singleflight. For the reset requirement, it kept a separate map of generation numbers, srvGen and aGen. A generation is just a counter per key. A reset bumps it. A lookup remembers the generation it started with, and before writing its result, it checks that the generation has not changed. If it changed, a reset happened in between, so the result is thrown away.

I also wrote a test with a fake resolver. One key blocks on a channel and the other returns right away. Both are fired together, and the test checks that the fast one finishes long before the slow one is released. On the old code this test fails. On the new code it passes.

I felt pretty good about it. Then the reviews started.

Revision 1: a new request could join an old lookup

The first real review comment was one line.

A post-reset request can still join the pre-reset singleflight and receive its stale result.

Here is what that means. The singleflight key was just the name, like serviceC. So imagine this order:

  1. A lookup for serviceC starts.
  2. A reset happens.
  3. A new request for serviceC comes in.

The new request sees a lookup for serviceC already running and joins it. But that lookup started before the reset. So the new request gets an answer from before the reset, which is the exact thing the reset was supposed to prevent.

The fix was to put the generation into the singleflight key. A lookup that started at generation 0 has key 0:serviceC. After the reset, a new request uses 1:serviceC. Different key, so it starts its own lookup.

While fixing this, I found a second bug of my own. I was deleting the generation counter after a successful write, to keep the map small. But that meant a slow lookup could finish late, see no counter, and overwrite a newer result. So I stopped deleting it. The counter only ever goes up.

Step through both versions here.

Step 1 of 4: A lookup starts

cache entry
key: serviceC
targets: old IPs (expired)
lookups
L1 · 1 waitingrunning…

A request for serviceC finds an old entry and starts lookup L1. The DNS server is slow, so L1 takes a while.

Revision 2: the counter map grew forever, and one request owned everyone's lookup

That second fix created the next problem, which the maintainer caught right away.

The generation map had no limit. The cache itself is capped at 100 entries. But srvGen was a separate map, and the keys can contain placeholders that expand per request. So every distinct key that ever got reset added a counter that was never removed. With enough different keys, that map just keeps growing.

The fix was to stop keeping a separate map. The generation now lives on the cache entry itself. When a key is reset, the entry is not deleted. Its targets are cleared and its generation goes up by one. Since it is a normal cache entry, it counts toward the same 100 entry limit as everything else.

cache.go
type cacheEntry struct {
    refresh   time.Duration
    freshness time.Time
    targets   []Target
    gen       uint64 // lives here, so the 100 entry cap bounds it
}

The shared lookup used the first request's context. In Go, every request carries a context. If the client disconnects, the context gets cancelled, and anything using it stops. The lookup was running with the context of whichever request started the singleflight. So if that one request was cancelled, the lookup failed for every other request waiting on it, even though they were all still alive.

The fix was context.WithoutCancel. It makes a copy of the context that keeps its values but ignores cancellation. Each waiting request still uses a select on its own context, so it can give up and return early without killing the lookup for everyone else.

select {
case res := <-ch:
    return res.Val.([]Target), res.Err
case <-ctx.Done():
    // only this request gives up; the lookup keeps going for others
    return nil, ctx.Err()
}

Revision 3: a lookup with no deadline

WithoutCancel fixed one thing and broke another. The request context also had a deadline. By removing cancellation I also removed the deadline. So if the resolver got stuck, the shared lookup could keep running forever, even after every request waiting on it had left.

The fix was to give the shared lookup its own deadline, separate from any request.

ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()

Now the lookup does not depend on any single request, but it also cannot run longer than 30 seconds.

This round also had my favorite mistake of the whole PR. I was working from two machines and forgot to pull before pushing. My push brought back the old unbounded srvGen map that I had already removed. The maintainer saw it and said they could already see unbounded memory concerns. I had to admit I overwrote my own fix. Not my proudest git moment.

Revision 4: too much work at once

At this point the cache was bounded, the generations were bounded, and every lookup had a deadline. The maintainer then pointed out one more thing.

The retained cache is bounded but outstanding work is not.

Each distinct key gets its own singleflight entry and its own lookup that can run for up to 30 seconds. Someone sending requests that expand to lots of different keys could start thousands of these at once. Each one is a goroutine and a DNS query. Nothing was limiting that.

The fix was a gate shared by the SRV and A caches. It is a counting semaphore with a waiting line.

new lookup
    │
    ├── free slot? (64 max) ──── yes ──► run the lookup
    │
    └── no ── room in the line? (256 max)
                 │
                 ├── yes ──► wait for a slot (or until the 30s deadline)
                 │
                 └── no ───► shed the lookup
                                │
                                ├── SRV with a grace period and old data cached
                                │       └──► serve the old data
                                └── otherwise ──► return an error

At most 64 lookups run at once. Up to 256 more can wait. Anything beyond that is rejected right away instead of parking another goroutine for 30 seconds. Requests that join a lookup already running do not count, because they are not creating new work.

When a lookup is rejected, Caddy does not always fail the request. If SRV has a grace period configured and there is an older answer cached, it serves that older answer. Slightly old data is better than an error. But it only does this when there is something to serve, because caching an empty result under heavy load would be worse.

The gate itself is small. A buffered channel is the slot counter, and an atomic integer counts the waiting line.

cache.go
func (g *lookupGate) acquire(ctx context.Context) error {
    select {
    case g.running <- struct{}{}:
        return nil // got a slot right away
    default:
    }
    if g.pending.Add(1) > g.maxPending {
        g.pending.Add(-1)
        return errTooManyLookups // line is full, shed it
    }
    defer g.pending.Add(-1)
    select {
    case g.running <- struct{}{}:
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

I added tests for a full gate, cancelling while waiting in line, recovering once slots free up, and both shed cases. CI went green and the PR was approved.

Getting it merged

The maintainer approved it but did not merge right away. They said it had become a fairly big cache and concurrency redesign, with global limits, shedding, stale fallback, generations and reset rules, and they wanted a second maintainer to look at the whole thing together. They also said the tests were probably too much. That was fair. I had written a lot of them.

While it waited, another PR moved all of this code from reverseproxy/upstreams.go into a new package, modules/internal/network. My changes did not apply anymore. A maintainer ported the same design into the new package. While doing that, they merged the SRV and A code into one shared cache type instead of two copies, and cut the tests from about 1150 new lines to about 280.

My PR, #7949, was merged on November 3.

The final design

Here is the whole flow in the final code.

request for key
    │
    ├── read lock: entry fresh? ── yes ──► return it (fast path)
    │
    └── no ── singleflight key = epoch + gen + key
                 │
                 ├── same key already running? ──► wait for it
                 │                                   (or give up on my own ctx)
                 └── no ── start a lookup
                              │
                              ├── detached ctx with a 30s timeout
                              ├── take a gate slot (or shed)
                              ├── DNS lookup, no lock held
                              └── write lock: epoch and gen unchanged?
                                     ├── yes ──► save the result
                                     └── no ───► drop it, a reset happened

One thing I have not explained yet is the epoch. The generation handles a reset of one key. But Caddy can also reset the whole cache at once. Bumping a counter on every entry would be slow, so the cache also has one global epoch. A full reset bumps the epoch, and a lookup checks both the epoch and the generation before writing.

There was also one small behavior change. AUpstreams now resets its cache entry on a retry, the same way SRVUpstreams already did. That costs one extra DNS lookup per retry, but the gate keeps that cost bounded.

What I learned

Removing the lock was the small part. Everything else in the PR came from questions that only show up once the lock is gone.

The lock was doing a lot of quiet work. It made everything happen one at a time, so none of these questions could come up. Taking it out made things fast, but I had to answer every one of them myself.


This is the biggest thing I have done in open source so far, and most of what I learned came from the review comments, not from my first version. Every round found something I had not thought about, and every comment was short and exact. If you want to see the whole thing, the issue is #7946 and the PR is #7949.