All posts

Fix MemoryError in Go in Production

Diagnose and fix out-of-memory issues in Go production services using pprof, goroutine leaks, and allocation optimization.

Go Memory Issues in Production

Go doesn't throw "MemoryError" like Python — instead, the runtime panics with runtime: out of memory or the OS kills the process. Here's how to diagnose and fix it.

Enable pprof

Add the profiling endpoint to your service:

import _ "net/http/pprof"

func main() {
    go func() {
        log.Println(http.ListenAndServe(":6060", nil))
    }()
    // ... your main server
}

Then capture a heap profile:

go tool pprof http://localhost:6060/debug/pprof/heap
(pprof) top 10

Goroutine Leaks

The most common Go memory issue — goroutines that never exit:

// LEAK: goroutine blocked forever if ctx is never cancelled
func startWorker(ch chan Data) {
    go func() {
        for data := range ch {
            process(data)
        }
    }()
    // If ch is never closed, this goroutine lives forever
}

// FIX: use context for cancellation
func startWorker(ctx context.Context, ch chan Data) {
    go func() {
        for {
            select {
            case data, ok := <-ch:
                if !ok { return }
                process(data)
            case <-ctx.Done():
                return
            }
        }
    }()
}

Large Allocations

// BAD — allocates entire file in memory
data, _ := os.ReadFile("huge.csv")

// GOOD — stream it
file, _ := os.Open("huge.csv")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
    processLine(scanner.Text())
}

Check goroutine counts in production:

curl http://localhost:6060/debug/pprof/goroutine?debug=1 | head -5

Bugsly captures Go panics including runtime: out of memory with goroutine dumps, making it easy to see which goroutines were running when memory ran out.

Try Bugsly Free

Track up to 100 issues per month on the free plan, with unlimited events and no credit card required.

Get Started Free