Goroutines are one of the most useful features of Go. They allow developers to run multiple tasks concurrently without managing operating system threads directly. Creating a goroutine is simple, but managing its lifetime correctly requires attention.
A goroutine should normally finish its work when it is no longer needed. However, some goroutines remain blocked forever because they are waiting for a channel message, a lock, or another synchronization event that will never happen. These goroutines are called goroutine leaks.
Goroutine leaks can be difficult to identify in production. An application may continue working normally while the number of goroutines slowly increases. Over time, leaked goroutines retain memory, increase garbage collection work, and consume resources that could otherwise be used by active requests.
Go provides several tools for investigating this problem, including runtime.NumGoroutine(), goroutine stack profiles, and the newer goroutine leak profile available through runtime/pprof.
The goroutine leak profile is particularly useful because it helps identify goroutines that the runtime can determine are permanently blocked. It was introduced experimentally in Go 1.26 and became generally available in Go 1.27.
This article explains how goroutine leaks happen, how to detect them using Go's profiling tools, and how to fix common concurrency problems.
What Is a Goroutine Leak?
A goroutine leak occurs when a goroutine continues to exist even though its intended work can no longer be completed.
Unlike a goroutine that is temporarily waiting for a network response or channel message, a leaked goroutine has no possible path to resume execution.
Consider this example:
package main
import (
"fmt"
"time"
)
func worker(ch chan int) {
fmt.Println("Worker started")
value := <-ch
fmt.Println("Received:", value)
}
func main() {
ch := make(chan int)
go worker(ch)
time.Sleep(2 * time.Second)
fmt.Println("Main function completed")
}
The worker goroutine waits for a value from the channel. However, the main function never sends anything to that channel.
After the main function finishes, the program exits, so this small example does not demonstrate a long-running production leak. In a server, however, the process may remain alive for hours or days, and the blocked goroutine can remain in memory throughout that time.
The problem becomes more serious when the application creates one such goroutine for every incoming request or background operation.
Why Goroutine Leaks Are Difficult to Find
Go makes it easy to start concurrent operations:
go processRequest()
The difficult part is knowing when those operations should stop.
A goroutine may become stuck for several reasons:
Waiting for a channel message that will never arrive.
Sending data to a channel that no longer has a receiver.
Waiting for a mutex that can never be unlocked.
Waiting on a synchronization condition that can no longer be satisfied.
Continuing to run after the request that started it has already been cancelled.
A goroutine leak does not always produce an immediate error. The application may continue accepting requests and returning successful responses.
Over time, however, the leaked goroutines can retain references to request data, buffers, objects, and other resources. This increases memory usage and can add pressure to the garbage collector.
For this reason, monitoring only CPU usage or HTTP response time may not reveal the underlying problem.
Understanding the New Goroutine Leak Profile
Go 1.27 introduces a dedicated goroutine leak profile through the runtime/pprof package.
The profile is named goroutineleak and reports goroutines that the runtime has identified as permanently blocked.
The important difference is that the regular goroutine profile reports all currently existing goroutines, while the leak profile focuses on goroutines that meet the runtime's leak-detection criteria.
The runtime uses garbage collector reachability analysis to identify certain blocked goroutines that cannot be resumed.
For example, suppose a goroutine is blocked while sending to a channel. If the channel and the synchronization conditions required to receive from it are no longer reachable from any runnable goroutine, the runtime can determine that the blocked goroutine cannot resume.
This makes the leak profile more useful than simply looking at the total goroutine count.
However, it does not detect every possible goroutine leak. It focuses on a large class of permanently blocked goroutines involving channels and synchronization primitives from the sync package.
Goroutines blocked on network operations, operating system calls, or other situations may not be classified as leaked by this profile.
Creating a Goroutine Leak Example
To understand how the leak profile works, consider a worker function that processes multiple items concurrently.
The following example contains a common channel-related mistake.
package main
import (
"fmt"
"time"
)
type Result struct {
Value int
}
func processItem(value int) Result {
time.Sleep(100 * time.Millisecond)
return Result{
Value: value * 2,
}
}
func processItems(items []int) []Result {
results := make(chan Result)
for _, item := range items {
go func(value int) {
result := processItem(value)
results <- result
}(item)
}
output := make([]Result, 0, len(items))
for i := 0; i < 2; i++ {
output = append(output, <-results)
}
return output
}
func main() {
items := []int{1, 2, 3, 4, 5}
results := processItems(items)
fmt.Println("Processed results:", results)
time.Sleep(time.Minute)
}
The function starts five worker goroutines but receives only two results.
After two workers send their results, the remaining workers become blocked while attempting to send to the unbuffered channel.
Because the receiving function has already returned, no goroutine remains to receive those values.
The application now has three goroutines that cannot complete their send operations.
This is a typical goroutine leak caused by incorrect channel lifecycle management.
Fixing the Channel-Related Leak
There are multiple ways to fix this problem. One simple approach is to use a buffered channel with enough capacity for every worker result.
func processItems(items []int) []Result {
results := make(chan Result, len(items))
for _, item := range items {
go func(value int) {
result := processItem(value)
results <- result
}(item)
}
output := make([]Result, 0, len(items))
for i := 0; i < len(items); i++ {
output = append(output, <-results)
}
return output
}
The channel can now hold all the worker results, even if the sending goroutines finish before the receiver processes them.
Another approach is to ensure that the function receives all results before returning.
The correct solution depends on the application's requirements. A buffered channel is not automatically the best choice for every concurrent workflow.
For larger applications, context cancellation, worker pools, and structured shutdown logic may provide better control.
Detecting Leaks With runtime.NumGoroutine()
Before using the new leak profile, Go developers commonly monitor the number of active goroutines.
The runtime.NumGoroutine() function returns the current number of goroutines.
For example:
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
go func() {
for {
time.Sleep(time.Second)
}
}()
for i := 0; i < 5; i++ {
fmt.Println(
"Active goroutines:",
runtime.NumGoroutine(),
)
time.Sleep(2 * time.Second)
}
}
This example starts a background goroutine and periodically prints the total number of goroutines.
In a production application, developers can expose this value through application metrics and monitor it over time.
A steadily increasing goroutine count may indicate a leak, especially when request traffic and workload remain relatively stable.
However, NumGoroutine() does not identify which goroutines are leaking. A high goroutine count may be completely normal during periods of heavy traffic.
It should be treated as an early warning signal rather than proof of a leak.
Capturing the Regular Goroutine Profile
The regular goroutine profile provides stack traces for all current goroutines.
It is useful when you need to understand where goroutines are running or blocked.
You can capture the profile directly through runtime/pprof:
package main
import (
"os"
"runtime/pprof"
)
func main() {
file, err := os.Create("goroutines.prof")
if err != nil {
panic(err)
}
defer file.Close()
profile := pprof.Lookup("goroutine")
if err := profile.WriteTo(file, 2); err != nil {
panic(err)
}
}
The debug value of 2 requests detailed goroutine stack traces.
You can also use the go tool pprof command to inspect supported profile formats.
For a long-running HTTP service, the net/http/pprof package provides a convenient way to collect profiles without changing application code every time you need to investigate a problem.
Exposing Profiles Through net/http/pprof
The net/http/pprof package registers HTTP handlers that expose runtime profiling information.
A basic setup looks like this:
package main
import (
"log"
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
log.Println(
http.ListenAndServe(
"localhost:6060",
nil,
),
)
}()
startApplication()
}
func startApplication() {
select {}
}
The blank import registers the profiling handlers on the default HTTP mux.
Once the application is running, you can access the profiling endpoints locally.
The regular goroutine profile is available at:
http://localhost:6060/debug/pprof/goroutine
For detailed stack traces, use:
http://localhost:6060/debug/pprof/goroutine?debug=2
The profiling endpoint should not be exposed publicly without appropriate protection. In production, use a private listener, authenticated access, or an internal monitoring network.
Collecting the Goroutine Leak Profile
On Go 1.27 and later, the goroutine leak profile is available through runtime/pprof and net/http/pprof.
If your application already imports net/http/pprof, the leak profile is exposed at:
http://localhost:6060/debug/pprof/goroutineleak
You can collect it using curl:
curl http://localhost:6060/debug/pprof/goroutineleak -o goroutine-leaks.prof
Then inspect the profile:
go tool pprof goroutine-leaks.prof
Inside the pprof interactive interface, you can use commands such as:
(pprof) top
(pprof) list processItems
The top command identifies functions associated with the reported leaked goroutines.
The list command displays source code around the relevant function when source information is available.
This can help identify the exact channel operation or synchronization point where goroutines are becoming permanently blocked.
The leak profile is especially useful because it filters for goroutines the runtime has classified as leaked instead of showing every active goroutine.
Capturing the Profile Programmatically
You can also collect the leak profile directly from Go code using runtime/pprof.
For example:
package main
import (
"os"
"runtime/pprof"
)
func captureLeakProfile() error {
profile := pprof.Lookup("goroutineleak")
if profile == nil {
return nil
}
file, err := os.Create("goroutine-leaks.prof")
if err != nil {
return err
}
defer file.Close()
return profile.WriteTo(file, 0)
}
This function checks whether the profile is available and writes it to a file.
The profile lookup can return nil when the runtime does not provide that profile. This is important when maintaining applications that may run on different Go versions.
The leak profile performs a garbage collection cycle as part of its detection process. It should therefore be collected deliberately rather than treated as a lightweight metric to poll continuously.
For most applications, the HTTP profiling endpoint is more convenient for manual investigation and operational diagnostics.
Understanding What the Leak Profile Can and Cannot Detect
The new profile is powerful, but developers should understand its detection boundaries.
The runtime identifies goroutines that are permanently blocked on synchronization primitives that can no longer be reached by runnable goroutines or other goroutines that could unblock them.
Examples include certain blocked channel sends, channel receives, mutex waits, and condition-variable waits.
However, not every goroutine that appears stuck is necessarily a leak.
Consider a goroutine waiting for a network response. It may be blocked for several seconds because the remote service is slow. The regular goroutine profile will show it, but the leak profile may not classify it as leaked.
Similarly, a goroutine waiting on a channel connected to a global worker may be blocked for a long time but still have a possible path to resume.
The leak profile is therefore a useful diagnostic tool, not a replacement for understanding the application's concurrency design.
Testing Goroutine Leaks Before Production
Production profiling is valuable, but developers should also detect leaks during development and testing.
A useful option is the go.uber.org/goleak package, which checks whether unexpected goroutines remain after a test completes.
For example:
package worker_test
import (
"testing"
"go.uber.org/goleak"
)
func TestWorker(t *testing.T) {
defer goleak.VerifyNone(t)
// Run the worker and verify its expected behavior.
}
The test checks for goroutines that remain after the test finishes.
In larger test suites, you can also configure goleak to run through a TestMain function.
Another useful tool is the standard library's testing/synctest package, introduced in Go 1.25. It provides a controlled environment for testing concurrent code and time-dependent behavior.
It can make certain concurrency tests more predictable, particularly when goroutines interact through channels, timers, and other synchronization mechanisms.
These tools serve different purposes:
Tool | Main Purpose |
|---|
runtime.NumGoroutine() | Monitors the current number of goroutines |
goroutine profile | Shows stack traces of all current goroutines |
goroutineleak profile | Identifies goroutines the runtime has classified as leaked |
go.uber.org/goleak | Detects unexpected goroutines remaining after tests |
testing/synctest | Helps test concurrent behavior in a controlled environment |
Using these tools together provides better coverage than relying on a single goroutine count or profile.
Common Goroutine Leak Patterns
Sending to a Channel Without a Receiver
A goroutine may block forever when sending to an unbuffered channel that no longer has an active receiver.
The solution is to coordinate sender and receiver lifetimes, use an appropriate buffer, or provide a cancellation mechanism.
Receiving From a Channel That Is Never Closed
A goroutine waiting for a value from a channel may remain blocked when no sender can provide another value.
If the channel represents a stream that has finished, close it from the component responsible for sending values.
Closing a channel is not appropriate when multiple components may independently send to it. Channel ownership should be clearly defined.
Forgetting Context Cancellation
A request may start several background operations. If the request finishes but the background goroutines continue waiting for work, they may remain active unnecessarily.
Use context cancellation to communicate when the work should stop.
For example:
func startWorker(ctx context.Context) {
go func() {
for {
select {
case <-ctx.Done():
return
default:
processNextItem()
}
}
}()
}
For production use, ensure processNextItem does not perform long-running work without checking cancellation. Otherwise, the worker may not stop promptly.
Forgetting to Release Locks
A goroutine waiting for a mutex may remain blocked if another execution path fails to unlock it.
Use defer when appropriate to ensure that locks are released after a protected operation:
mu.Lock()
defer mu.Unlock()
updateSharedData()
Be careful not to hold locks while performing slow network requests or other operations that do not need synchronization.
Leaving Background Workers Running After Shutdown
Long-running services often start background workers for queue processing, monitoring, and scheduled tasks.
If the application shuts down without notifying these workers, they may remain blocked or continue running longer than necessary.
Use a shared shutdown context, wait groups, and explicit cleanup procedures to manage their lifecycle.
Best Practices for Preventing Goroutine Leaks
The following practices help make concurrent Go applications easier to maintain:
Give every long-running goroutine a clear lifecycle.
Use context.Context to communicate cancellation.
Define which component owns channel creation and closure.
Avoid sending to channels after their receivers have stopped.
Close channels only from the component responsible for sending.
Use sync.WaitGroup when the application needs to wait for a group of goroutines.
Avoid holding locks during slow operations.
Monitor goroutine counts in long-running services.
Capture regular goroutine profiles when counts increase unexpectedly.
Use the goroutine leak profile when running Go 1.27 or later.
Add leak checks to automated tests.
Test shutdown behavior, not just successful execution.
A useful design principle is that every goroutine should have a clear reason to start and a clear condition under which it can stop.
Advantages and Limitations of the Goroutine Leak Profile
The new profile makes it easier to identify a significant class of goroutine leaks without manually inspecting every stack trace.
It is particularly useful for long-running services because it can help identify permanently blocked goroutines that accumulate over time.
It also integrates with the existing Go profiling ecosystem, making it available through runtime/pprof and net/http/pprof.
However, it does not detect every possible leak. Goroutines blocked on network operations or other external events may not be classified as leaked. It also cannot replace proper concurrency design, cancellation, and lifecycle management.
For this reason, developers should combine leak profiling with regular goroutine profiles, application metrics, automated tests, and code reviews.
Summary
Goroutine leaks can gradually affect the performance and reliability of Go applications. They often occur when goroutines wait indefinitely for channel messages, locks, or other synchronization events that will never happen.
Go provides several ways to investigate these problems. runtime.NumGoroutine() helps monitor goroutine counts, regular goroutine profiles reveal stack traces, and the goroutineleak profile in Go 1.27 identifies a large class of permanently blocked goroutines.
Developers can collect leak profiles through runtime/pprof or the net/http/pprof endpoint and inspect them with go tool pprof.
The best approach is to prevent leaks through clear goroutine lifecycles, context cancellation, correct channel management, and automated testing. With these practices and the new runtime profiling support, developers can identify concurrency problems earlier and build more reliable Go services.
Join the conversation! Your thoughts help the community grow.