Go Concurrency: Goroutines, Channels and One Owner
Goroutines, channels, select and the mistakes that leak or race, from building Crystal, a Raft key-value store whose core is one goroutine.
Goroutines are cheap, races are not
People coming to Go from Java tend to think of goroutines as threads. They behave differently in one way that matters and the same way in another.
A goroutine is scheduled by the Go runtime, which spreads many goroutines over a few OS threads. One starts with a stack of a few kilobytes, so running a hundred thousand of them on a laptop is normal, and you couldn’t do that with threads. But goroutines share memory like threads do, so a data race is exactly as real.
I write a lot of my backend code in Go, and the place I learned the most about this was Crystal, my Raft key-value store. A consensus node is a pile of concurrent events, and getting it wrong doesn’t crash anything. Two replicas just quietly disagree. Everything below comes back to that project.
Channels
Go’s line is “don’t communicate by sharing memory, share memory by communicating”. A channel is a typed pipe that is safe to use from many goroutines.
results := make(chan User, 1)
go func() { results <- loadUser(id) }()
user := <-results
On an unbuffered channel, the sender waits until a receiver takes the value, which makes it a handoff. A buffered channel lets the sender continue until the buffer is full. I default to unbuffered and add a buffer when there is a reason, usually that the sender must never block (more on that below).
select
select waits on several channels at once and runs whichever case is ready first. Crystal’s whole core is one select in a loop.
for {
select {
case <-done:
return
case prop := <-e.proposals:
e.handleProposal(prop)
case a := <-e.ackCh:
e.handleAck(a)
case <-ticker.C:
e.onTick()
}
}
The same shape gives you timeouts and cancellation. Add case <-ctx.Done(): and the wait ends when the context does.
The pattern I use most, one owner
Raft’s dangerous operations read several fields and then write one, for example “if a majority has this entry and it’s from my term, move the commit index”. With a mutex per field you need to hold the right combination of locks every time. In Crystal I made one goroutine, the control loop above, the only writer of that state. Everything else sends it a message. Each event is handled from start to finish before the next one begins, so the tricky rules become plain sequential code.
The slow work happens around the edges. Each follower gets its own replication goroutine that owns all network calls to that follower, and it only reports results back to the loop. A slow follower slows down its own goroutine and nothing else.
proposals ─┐
acks ──────┼──▶ [control loop] ──▶ per-follower goroutines ──▶ network
ticks ─────┘ ▲ │
└──────── results ──────┘
It’s the CSP idea that Go is built on, applied to the one part of the program where correctness matters most.
Bounding the work
Starting one goroutine per item is fine for ten items and a problem for ten thousand HTTP calls. A worker pool caps it.
jobs := make(chan Item)
results := make(chan Result)
for range workers {
go func() {
for item := range jobs {
results <- process(item)
}
}()
}
Sending into jobs blocks while every worker is busy, so the producer slows down by itself and you never write rate-limiting code.
When you only need to wait for goroutines to finish and nothing comes back, sync.WaitGroup is simpler than a channel.
Common mistakes
Leaks
A goroutine blocked forever is never collected. The classic case is a goroutine sending its result on an unbuffered channel after the receiver already gave up.
ch := make(chan int)
go func() { ch <- slowWork() }() // blocks forever if nobody reads
Give the channel a buffer of one, or select on the send together with ctx.Done(). Crystal’s election goroutines do the second. Each vote request runs in its own goroutine, and the reply is sent with a select that also watches the node’s shutdown channel, so a reply that arrives after shutdown doesn’t strand the goroutine.
Races
Two goroutines touching the same variable without synchronization is a race, and the race detector finds it.
go test -race ./...
Run tests with -race as a habit. It slows them down a lot, and every report it gives is a real bug. Crystal has tests that hit the RPC handlers from many goroutines at once with different terms, just so the detector has something to look at.
Closing channels
Closing a closed channel panics, and so does sending on one. Close from the sending side only, once all sends are done. If several goroutines send, one coordinator closes after a WaitGroup says they’re finished.
In short
Go doesn’t make concurrency easy. It makes the hard parts visible. The rule that helped me most is to decide who owns each piece of state, and when the answer is “one goroutine”, let everyone else talk to it through channels.