---
title: Goroutine Leak Prevention
impact: HIGH
impactDescription: prevents memory exhaustion and zombie processes
tags: go, concurrency, stability, quality
---

## Goroutine Leak Prevention

Always ensure that a goroutine has a clear termination path, typically via a `context.Context` or a close channel. Goroutines that block indefinitely on channel operations or I/O without a timeout cause memory leaks.

**Incorrect (leaky goroutine):**

```go
func StartWatcher(ch chan string) {
    go func() {
        for msg := range ch { // Blocks forever if ch is never closed
            fmt.Println(msg)
        }
    }()
}
```

**Correct (context-aware goroutine):**

```go
func StartWatcher(ctx context.Context, ch chan string) {
    go func() {
        for {
            select {
            case <-ctx.Done():
                return // Exit cleanly when context is cancelled
            case msg, ok := <-ch:
                if !ok {
                    return // Exit when channel is closed
                }
                fmt.Println(msg)
            }
        }
    }()
}
```

**Benefits:**
- Prevents memory leaks and resource exhaustion
- Ensures clean application shutdown
- Makes concurrent code more predictable and testable

**Tools:** goleak, golangci-lint
