Repurposing GC Reachability to Catch Partial Deadlocks: Inside Go 1.27's goroutineleak Profiler
Go 1.27 ships the goroutineleak profiler in runtime/pprof and net/http/pprof. Rather than sampling stacks or guessing from goroutine counts, it adapts Go's tri-color mark-and-sweep GC to compute an inductive liveness fixpoint LIVE+(g)—pinpointing permanently blocked goroutines in production with near-zero false positives, while carrying sharp boundaries around memory overreach, O(n²) daisy-chains, and non-channel blocking.
1. Why Existing Goroutine Diagnostics Miss Production Leaks
Go's runtime already catches global deadlocks—when every goroutine in the process is blocked—by crashing immediately. In production services, global deadlocks are rare. The far more common failure mode is a partial deadlock (goroutine leak): a subset of goroutines parks forever on channels or sync primitives while the rest of the service keeps serving requests. Each leaked goroutine retains its stack and whatever heap subgraph its local variables reference, steadily inflating memory footprint and forcing the garbage collector to burn extra CPU—especially under tight GOMEMLIMIT budgets.
Until Go 1.27, engineers had three imperfect tools:
| Approach | Strength | Structural Blind Spot |
|---|---|---|
Unit-test guards (goleak, testing/synctest) | High precision in deterministic tests | Cannot observe production traffic, rare interleavings, or cross-service timing |
Standard goroutine pprof profile | Always available in production | Cannot distinguish legitimately parked goroutines (e.g., high concurrency) from permanently leaked ones |
| Manual heap / goroutine trend alerts | Catches large, fast-growing leaks | Slow leaks slip through for months; root-cause still requires manual stack forensics |
Previewed behind GOEXPERIMENT=goroutineleakprofile in Go 1.26 and promoted to GA in Go 1.27 (Go Turns 17, Goroutine Leak Profiles), the goroutineleak profiler closes this gap. Originating from a collaboration between Aarhus University, Washington University in St. Louis, and Uber ("Dynamic Partial Deadlock Detection and Recovery via Garbage Collection", Saioc et al., ASPLOS 2025), it reframes partial deadlock detection as a graph reachability problem that the garbage collector already knows how to solve.
2. Formalizing Liveness as a Least Fixpoint
When is a blocked goroutine provably unrecoverable? Suppose goroutine is blocked on a set of concurrency primitives (a single channel for send/receive, multiple channels for a blocking select, or a sync primitive). For to ever make progress again, some other goroutine that is still live must eventually perform a complementary operation on at least one primitive —which requires holding a memory reference to .
The ASPLOS 2025 paper formalizes this as an inductive predicate, reachable liveness :
- Base case: If is not blocked on a tracked concurrency primitive (, including runnable goroutines and goroutines blocked in syscalls or I/O), then holds.
- Inductive step: If there exists another goroutine such that holds and can transitively reach some primitive in memory (or is reachable from global roots), then holds.
is defined as the least fixpoint satisfying these two rules. Any goroutine for which does not hold has no reachable unblocker anywhere in the program—it is classified as leaked.
Two theoretical properties govern every practical trade-off that follows:
- Soundness holds (): If a goroutine could genuinely unblock in some future execution, some live goroutine must hold a reference to its blocking primitive, so must be true. Consequently, the profiler produces near-zero false positives.
- Completeness does not hold (): Holding a pointer to a channel does not guarantee a goroutine will ever send or receive on it. False negatives are structurally possible whenever an unused primitive stays reachable.
3. How Go 1.27 Adapts the Tri-Color Mark-and-Sweep GC
Go's runtime already runs a concurrent tri-color mark-and-sweep collector (using the Green Tea GC by default since Go 1.26). Computing requires no separate graph engine—only four surgical adjustments during a GC cycle triggered by a goroutineleak profile request (Goroutine Leak Profiles):
- Shrink the initial mark roots. A regular GC treats every goroutine stack (plus globals) as an initial mark root so nothing reachable from a parked stack is ever swept. During a
goroutineleakcycle, the runtime initially roots only unblocked goroutines and globals; goroutines parked on tracked concurrency primitives are withheld. - Run the standard concurrent mark phase. Without changing the core tri-color scanner or write barrier, the GC traces all objects transitively reachable from those initial roots—implicitly marking every channel, mutex, wait group, and condition variable accessible to currently live goroutines.
- Iterate to a fixpoint. When marking drains, the runtime inspects the withheld blocked goroutines. Any goroutine waiting on at least one primitive that has now been marked is promoted to a mark root, and marking resumes. Each round discovers goroutines unblocked by the previous round until an entire pass promotes zero new goroutines.
- Tag
_Gleakedand perform a safety rescan. Every blocked goroutine still unpromoted at the fixpoint is tagged with status_Gleaked. Crucially, Go's shipped profiler does not kill or reclaim leaked goroutines (unlike the "Recovery" half of the Golf research prototype in ASPLOS 2025). Instead, the runtime adds all_Gleakedgoroutines as mark roots and runs one final marking pass so the GC's live heap set matches a regular cycle. Once GC finishes,runtime/pprofcaptures a goroutine profile filtered strictly to_Gleakedstacks.
Because these extra steps only execute when a goroutineleak profile is explicitly requested, idle overhead is zero.
4. Production Usage & Canonical Leak Patterns
If your service already mounts net/http/pprof, the endpoint /debug/pprof/goroutineleak is exposed automatically in Go 1.27—no instrumentation or build flags required. You can also query pprof.Lookup("goroutineleak") programmatically.
package main
import (
"errors"
"log"
"net/http"
_ "net/http/pprof"
"time"
)
type result struct {
val int
err error
}
func processBatch(items []int) ([]int, error) {
// Unbuffered channel: if an early error exits the loop below,
// all remaining worker goroutines block forever on ch <- ...
ch := make(chan result)
for _, item := range items {
go func(v int) {
time.Sleep(10 * time.Millisecond)
if v == 5 {
ch <- result{err: errors.New("bad item")}
return
}
ch <- result{val: v * 2}
}(item)
}
out := make([]int, 0, len(items))
for range len(items) {
r := <-ch
if r.err != nil {
return nil, r.err // Early return strands remaining senders
}
out = append(out, r.val)
}
return out, nil
}
func main() {
go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()
for {
_, _ = processBatch([]int{1, 2, 3, 4, 5, 6, 7, 8})
time.Sleep(time.Second)
}
}Inspecting the live service with go tool pprof isolates the exact leaking send line rather than dumping every parked goroutine in the process:
curl -s http://localhost:6060/debug/pprof/goroutineleak > leak.prof
go tool pprof -list=processBatch leak.profSizing the channel buffer to make(chan result, len(items)) eliminates the leak.
Beyond early returns, the official Go blog catalogs industrial leaks from CockroachDB, etcd, Kubernetes, and Moby that goroutineleak catches directly:
- Channel/timeout abandonment: A
selectwaits on<-chor<-ctx.Done(); when the context cancels first, the worker sending on an unbufferedchleaks permanently. - Unclosed
range chor zero-worker deadlocks: Workers loopingfor item := range chleak if the producer forgetsclose(ch); conversely, a producer sending intochleaks ifworkers == 0. - Hidden lifecycle contracts behind interfaces: A concrete type behind a
Workerinterface spawns a background loop inStart()that only exits whenStop()closesdone. Once the caller drops the interface without callingStop(), the background goroutine'sdonechannel becomes unreachable andgoroutineleakflags the exactselect. - Missing
Unlockbeforebreak(CockroachDB): Acquiringsync.Mutexinside a loop and breaking out on aclosedflag without unlocking leaks subsequent callers blocked inmu.Lock(). - Channel + Mutex lock-order inversion (Kubernetes & Moby): Goroutine A holds a
sync.Mutexand performs a blocking send on an unbuffered channel, while Goroutine B waits to acquire that same mutex before draining or closing the channel. Because neither is runnable and no external live goroutine references either primitive, both are caught simultaneously as a 2-goroutine partial deadlock.
In the ASPLOS 2025 evaluation, the Golf prototype detected 94% of partial deadlocks across 73 microbenchmarks, surfaced 180 of 357 known partial deadlocks across 3,111 Uber Go packages, and caught 252 partial deadlocks from 3 real bugs in a production Uber microservice within 24 hours.
5. Performance Pathologies, False Negatives, and Runtime Caveats
A diagnostic built on GC reachability inherits both the strengths and the blind spots of reachability analysis.
5.1 The Daisy-Chain Pathology ( Worst Case)
Memory overhead for bookkeeping is negligible, but GC cycle latency during a profile can degrade in a daisy-chain: runnable holds primitive blocking , which holds blocking , up to .
- Intrinsic serialization: Proving is live requires marking memory reachable from first, forcing sequential marking rounds.
- Quadratic inspection: In the current runtime implementation, the end of each marking round scans all remaining withheld blocked goroutines, yielding up to inspection steps in a single profiling GC cycle.
While the second cost can be optimized with finer indexing in future Go releases, the serialization dependency is fundamental. In production, the practical defense is cadence: because a leaked goroutine remains leaked indefinitely, polling /debug/pprof/goroutineleak periodically (e.g., every 4 hours, as suggested by the Go team) keeps amortized overhead near zero without sacrificing detection.
5.2 Memory Overreach (Structural False Negatives)
Because globals and always-running goroutines are roots, any concurrency primitive transitively reachable from them will never trigger a leak report—even if no code path will ever touch it again.
A subtle industrial case highlighted in the Golf paper is a runaway helper goroutine sharing a parent struct: if a long-lived heartbeat goroutine holds *Dispatcher solely to increment d.ticks every second, it keeps d.ch reachable on the heap forever. Any goroutine permanently blocked on d.ch will be conservatively marked live. Scoping struct lifetimes narrowly—passing only the fields a background goroutine actually needs—directly improves leak observability.
5.3 Unsupported Blocking & the testing/synctest Interaction Bug
For soundness, goroutineleak only tracks Go's first-class concurrency primitives:
- Tracked: channel send/receive (including
nilchannels), blockingselectstatements (nodefault, including emptyselect{}), andsync.Mutex,sync.RWMutex,sync.WaitGroup, andsync.Cond. - Not tracked: network or file I/O, direct syscalls, and custom user-space spinlocks or atomic wait loops not built on the primitives above.
One fresh runtime caveat worth noting if you combine Go 1.27's new tools in tests: golang/go#83065 (filed November 2026, reproduced on go1.27.3 and go1.27.4) reports that taking a goroutineleak profile inside a testing/synctest bubble containing a leaked goroutine can freeze virtual time and hang the test. The root cause is that changegstatus treats _Gleaked as running—incorrectly incrementing bubble.running—and the subsequent GC resets the status without decrementing the counter, so the bubble never becomes durably idle. Until that fix lands in a point release, avoid invoking goroutineleak profiling inside synctest bubbles.
6. Operational Playbook
- Layer your defenses instead of picking one tool. Keep
goleakandtesting/synctestin unit tests for deterministic, fast feedback on known concurrency paths, and add low-frequencygoroutineleakscraping (e.g., every 4 hours) to your continuous profiling fleet in production. - Design for reachability hygiene. Avoid package-level global channels and avoid passing fat "god structs" to long-lived background goroutines; both mask leaks via memory overreach.
- Treat every hit as high-signal. Unlike raw
goroutineprofiles that require eyeballing growth curves, a non-emptygoroutineleakprofile almost always indicates a real, permanent partial deadlock—making it suitable for automated issue filing or low-noise engineering alerts.
References
- Goroutine Leak Profiles (Vlad Saioc, The Go Blog, 2026-09-02)
- Go Turns 17 (Austin Clements, The Go Blog, 2026-11-10)
- Go 1.27 Release Announcement (The Go Blog, 2026-08-19)
- Dynamic Partial Deadlock Detection and Recovery via Garbage Collection (Saioc et al., ASPLOS 2025)
- golang/go#74609: runtime/pprof, runtime: new goroutine leak profile
- golang/go#83065: runtime: goroutineleak profile freezes synctest bubbles that contain a leaked goroutine
Related Posts
GitHub Rubicon: Coordinating Only Ref Updates—Benchmarking Repo-Wide Locks vs. Per-Ref CAS in Go
GitHub's new Git storage architecture, Rubicon, stores immutable objects in Azure Blob Storage, delegates reference and pack manifest transactions to Ref-CAS, and uses disposable virtual replicas and dedicated compaction nodes for reads, writes, and maintenance. Based on the full official post, this article explains the publication boundary and the workload assumptions behind per-ref parallelism, accompanied by a runnable minimal Go implementation: SHA-256 immutable objects, file and directory fsync before CAS, an ordered in-memory per-ref log, and a repo-wide mutex baseline. Across 36 runs, all 216,000 acknowledged pushes passed in-process verification. At N=32, median throughput on distinct refs was 15,216 push/s vs. 4,397 for the repo-wide lock; on the same ref, it dropped to 858 vs. 3,937 with a 93.6% attempt conflict rate. The ref log is not durable, so this proves neither crash recovery nor distributed consensus, and the numbers cannot be compared against GitHub's internal 7,200 push/s figure.
Splitting encoding/json Into Two Layers and Putting It Back Together: Layering and Compatibility in Go's json/v2
Go 1.27 runs the old encoding/json package on top of v2: syntax (jsontext) and semantics (v2) are split apart, every behavioral difference is an option, and old and new code coexist in the same dependency graph without a flag day.
KV-Cache-Aware Inference Routing: Reading Kinference and Benchmarking in Go
A walkthrough of Kinference's PredictedTTFT and InferencePolicy, paired with a Go mock benchmark comparing round-robin, prefix-affinity, and combined scoring under hot-prefix workloads.