Resource and memory bugs: everything you acquire needs an owner and a limit
21 min read
A link preview feature fetches the title of a URL that a user pastes. Some external sites are slow, so the handler has a timeout. The code is short and easy to read.
func previewTitle(ctx context.Context, url string) (string, error) {
ch := make(chan string) // no buffer
go func() {
ch <- fetchTitle(url) // if nobody is receiving anymore, this line blocks forever
}()
select {
case t := <-ch:
return t, nil
case <-ctx.Done():
return "", ctx.Err()
}
}
Every test passes. Every request returns within its time limit. Now call it 1,000 times, with fetchTitle taking 50 ms and a 10 ms timeout, and wait for every fetchTitle to finish. The result:
goroutines: 1001
The handlers returned long ago. Every fetchTitle call has finished. But all 1,000 goroutines still wait to send a value into a channel that nobody will ever read. In production this number grows every time an external site is slow. Memory climbs a little at a time. Eventually somebody adds a cron job that restarts the service every week and calls it "normal".
Go has a garbage collector, so how can this leak? This article is part six of the series that started with the bug map. The previous part covered error handling bugs. This part covers group 4, resources and memory.
The garbage collector frees only what nothing can reach
A garbage collector does one job. It frees memory that the program can no longer reach. It does not know what is "no longer used". It only knows what "nothing points to anymore". It does not do these things for you:
- It does not close files, connections or transactions that are still open.
- It does not stop a goroutine that is blocked. A live goroutine is a starting point (a root) for the collector's search. Everything the goroutine points to stays alive too.
- It does not delete entries from a map that you still hold, even if nobody will ever read those entries again.
The short answer of this article is that every resource you acquire must answer two questions:
- Who releases it, and does that happen on every path? That includes the normal path, the error path and the timeout path.
- How large can it grow, and what happens when it reaches its limit?
A bug that fails the first question is a resource leak. A bug that fails the second is unbounded growth. Neither shows symptoms in a test run, because tests are short and use a few inputs. The symptoms appear after the program has run for days, or when somebody sends input that you did not expect.
Other languages name the first question differently. C++ ties the release to the lifetime of a variable and calls it RAII. Java has try-with-resources. Python has with. Go has defer. The mechanisms differ, but the question is the same: who owns this resource, and who must release it?
A goroutine is a resource, and it needs a way to end
The goroutine in the example blocks because an unbuffered channel needs a sender and a receiver to meet at the same time. When the timeout fires first, previewTitle returns and nobody receives the value. The goroutine waits to send forever.
The smallest fix is to give the channel one free slot. The goroutine can then always send its value and exit, whether or not anybody is waiting.
ch := make(chan string, 1) // one free slot, so the send always succeeds
goroutines: 1
A better fix passes ctx into fetchTitle and builds the request with http.NewRequestWithContext. Then a timeout also stops the work, not only the goroutine. Without that, every request that times out still fetches the external site to the end, and nobody uses the result.
Use one rule every time. Before you type go, say when this goroutine ends and what makes it end. If the answer is "when the work is done", ask a second question. If nobody waits for the result anymore, can the work still finish?
This problem is not limited to examples. Uber studied goroutine leaks in its own monorepo, which holds about 75 million lines of Go code and about 2,500 microservices. The results are in a paper at CGO 2024. LeakProf, a tool that reads profiles from production, found 24 leaks, and 21 of them were fixed. Goleak, which checks during unit tests, found 857 leaks already in the code and prevented about 260 new ones in one year. The fixes made some services up to 34% faster and cut their memory use by up to 9.2 times.
Since Go 1.27, the runtime can find these goroutines for you with a profile named goroutineleak. Go 1.26 required GOEXPERIMENT=goroutineleakprofile. In 1.27 it is available without that setting, and net/http/pprof serves it at /debug/pprof/goroutineleak.
_ = pprof.Lookup("goroutineleak").WriteTo(os.Stdout, 1)
goroutineleak profile: total 1000
1000 @ 0x104f21a08 0x104eba854 0x104eba468 0x104f78554 0x104f27cd4
# 0x104f78553 main.previewTitle.func1+0x63 .../leak/main.go:21
The profile points directly at the line ch <- fetchTitle(url). It works through the garbage collector itself. If a goroutine is blocked on a channel that no runnable goroutine can reach, nothing can ever wake it, so it has certainly leaked. The Go 1.26 release notes state a limit. If the channel is reachable through a global variable, the runtime does not detect the leak. An empty profile therefore does not prove that nothing leaks.
Release right after you acquire, so every return passes the release
This function checks that a link in an article still works. It has defer resp.Body.Close(), but not directly after it gets resp.
func checkLink(c *http.Client, url string) error {
resp, err := c.Get(url)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("checking %s: status %d", url, resp.StatusCode) // returns before Close
}
defer resp.Body.Close()
return nil
}
A working link reaches the defer. A broken link does not. I checked a link that returns 404 100 times. I counted the connections the server saw and the goroutines left after the run:
buggy: 100 requests, 100 connections opened, 302 goroutines
close: 100 requests, 1 connections opened, 5 goroutines
A body that is never closed keeps its connection out of the pool. Every call must open a new connection, and the old connection stays open with the goroutines that serve it. These numbers explain how one process reaches "too many open files" on the day that many target sites break at once. That is the day the system most needs to work.
The fix moves the defer up, directly after the error check. Every return below it then passes through the release.
resp, err := c.Get(url)
if err != nil {
return err
}
defer resp.Body.Close() // release right after acquiring, so every path passes here
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("checking %s: status %d", url, resp.StatusCode)
}
I ran the fixed version five times. It opened one or two connections, not the same number each time. The documentation of Client.Do explains why. A connection can be reused when the body has been read to EOF and closed. On close, Transport tries to read the rest of the body asynchronously, but only up to a conservative limit. If you need the connection reused every time, read the body to the end with io.Copy(io.Discard, resp.Body) before you close it. That version opened one connection on every run.
This bug is related to error handling bugs. Error branches are the branches that tests rarely run, and they are often the branches that return before releasing a resource. One habit prevents it every time. After you acquire a resource, the line after the error check is always the release.
defer runs when the function ends, not when the loop iteration ends
defer runs when the surrounding function returns. It does not run at the end of a block or a loop iteration.
func countLines(paths []string) (int, error) {
total := 0
for _, p := range paths {
f, err := os.Open(p)
if err != nil {
return 0, err
}
defer f.Close() // runs when countLines returns, not at the end of this iteration
s := bufio.NewScanner(f)
for s.Scan() {
total++
}
}
return total, nil
}
With 1,000 post files, this function keeps all 1,000 files open and closes them together at the end. Here is the result with the open file limit set to 256:
buggy: 0 open $TMPDIR/posts4151777423/post-253.md: too many open files
fixed: 3000 <nil>
To run this, I set the limit with ulimit -Hn 256, not only ulimit -n. Since Go 1.19, a program that imports os raises its soft limit to the hard limit at startup. This detail explains why the bug rarely appears on a developer machine. The limit is high enough for a test with a few files to pass. The bug waits until the real number of files grows past the limit.
The fix moves the work of one iteration into its own function. The defer then runs when that function returns, which is once per iteration.
// countFile opens and closes one file, so defer runs on every iteration
func countFile(p string) (int, error) {
f, err := os.Open(p)
if err != nil {
return 0, err
}
defer f.Close()
n := 0
s := bufio.NewScanner(f)
for s.Scan() {
n++
}
return n, s.Err()
}
Everything that can grow needs a limit
An in-memory cache is the easiest way to make a page faster. It is also the easiest way to make a process use all of its memory.
type pageCache struct {
pages map[string][]byte // only grows, never shrinks
}
func (c *pageCache) get(url string, render func() []byte) []byte {
if b, ok := c.pages[url]; ok { // url includes the query string
return b
}
b := render()
c.pages[url] = b
return b
}
A normal user who opens the same page ten thousand times creates one key. A bot that adds a different query string each time, such as ?utm=1 and ?utm=2, creates a new entry on every request. Here is a test with a 20 KB page:
normal traffic: 1 entries, heap 0.3 MB
bot traffic: 10001 entries, heap 196.7 MB
The point to see here is that the size of the map does not depend on your code. It depends on the input. Whoever can send requests decides how much memory your process uses. Every structure that grows with input therefore needs a limit. That includes maps used as caches, slices that you keep appending to, job queues, the number of goroutines you start per request, and the size of the request body you accept.
The fixed version does two things. The same page always gets the same key, and the cache has a maximum number of entries.
key := u.Path // the same page must get the same key, whatever the query is
if b, ok := c.pages[key]; ok {
return b
}
b := render()
if len(c.pages) >= c.max { // limit reached: drop any one entry
for k := range c.pages {
delete(c.pages, k)
break
}
}
c.pages[key] = b
query bot: 1 entries, heap 0.3 MB
path bot: 100 entries, heap 2.3 MB
A bot that changes the path instead of the query can grow the cache to 100 entries and no further. Dropping a random entry is the simplest policy. If you want to drop the least recently used entry first, use an LRU cache. What matters most is that the number exists. The eviction policy comes second.
A limit must say what happens when it is reached
On 18 November 2025, Cloudflare returned HTTP 5xx errors to many users for several hours. Cloudflare's report explains that Bot Management uses a "feature file" that a ClickHouse query generates every five minutes. The code that reads the file preallocates memory for performance and sets a limit of 200 features. Normal use was about 60.
A permissions change in ClickHouse made the query also return the metadata of another schema. The number of rows more than doubled, and the new file had more than 200 features. The Rust code called unwrap() on a result that was an error, so it panicked, and the proxy returned 5xx. The main impact started at about 11:20 UTC. All systems were back at 17:06 UTC.
The limit in this incident existed, and its value was reasonable. What was missing was an answer to the question of what happens at the limit. The code stopped the whole process. It could have rejected the new file and kept using the previous file, which worked. One of Cloudflare's follow-up items is to check configuration files that Cloudflare generates itself in the same way as input from users.
There are only a few answers to "what happens at the limit", and you must choose one during design:
| At the limit | Use it for | Example |
|---|---|---|
| Drop old items | caches | LRU, maxmemory-policy allkeys-lru |
| Reject new items | requests, queued jobs, new configuration | respond 503 or 429, keep the previous configuration |
| Make the sender wait (backpressure) | internal work that can slow down | a blocking send into a buffered channel |
| Stop the whole process | almost nothing | what happened at Cloudflare |
In Go, a job queue that rejects work when it is full is short. It uses a buffered channel and a select with a default case.
// Submit does not wait. If the queue is full, it rejects the job immediately
func (q *Queue) Submit(j Job) error {
select {
case q.jobs <- j:
return nil
default:
return ErrQueueFull // limit reached: tell the caller, so the handler can respond 503
}
}
job 1 -> <nil>
job 2 -> <nil>
job 3 -> <nil>
job 4 -> queue full
job 5 -> queue full
ErrQueueFull is an error that the system sends on purpose. Following the rule from the previous part, the layer that knows enough to decide is the handler. It can respond 503 with Retry-After, or tell the user to try again later.
Memory that is still reachable but no longer used
In a language with a garbage collector, memory can leak without forgetting to close anything. You only need to hold a reference longer than necessary. A common example in Go is a small slice of a large array.
// signature keeps only the first 8 bytes to detect the file type (buggy version)
func signature(data []byte) []byte {
return data[:8] // still points at the same 4 MB array
}
func signatureFixed(data []byte) []byte {
return bytes.Clone(data[:8]) // copies 8 bytes, so the large array can be collected
}
Here is the result of keeping the signatures of 50 uploaded files of 4 MB each:
data[:8]: keep 50 x 8 bytes, heap 200.3 MB
bytes.Clone: keep 50 x 8 bytes, heap 0.3 MB
Both versions keep the same 400 bytes of real data. The first version keeps all 50 arrays reachable, so the collector cannot free them. The Go blog article Go Slices: usage and internals warned about this in 2011. Re-slicing does not copy the underlying array, and the whole array stays in memory while anything still points to it.
This problem has a second side, which the part on null, state and data bugs already covered. A string from fiber.Ctx points into a buffer that Fiber will reuse. In the first case, you hold somebody else's memory too long. In the second case, you use memory that its owner has already taken back. In C, the second case is a use-after-free. The bug map gives Heartbleed and CrowdStrike as examples from the same group. Memory-safe languages remove that subgroup of bugs. They do not remove the question of who owns the memory. The question remains, and a wrong answer costs less.
Where this repository answers the two questions
z2s-web-app uses Redis (Valkey) as a cache, and it answers the limit question at two levels.
At the first level, every key must expire. AGENTS.md says "Every key gets a TTL", and the Opengrep rule redis-key-without-ttl in .opengrep/conventions.yaml catches a Set with a TTL of 0. The Opengrep article explains that rule. Cached pages expire after 10 minutes (pageTTL in internal/shell/web/app.go).
At the second level, the whole instance has a limit, set in deploy/helm/valkey/values.yml:
maxmemory 3gb
maxmemory-policy allkeys-lru
The first line is the limit. The second line says what happens at the limit. Valkey drops the least recently used keys. It does not reject writes and make requests fail.
The key for a cached page comes from c.Path() in internal/shell/web/respond.go, which does not include the query string. A bot that adds ?utm= therefore cannot create new keys. Time has limits too. Every Redis call has a 50 ms timeout (opTimeout in internal/shell/cache/cache.go), so a slow Redis does not make requests wait. Sending email from the contact form has a 15 second timeout, and a limiter allows 5 submissions per IP address every 10 minutes.
For releases, the Opengrep rule http-body-not-closed catches an http.Get that is not followed by defer ....Body.Close(). cmd/server/main.go closes the Redis client with defer rdb.Close() right after it creates the client.
Tools see that a release exists, not that it runs on every path
I ran the buggy examples above through go vet and golangci-lint 2.15.0 with Go 1.27.4. These are the results:
| Bug | Tool | Caught? |
|---|---|---|
Discarding the cancel from context.WithTimeout |
go vet (lostcancel), on by default |
yes |
defer in a loop |
revive, rule defer |
yes |
| The body is never closed | bodyclose | yes |
The body is closed, but a return comes before Close |
bodyclose, http-body-not-closed |
no |
| A goroutine blocked forever | goroutineleak profile, goleak |
yes, at run time, not at lint time |
| A map with no limit | none | no |
The fourth row is the checkLink bug. The tools see a Close in the function and stop there. They do not check whether a return above it skips the release. You can close this gap by turning the habit "release right after you acquire" into a rule. The Opengrep rule below reports any statement between the error check and defer ... Close().
rules:
- id: close-right-after-acquire
languages: [go]
severity: WARNING
message: >-
Code runs between acquiring $RES and the deferred Close. A return in
that code skips the release. Put the defer right after the error check.
patterns:
- pattern-either:
- pattern: |
$RES, $ERR := $ACQ(...)
if $ERR != nil { ... }
$STMT
...
defer $RES.Close()
- pattern: |
$RES, $ERR := $ACQ(...)
if $ERR != nil { ... }
$STMT
...
defer $RES.Body.Close()
- metavariable-pattern:
metavariable: $STMT
patterns:
- pattern-not: defer $RES.Close()
- pattern-not: defer $RES.Body.Close()
$STMT is the first statement after the error check. The metavariable-pattern says that this statement must not be the deferred release. The rule's fixture has two cases that it must catch: checkLink, and a function that reads a file before defer f.Close(). It has three cases that it must not catch, including a defer func() that reads the body to the end before closing it. The result from Opengrep 1.26.0:
1/1: ✓ All tests passed
A scan of cmd and internal in this repository finds nothing, which means the code here already releases resources right after acquiring them. The rule is not in .opengrep/ yet. It shows that a bug the usual linters miss can become a team rule in a few lines.
A blocked goroutine is hard to find with static analysis, because the tool must know whether anything will receive at run time. What works is checking at run time, with goleak in tests or with the goroutineleak profile in production. No tool catches a map without a limit, because no tool knows whose input the keys come from. The person who reads the code must ask that question.
Agents write the normal path and forget the release path
Every bug in this article passes its tests and compiles. Those are the checks an agent uses to decide that it is done. A prompt like "make it faster" often returns a go func() or a map used as a cache. A prompt like "read every file in the folder" often returns a defer in a loop. The tests that the agent writes with the code usually run on a few inputs, which is too few for these bugs to show.
When you read a diff that an agent wrote, as the article on reading code suggests, stop at three places:
- Every
Open,Get,Begin,LockandAcquire. Is the line after the error check the release? - Every
go. When does this goroutine end? If whoever waits for the result goes away, can it still end? - Every map, slice and queue that lives longer than one request. What is its maximum size, who controls its size, and what happens at the limit?
A table to keep
| Bug | Why it happens | Why tests miss it | What helps |
|---|---|---|---|
| A blocked goroutine | It sends into a channel nobody reads anymore | The handler still responds in time | A buffered channel, passing ctx in, goroutineleak, goleak |
| No release in an error branch | A return comes before Close |
Tests run only the normal path | defer right after the error check, the close-right-after-acquire rule |
defer in a loop |
defer runs when the function ends |
Tests use fewer files than the limit | A function per iteration, revive defer |
Discarded cancel |
The context is not released until it times out | No immediate symptom | go vet lostcancel |
| A cache with no limit | The input decides the number of keys | Tests use a few keys | Normalized keys, a maximum size, a TTL |
| Failure at the limit | Nobody designed what happens at the limit | Test input never reaches the limit | Choose in advance: drop old items, reject new items, or make the sender wait |
| A small slice holds a large array | The collector frees only what nothing points to | Tests do not measure memory | bytes.Clone, strings.Clone |
What to do differently
Every time you write code that acquires a resource, write the release on the line after the error check, before you write the code that uses the resource. Every time you write go, say when it ends. Every time you create a structure that lives longer than one request, write its limit as a number in the code, and write what happens when it reaches that limit. And do not accept a weekly restart as normal. It is a manual release of resources for code that does not release them itself.
The next article in this series covers group 5, concurrency: race conditions, deadlocks, and check-then-act. That is the group where the goroutines from this article start to fight over the same data.
References
- Unveiling and Vanquishing Goroutine Leaks in Enterprise Microservices: A Dynamic Analysis Approach (Saioc, Shirchenko, Chabbi, CGO 2024): the size of Uber's monorepo, the goroutine leaks that LeakProf and goleak found, and the effect on CPU and memory.
- Go 1.27 Release Notes: the
goroutineleakprofile is generally available, and the/debug/pprof/goroutineleakendpoint. - Go 1.26 Release Notes: how the runtime uses the garbage collector to find leaked goroutines, and the limit with global variables.
- runtime/pprof: new goroutine leak profile (golang/go issue 74609): the proposal for this profile.
- Cloudflare outage on November 18, 2025 (Cloudflare, 2025): the feature file that exceeded the limit of 200, the
unwrap()that panicked, and the follow-up items. - net/http: Client.Do (Go documentation): the body must be read to EOF and closed before the connection can be reused.
- Go 1.19 Release Notes: Go raises the
RLIMIT_NOFILElimit at startup. - Go Slices: usage and internals (Andrew Gerrand, Go blog, 2011): the section "A possible gotcha" on a small slice that holds a whole array.
- The Go Programming Language Specification: Defer statements:
deferruns when the surrounding function returns. - go.uber.org/goleak (Uber): detects goroutines left running after a test ends.
- golangci-lint linters (golangci-lint 2.15.0): bodyclose, revive and govet, which the article tested.