Lesson 9 of 9 · 28m
Deadlock Patterns, Prevention, and Postmortems
Recognize circular waits, abandoned sends, lock-order inversion, and shutdown deadlocks before they freeze production — and debug them systematically when they do.
Deadlocks rarely announce themselves as deadlocks. Deploys hang, health checks time out, queues stop moving, and someone says the service is 'stuck.' By the time you open a shell, the goroutine dump is the only honest witness. Most deadlocks are variations on a small set of shapes. Learn the shapes and code review becomes much sharper.
Shape one: circular wait
One path holds the database lock and wants the cache lock; another does the reverse. Establish one lock order, or copy data out of one critical section before entering the next:
// path 1: dbMu.Lock(); cacheMu.Lock()
// path 2: cacheMu.Lock(); dbMu.Lock()Shape two: sending to a receiver that left
select {
case result <- value:
case <-ctx.Done(): return ctx.Err()
}Without the cancellation case, a sender whose downstream exited waits forever. Shutdown waits for the sender; the process waits for shutdown. Audit every send with the question: what if nobody is receiving?
Shape three: WaitGroup misuse
Add after Wait starts, missing Done, and spawning work after close can freeze or panic shutdown:
wg.Add(1)
go func() { defer wg.Done(); work() }()
wg.Wait()Keep Add before the goroutine starts and pair Done with defer immediately. If Add moves inside the child, a fast Wait can return before the child registers itself.
Shape four: confused close ownership
With multiple producers, one premature close panics other senders; no close strands receivers. Centralize closure:
go func() { wg.Wait(); close(results) }()The closer waits for all producers. No individual producer owns termination of the shared channel.
Debug the wait graph
Capture state before restarting:
curl -s http://127.0.0.1:6060/debug/pprof/goroutine?debug=2 > pre-restart.txtGroup goroutines by stack. Identify what each group waits on: mutex, channel send, channel receive, Wait, network. Then draw the cycle. A deadlock is not a mystery; it is a graph you have not drawn yet.
Field notes
- Go detects deadlock only when every goroutine is blocked. Partial deadlocks in live servers still require your own diagnostics.
- A timeout converts deadlock into recurring latency unless the underlying wait cycle is removed.
- Avoid callbacks while holding locks; you do not control what the callback waits on.
- The best postmortem artifact is the goroutine dump plus a diagram of wait edges. Fix the graph, not the symptom.
Was this lesson helpful?