Flight recorder and goroutine leak profile
suggest changeTwo production problems are hard to debug with a regular profiler:
- The rare slow request. 99.9% of requests take 2 ms, one takes 300 ms. A CPU profile averages it away, and by the time you start
runtime/tracethe problem is gone. - Goroutines that never exit. The goroutine count creeps up for days. The goroutine profile lists thousands of blocked goroutines, but most blocked goroutines are fine (they wait for work). Which ones are stuck forever?
Recent Go releases added a tool for each:
trace.FlightRecorder(Go 1.25) keeps the last few seconds of an execution trace in memory, and you write it to a file only when something interesting happens.- The
goroutineleakprofile (experimental in Go 1.26, on by default in Go 1.27) uses the garbage collector to find goroutines that are blocked on a channel or lock that nothing else can ever reach. - Since Go 1.27 pprof labels also show up in panic tracebacks and goroutine dumps, so you can tell which request or tenant a goroutine belonged to.
All examples were run with Go 1.27 (go 1.27 in go.mod). For the basics of runtime/trace and go tool trace see Debugging. For CPU and memory profiles see Basic cpu and memory profiling.
Flight recorder: tracing the past
A normal trace with trace.Start / trace.Stop records everything from start to stop. That's fine for a benchmark, but you can't run it all day in production: the file grows by megabytes per second.
A flight recorder also traces all the time, but keeps only a moving window of recent data in memory. When your code sees a problem (a slow request, an error, a failed health check) it calls WriteTo and gets the trace of the seconds that led up to the problem:
package main
import (
"fmt"
"log"
"math/rand/v2"
"os"
"runtime/trace"
"time"
)
func handle(i int) {
// Most calls are fast, an occasional one is slow.
d := time.Duration(rand.IntN(5)) * time.Millisecond
if i == 70 {
d = 300 * time.Millisecond
}
time.Sleep(d)
}
func main() {
fr := trace.NewFlightRecorder(trace.FlightRecorderConfig{
MinAge: 2 * time.Second, // keep at least the last 2 seconds
MaxBytes: 4 << 20, // but no more than ~4 MB
})
if err := fr.Start(); err != nil {
log.Fatal(err)
}
defer fr.Stop()
for i := range 100 {
start := time.Now()
handle(i)
if el := time.Since(start); el > 100*time.Millisecond {
fmt.Printf("call %d took %v, saving trace\n", i, el.Round(time.Millisecond))
f, err := os.Create("slow.trace")
if err != nil {
log.Fatal(err)
}
n, err := fr.WriteTo(f)
f.Close()
if err != nil {
log.Fatal(err)
}
fmt.Printf("wrote %d KB\n", n/1024)
}
}
fmt.Println("enabled:", fr.Enabled())
}
call 70 took 300ms, saving trace
wrote 6 KB
enabled: true
FlightRecorderConfig has two fields, both hints rather than hard limits:
MinAge: how far back the window should reach. Set it to a bit more than the problem you want to see. If you trigger on requests slower than 1 second, a 2-5 second window shows the slow request and what ran before it. 0 means "a few seconds".MaxBytes: a cap on the window size. It wins overMinAge: a busy server may produce more data in 2 seconds than you allow, and then the window gets shorter. 0 means an implementation-defined default.
How much data a second of tracing produces depends on how many goroutines are scheduled, how often they block, how much the GC runs. A busy server can produce several MB per second. Start with something like MinAge: 5*time.Second, MaxBytes: 32<<20, look at the size of the files you get, and adjust.
The rules:
- Only one flight recorder can be active in a process. A second
Startreturns an error. - A flight recorder can run at the same time as a regular
trace.Start(e.g. someone grabbing/debug/pprof/trace). - Only one
WriteTocan run at a time; a concurrent call returns an error. WriteToafterStopreturns an error.
a := trace.NewFlightRecorder(trace.FlightRecorderConfig{})
b := trace.NewFlightRecorder(trace.FlightRecorderConfig{})
fmt.Println("a:", a.Start())
fmt.Println("b:", b.Start())
fmt.Println("trace.Start:", trace.Start(io.Discard))
trace.Stop()
a.Stop()
_, err := a.WriteTo(io.Discard)
fmt.Println("WriteTo after Stop:", err)
a: <nil>
b: flight recorder already enabled
trace.Start: <nil>
WriteTo after Stop: cannot snapshot a disabled flight recorder
The cost: tracing is cheap since Go 1.21 (a few percent of CPU), and the flight recorder adds the memory for the window. That's usually acceptable to leave on in production, but measure it on your own workload.
Snapshotting slow HTTP requests
The typical use is a middleware that times every request and saves a snapshot when one is too slow. Two details matter in a real server:
- Rate-limit snapshots. If the database stalls, every request is slow and you don't want thousands of identical files. Saving at most one per minute is plenty.
- Don't make the slow request even slower: write the snapshot from a separate goroutine.
We also wrap each request in a trace.NewTask and the cache lookup in a trace.StartRegion, so it's easy to find them in the trace viewer:
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"runtime/trace"
"sync"
"time"
)
var fr *trace.FlightRecorder
// snapshot writes the flight recorder window to a new file, at most once per minute.
var (
snapMu sync.Mutex
lastSnap time.Time
)
func snapshot(reason string) {
snapMu.Lock()
defer snapMu.Unlock()
if !lastSnap.IsZero() && time.Since(lastSnap) < time.Minute {
return // don't flood the disk if many requests are slow
}
lastSnap = time.Now()
name := fmt.Sprintf("trace-%s.out", lastSnap.Format("150405"))
f, err := os.Create(name)
if err != nil {
log.Print(err)
return
}
defer f.Close()
if _, err := fr.WriteTo(f); err != nil {
log.Print(err)
return
}
log.Printf("%s: saved %s", reason, name)
}
// withFlightRecorder snapshots the trace when a request is slower than limit.
func withFlightRecorder(limit time.Duration, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, task := trace.NewTask(r.Context(), "http "+r.URL.Path)
start := time.Now()
next.ServeHTTP(w, r.WithContext(ctx))
task.End()
if el := time.Since(start); el > limit {
// Snapshot in a new goroutine: WriteTo can take a while
// and the client shouldn't wait for it.
go snapshot(fmt.Sprintf("%s took %v", r.URL.Path, el.Round(time.Millisecond)))
}
})
}
var (
cacheMu sync.Mutex
cache = map[string]string{}
)
func refreshCache() {
cacheMu.Lock()
defer cacheMu.Unlock()
time.Sleep(250 * time.Millisecond) // a slow refresh holding the lock
cache["greeting"] = "hello"
}
func handleGet(w http.ResponseWriter, r *http.Request) {
defer trace.StartRegion(r.Context(), "cache lookup").End()
cacheMu.Lock()
v := cache["greeting"]
cacheMu.Unlock()
fmt.Fprintln(w, v)
}
func main() {
log.SetFlags(0)
fr = trace.NewFlightRecorder(trace.FlightRecorderConfig{
MinAge: 5 * time.Second,
MaxBytes: 16 << 20,
})
if err := fr.Start(); err != nil {
log.Fatal(err)
}
defer fr.Stop()
mux := http.NewServeMux()
mux.HandleFunc("GET /get", handleGet)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
srv := &http.Server{Handler: withFlightRecorder(100*time.Millisecond, mux)}
go srv.Serve(ln)
defer srv.Close()
url := "http://" + ln.Addr().String() + "/get"
for i := range 5 {
if i == 3 {
go refreshCache()
time.Sleep(time.Millisecond)
}
start := time.Now()
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
log.Printf("request %d: %v", i, time.Since(start).Round(10*time.Millisecond))
}
time.Sleep(200 * time.Millisecond) // let the snapshot goroutine finish
}
request 0: 0s
request 1: 0s
request 2: 0s
request 3: 250ms
request 4: 0s
/get took 249ms: saved trace-232614.out
Request 3 was slow because a background refresh held cacheMu. A CPU profile wouldn't show that: nothing was using the CPU. The trace shows it.
Other good triggers for a snapshot: a request that returned 5xx, a context.DeadlineExceeded, a health check that took too long, or an admin endpoint that dumps the current window on demand.
Analyzing the snapshot
A flight recorder snapshot is a regular trace file, so go tool trace opens it:
$ go tool trace trace-232614.out
This starts a local web server and opens the browser. Things to look at:
- User-defined tasks: lists the
http /gettasks with a latency histogram. Click the slow one to see what its goroutine did. - View trace by proc / goroutine: the timeline. The slow request's goroutine shows a long gap where it was blocked, and the goroutine that held the lock running
refreshCacheduring that time. - Synchronization blocking profile, Network blocking profile, Scheduler latency profile: where goroutines waited, aggregated as pprof profiles.
By default the web server listens on a random port on localhost. In Go 1.27 a bare port like -http=:6060 also binds only to localhost, so a trace with your production data isn't exposed to the network by accident. To listen on all interfaces, say so explicitly: -http=0.0.0.0:6060.
You don't need the browser for the blocking profiles. -pprof=TYPE (net, sync, syscall or sched) writes a pprof profile you can inspect with go tool pprof:
$ go tool trace -pprof=sync trace-232614.out > sync.pprof
$ go tool pprof -top -focus=handleGet sync.pprof
Type: delay
Active filters:
focus=handleGet
Showing nodes accounting for 251.46ms, 26.10% of 963.55ms total
flat flat% sum% cum cum%
251.46ms 26.10% 26.10% 251.46ms 26.10% sync.(*Mutex).Lock
0 0% 26.10% 251.46ms 26.10% main.handleGet
0 0% 26.10% 251.46ms 26.10% main.withFlightRecorder.func1
0 0% 26.10% 251.46ms 26.10% net/http.(*ServeMux).ServeHTTP
0 0% 26.10% 251.46ms 26.10% net/http.(*conn).serve
0 0% 26.10% 251.46ms 26.10% net/http.HandlerFunc.ServeHTTP
handleGet spent 251 ms waiting in sync.(*Mutex).Lock: that's the whole slow request.
Finding leaked goroutines
A goroutine leak is a goroutine that's blocked and will never be unblocked. The most common cause is the "send the result on a channel, but the caller already gave up" pattern:
package main
import (
"errors"
"fmt"
"os"
"runtime"
"runtime/pprof"
"time"
)
// fetch returns the result of a slow lookup, or gives up after timeout.
// BUG: if the timeout wins, the goroutine blocks forever on `ch <- ...`
// because nobody receives from ch anymore.
func fetch(timeout time.Duration) (string, error) {
ch := make(chan string) // unbuffered
go func() {
time.Sleep(50 * time.Millisecond) // pretend to do I/O
ch <- "result"
}()
select {
case s := <-ch:
return s, nil
case <-time.After(timeout):
return "", errors.New("timeout")
}
}
func main() {
for range 10 {
fetch(10 * time.Millisecond)
}
time.Sleep(100 * time.Millisecond) // let the senders reach `ch <-`
fmt.Println("goroutines:", runtime.NumGoroutine())
p := pprof.Lookup("goroutineleak")
p.WriteTo(os.Stdout, 1)
}
$ go run -trimpath .
goroutines: 11
goroutineleak profile: total 10
10 @ 0x7ff7efb8dd6a 0x7ff7efb20f5c 0x7ff7efb20b57 0x7ff7efbf9a76 0x7ff7efb93f61
# 0x7ff7efbf9a75 main.fetch.func1+0x35 example.com/fr/leak1/main.go:19
All 10 goroutines are blocked on line 19, ch <- "result". The fix is a buffered channel, make(chan string, 1): the send always succeeds and the goroutine exits even if nobody reads the value. See Channels and select and Timeout requests with a context for more on these patterns.
How does the runtime know these goroutines are leaked and not just waiting? Writing the profile runs a special GC cycle. Normally the GC treats every goroutine's stack as a root. In leak detection mode, a goroutine blocked on a channel, sync.Mutex, sync.RWMutex, sync.WaitGroup or sync.Cond is a root only if the thing it waits on is reachable from some other goroutine that can still run (or from a global variable). The channel ch above is referenced only by the blocked goroutine itself, so no one can ever receive from it. That's a proof, not a guess: the profile has no false positives.
With debug=2 you get the stacks of all goroutines in panic format, with leaked ones marked (leaked):
p.WriteTo(os.Stdout, 2)
goroutine 1 [running]:
runtime/pprof.writeGoroutineStacks({0x7ff7efd09ee8, 0x32e0a1f72058})
runtime/pprof/pprof.go:816 +0x69
...
goroutine 7 [chan send (leaked)]:
main.fetch.func1()
example.com/fr/leak1/main.go:19 +0x36
created by main.fetch in goroutine 1
example.com/fr/leak1/main.go:17 +0x76
goroutine 18 [chan send (leaked)]:
main.fetch.func1()
example.com/fr/leak1/main.go:19 +0x36
created by main.fetch in goroutine 1
example.com/fr/leak1/main.go:17 +0x76
...
In Go 1.26 the profile was only available when building with GOEXPERIMENT=goroutineleakprofile. In Go 1.27 it's always there.
The goroutineleak profile over HTTP
Importing net/http/pprof registers the /debug/pprof/ endpoints, and since Go 1.27 that includes /debug/pprof/goroutineleak. Combine it with pprof labels and the profile tells you which request started each leaked goroutine:
package main
import (
"context"
"fmt"
"io"
"log"
"net"
"net/http"
_ "net/http/pprof" // registers /debug/pprof/* on http.DefaultServeMux
"runtime/pprof"
"time"
)
func slowSearch(q string) chan string {
ch := make(chan string)
go func() {
time.Sleep(20 * time.Millisecond)
ch <- "results for " + q // leaks if the caller already gave up
}()
return ch
}
func handleSearch(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
// Labels are inherited by goroutines started inside pprof.Do.
pprof.Do(r.Context(), pprof.Labels("handler", "search", "q", q), func(ctx context.Context) {
select {
case res := <-slowSearch(q):
fmt.Fprintln(w, res)
case <-time.After(5 * time.Millisecond):
http.Error(w, "timeout", http.StatusGatewayTimeout)
}
})
}
func get(url string) string {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return string(b)
}
func main() {
http.HandleFunc("GET /search", handleSearch)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatal(err)
}
go http.Serve(ln, nil)
base := "http://" + ln.Addr().String()
for _, q := range []string{"go", "rust", "zig"} {
get(base + "/search?q=" + q)
}
time.Sleep(50 * time.Millisecond)
fmt.Print(get(base + "/debug/pprof/goroutineleak?debug=1"))
}
goroutineleak profile: total 3
1 @ 0x7ff6b2ca79aa 0x7ff6b2c34b3c 0x7ff6b2c34737 0x7ff6b2eda749 0x7ff6b2cae961
# labels: {"handler":"search", "q":"go"}
# 0x7ff6b2eda748 main.slowSearch.func1+0x68 example.com/fr/httpleak/main.go:19
1 @ 0x7ff6b2ca79aa 0x7ff6b2c34b3c 0x7ff6b2c34737 0x7ff6b2eda749 0x7ff6b2cae961
# labels: {"handler":"search", "q":"rust"}
# 0x7ff6b2eda748 main.slowSearch.func1+0x68 example.com/fr/httpleak/main.go:19
1 @ 0x7ff6b2ca79aa 0x7ff6b2c34b3c 0x7ff6b2c34737 0x7ff6b2eda749 0x7ff6b2cae961
# labels: {"handler":"search", "q":"zig"}
# 0x7ff6b2eda748 main.slowSearch.func1+0x68 example.com/fr/httpleak/main.go:19
Without ?debug=1 the endpoint returns a binary profile for go tool pprof. You can also point go tool pprof straight at the URL, e.g. go tool pprof http://localhost:6060/debug/pprof/goroutineleak. With many leaks, -tags summarizes them by label:
$ curl -o leak.pb.gz http://localhost:6060/debug/pprof/goroutineleak
$ go tool pprof -tags leak.pb.gz
handler: Total 3 of 3 ( 100%)
3 ( 100%): search
q: Total 3 of 3 ( 100%)
1 (33.33%): go
1 (33.33%): rust
1 (33.33%): zig
Don't expose /debug/pprof/ on a public port. Serve it on a separate listener bound to localhost or an internal network, because profiles reveal code paths, and labels may contain user data.
Each request for this profile runs a full GC cycle, so it costs about as much as a runtime.GC() call. Fetching it every few minutes is fine; fetching it on every request is not.
What the leak profile misses
The detector reports a goroutine only if it can prove the goroutine can never wake up. Many real leaks don't meet that bar:
package main
import (
"fmt"
"net"
"os"
"runtime/pprof"
"sync"
"time"
)
var global = make(chan int) // reachable from a package variable
func main() {
// 1. Reported: blocked on a local mutex that is never unlocked.
var mu sync.Mutex
mu.Lock()
go func() { mu.Lock() }()
// 2. Reported: waiting on a WaitGroup nobody will call Done on.
go func() {
var wg sync.WaitGroup
wg.Add(1)
wg.Wait()
}()
// 3. Missed: the channel is reachable from a global variable,
// so in theory someone could still send on it.
go func() { <-global }()
// 4. Missed: the channel is also held by a goroutine that is
// sleeping, not blocked; it might still send one day.
ch := make(chan int)
go func() { <-ch }()
go func() {
time.Sleep(time.Hour)
ch <- 1
}()
// 5. Missed: blocked in network I/O, not on a Go sync primitive.
ln, _ := net.Listen("tcp", "127.0.0.1:0")
defer ln.Close()
go func() { ln.Accept() }()
time.Sleep(50 * time.Millisecond)
pprof.Lookup("goroutineleak").WriteTo(os.Stdout, 1)
fmt.Println("all goroutines:", pprof.Lookup("goroutine").Count())
}
$ go run -trimpath . | grep main.go
# 0x7ff7bc0527ee main.main.func1+0xe example.com/fr/leak2/main.go:18
# 0x7ff7bc05285d main.main.func2+0x3d example.com/fr/leak2/main.go:24
Only 2 of the 6 stuck goroutines are reported. Note that case 1 is reported even though main is still running: main never touches mu again, so the compiler considers it dead and the GC doesn't count main's stack as a reference.
The profile can't see:
- goroutines waiting on a channel, mutex or WaitGroup that's reachable from a global variable, or from a struct that's still in use (e.g. a long-lived server object)
- goroutines waiting on something that another live goroutine still references, even if that goroutine will never use it
- goroutines blocked in I/O (network, files, pipes), syscalls, cgo or
time.Sleep - goroutines that aren't blocked at all: a
forloop with atime.Tickerthat nobody stops, a worker that polls forever
So an empty goroutineleak profile doesn't mean there's no leak. If runtime.NumGoroutine() keeps growing, compare two regular goroutine profiles taken some time apart (go tool pprof -base old.pb.gz new.pb.gz) to see which stacks grow.
Checking for leaks in tests
Because the profile has no false positives, it works well as a check at the end of a test run. Count returns the number of leaks found by the last leak-detecting GC, so call WriteTo first:
package fetch
import (
"bytes"
"os"
"runtime/pprof"
"testing"
"time"
)
func TestFetchTimeout(t *testing.T) {
if _, err := Fetch(time.Millisecond); err == nil {
t.Fatal("expected timeout")
}
}
func TestMain(m *testing.M) {
code := m.Run()
time.Sleep(50 * time.Millisecond) // let in-flight goroutines settle
var buf bytes.Buffer
p := pprof.Lookup("goroutineleak")
p.WriteTo(&buf, 1) // runs the leak-detecting GC
if p.Count() > 0 {
os.Stderr.WriteString("leaked goroutines:\n" + buf.String())
code = 1
}
os.Exit(code)
}
Fetch is the leaky function from above. With the unbuffered channel:
$ go test -trimpath .
PASS
leaked goroutines:
goroutineleak profile: total 1
1 @ 0x7ff7d2bb39ca 0x7ff7d2b42d1c 0x7ff7d2b42917 0x7ff7d2c79d56 0x7ff7d2bba161
# 0x7ff7d2c79d55 example.com/fr/leaktest.Fetch.func1+0x35 example.com/fr/leaktest/fetch.go:12
FAIL example.com/fr/leaktest 1.105s
FAIL
After changing it to make(chan string, 1):
$ go test -trimpath -count=1 .
ok example.com/fr/leaktest 1.810s
Labels in tracebacks
pprof labels are key-value pairs attached to a goroutine with pprof.Do (or pprof.SetGoroutineLabels). Goroutines started inside pprof.Do inherit them. They were designed to split CPU profiles by request type, but are just as useful for debugging.
Go 1.26 added the tracebacklabels GODEBUG setting and Go 1.27 turned it on by default: labels are now printed in the goroutine header of panic tracebacks, GOTRACEBACK=all crash dumps and debug=2 goroutine profiles:
package main
import (
"context"
"runtime/pprof"
"time"
)
func sum(items []int) int {
total := 0
for i := 0; i <= len(items); i++ { // bug: <= instead of <
total += items[i]
}
return total
}
func runJob(ctx context.Context, tenant string, items []int) {
labels := pprof.Labels("job", "report", "tenant", tenant)
pprof.Do(ctx, labels, func(ctx context.Context) {
// Goroutines started here inherit the labels.
go sum(items)
})
}
func main() {
runJob(context.Background(), "acme corp", []int{1, 2, 3})
time.Sleep(time.Second)
}
panic: runtime error: index out of range [3] with length 3
goroutine 7 [running] {job: report, tenant: "acme corp"}:
main.sum(...)
example.com/fr/labels/main.go:12
created by main.runJob.func1 in goroutine 1
example.com/fr/labels/main.go:21 +0x87
exit status 2
Now the crash report says which tenant's job crashed. Values are quoted only when they contain spaces or special characters.
A gotcha: pprof.Do restores the previous labels in a defer. If the panic happens directly inside the pprof.Do callback (not in a goroutine started from it), the deferred restore runs before the traceback is printed and the labels are gone. Goroutines started inside pprof.Do, as above, keep them.
The new default depends on the go line in go.mod: a module that says go 1.26 or older keeps the old behavior (no labels). If labels might contain sensitive data (user emails, tokens) that must not end up in crash logs, turn it off:
$ GODEBUG=tracebacklabels=0 go run .
panic: runtime error: index out of range [3] with length 3
goroutine 20 [running]:
main.sum(...)
or permanently with godebug tracebacklabels=0 in go.mod, or //go:debug tracebacklabels=0 above package main.
Summary
| Problem | Tool |
|---|---|
| A rare slow request, an occasional latency spike | trace.FlightRecorder, WriteTo when the request is slow |
| Why was it slow: lock, I/O, GC, scheduler? | go tool trace, or go tool trace -pprof=sync|net|sched |
| Goroutines stuck forever on channels or locks | pprof.Lookup("goroutineleak"), /debug/pprof/goroutineleak |
| Goroutine count grows but the leak profile is empty | diff two goroutine profiles with go tool pprof -base |
| Which request or tenant did a goroutine belong to? | pprof.Do labels, shown in profiles and (Go 1.27) tracebacks |
Practical tips:
- Leave a flight recorder running in production with a small window, and snapshot on slow requests, 5xx errors and deadline exceeded errors. Rate-limit the snapshots.
- Add
trace.NewTask/trace.StartRegionto request handlers so the slow request is easy to find in the trace. - Check the
goroutineleakprofile inTestMainor a CI job, and fetch it periodically from production. - Remember what it can't see: globals, I/O, sleeping or spinning goroutines.
- Label goroutines with
pprof.Doat request boundaries, but keep secrets out of labels: they now end up in crash logs.