Goroutines and channels
Concurrency is the strongest part of Go, and the place where most bugs hide. If you understand goroutines and the scheduler, buffered and unbuffered channels, the rules for closing channels, select, races and mutexes, WaitGroup, worker pools, errgroup and goroutine leaks, you can answer most interview questions.
Author: bezzad
Contents
The problem: a nightly job that breaks in a new way every night
Our shop has a nightly job that sends a receipt email for every order of the day. To make it faster, someone made it concurrent. Now:
- One night the email service blocked us, because we opened 5,000 connections at the same time.
- One night the program stopped with “fatal error: all goroutines are asleep - deadlock!”.
- One night the “emails sent” counter showed a wrong number.
- The memory of the service grows a little every day.
All four bugs come from simple rules of concurrency in Go. In this lesson we look at them one by one.
Goroutines
A goroutine is a function that runs at the same time as the rest of the program. You start it with the go keyword:
go sendReceipt(order)
- It is very cheap. It starts with a small stack (a few kilobytes) that grows when needed. A program can have hundreds of thousands of goroutines.
- The go statement returns at once. It returns no result and no error. If you need a result, you must send it back with a channel or a shared variable.
- When main ends, the program exits and all other goroutines are killed without warning.
- Nobody can stop a goroutine from outside. It must notice by itself that it is not needed anymore, usually with a context.
The Go scheduler
The Go scheduler runs goroutines on a small number of operating system threads. It has three parts:
- G is a goroutine.
- M is a real operating system thread.
- P is a “logical processor” with a local queue of Gs. An M needs a P to run Go code. The number of Ps equals GOMAXPROCS, and by default that is the number of CPU cores.
- When a goroutine waits for the network, it frees the thread. So thousands of concurrent requests are served by a few threads.
- The scheduler is preemptive. Since Go 1.14 even a long loop can not hold a P forever.
- In a container GOMAXPROCS should match the container’s CPU limit. Since Go 1.25 the runtime also looks at the CPU limit of the Linux cgroup. With older versions, teams used the automaxprocs library.
Channels
A channel is a typed pipe between goroutines. One goroutine sends, and another one receives:
ch := make(chan string) // unbuffered
done := make(chan struct{})
go func() {
fmt.Println("got", <-ch)
close(done)
}()
ch <- "order 42" // waits until the receiver takes it
<-done
- An unbuffered channel brings the sender and the receiver together at one moment. The sender waits until the receiver comes. It is both a message and a synchronization.
- A buffered channel (for example make with a capacity of 10) has a small queue. The sender waits only when the queue is full.
- A buffer is a flow control tool, not a speed fix. If the receiver is slow, a buffer only shows the problem later.
Rules for closing a channel
| Action | On an open channel | On a closed channel | On a nil channel |
|---|---|---|---|
| Send | sends or waits | panic | waits forever |
| Receive | receives or waits | zero value, at once | waits forever |
| Close | closes it | panic | panic |
- Only the sender closes a channel, and only when the receiver must know “nothing more is coming”. Closing is not needed to free memory.
- A range loop over a channel runs until the channel is closed. If nobody closes it, the loop waits forever.
- With the two-result form (value and ok) the receiver learns that the channel is closed.
- If you have several senders, none of them should close the channel. A separate goroutine closes it after all of them are done (with a WaitGroup).
The select statement
The select statement waits on several channel operations and runs the first one that is ready:
func priceWithTimeout(ctx context.Context) (int, error) {
ch := make(chan int, 1) // buffer 1: the sender never blocks
go func() { ch <- slowPrice() }()
select {
case p := <-ch:
return p, nil
case <-time.After(time.Second):
return 0, errors.New("price timeout")
case <-ctx.Done():
return 0, ctx.Err()
}
}
- If several cases are ready together, one is chosen at random.
- The default case runs when no case is ready. With it you can send or receive without waiting.
- The buffer of 1 in this example matters. If the timeout wins, the goroutine can still put its answer and end. Without the buffer, it waits forever and leaks.
Data races and mutexes
A data race means two goroutines access one variable at the same time and at least one of them writes. This is our third bug:
// Bad: sent++ from many goroutines
var sent int
for _, o := range orders {
go func() {
sendReceipt(o)
sent++ // read, add, write: not atomic
}()
}
- The expression sent++ is three steps: read, add and write. Two goroutines may read the same value, and one of the additions is lost.
- A data race in Go has undefined behavior. It is not only “a wrong number”. You may see broken data or a crash.
- The race detector finds this: run tests with go test -race. It only sees paths that really run, so you need concurrent tests.
Use sync.Mutex to protect shared data:
type Counter struct {
mu sync.Mutex
n map[string]int
}
func (c *Counter) Inc(sku string) {
c.mu.Lock()
defer c.mu.Unlock()
c.n[sku]++
}
- Keep the lock short. Never call the network or the database while you hold a lock.
- The sync.RWMutex type lets many readers hold the lock at the same time. It helps only when reads are much more common than writes.
- For a simple number, the sync/atomic types (like atomic.Int64) are simpler and faster.
- Do not copy a struct that has a mutex. Use pointer receivers for its methods.
WaitGroup
The sync.WaitGroup type waits until a group of goroutines is done:
var wg sync.WaitGroup
for _, o := range orders {
wg.Add(1) // before the go statement
go func() {
defer wg.Done()
sendReceipt(o)
}()
}
wg.Wait()
- Call Add before the go statement, not inside the goroutine. Otherwise Wait may run before Add and return too early.
- Call Done with defer, so it runs even after an early return.
- Since Go 1.25 the wg.Go method does Add and Done together and makes this mistake impossible.
A worker pool
Our first bug was one goroutine per order. 5,000 orders meant 5,000 connections to the email service at once. The fix: a fixed number of workers that take jobs from one channel:
func sendReceipts(orders []Order, workers int) {
jobs := make(chan Order)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for o := range jobs {
sendReceipt(o)
}
}()
}
for _, o := range orders {
jobs <- o
}
close(jobs) // workers leave their range loop
wg.Wait()
}
- The number of workers is the limit of concurrent work. Set it from the limit of the downstream service.
- Closing the jobs channel tells the workers that the work is done. Their range loops end.
- This is the fan-out pattern: one queue, many workers. Collecting results into one channel is called fan-in.
If errors matter too, the errgroup package (in golang.org/x/sync) makes this simpler:
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(8) // at most 8 goroutines at once
for _, o := range orders {
g.Go(func() error {
return sendReceipt(ctx, o)
})
}
return g.Wait() // the first error, or nil
- The SetLimit method limits the number of concurrent goroutines. The Go method waits when the limit is reached.
- With WithContext, the first error cancels the context, so the other jobs stop early.
- The Wait method returns the first error.
Deadlocks and goroutine leaks
Our second bug was a deadlock. When all goroutines wait for something that never comes, the runtime stops the program with “all goroutines are asleep”:
// Bad: deadlock, nobody receives
results := make(chan Receipt)
for _, o := range orders {
results <- makeReceipt(o) // blocks forever
}
- Sending on an unbuffered channel with no receiver waits forever.
- The runtime only detects this when all goroutines are blocked. In a real server where other goroutines are still running, you see no error at all.
That second case is a goroutine leak, and it is our fourth bug. A goroutine that waits on a channel forever is never collected. Its memory and everything it points to stay. To find it:
- Watch a goroutine count metric (the runtime.NumGoroutine function). If it keeps growing, you have a leak.
- The goroutine profile in pprof shows on which line thousands of goroutines are waiting.
- In tests, the goleak library checks that no extra goroutines are left after the test.
A simple rule: before you start a goroutine, know when and how it ends.
Common mistakes
| Mistake | Result | The right way |
|---|---|---|
| One goroutine per job, with no limit | Heavy load on services and memory | A worker pool or errgroup with SetLimit |
| A shared counter or map without a lock | A data race and wrong numbers | A mutex or an atomic type |
| Calling wg.Add inside the goroutine | Wait returns too early. | Add before the go statement |
| Closing a channel from the receiver side | The sender panics. | Only the sender closes. |
| Not closing a channel you range over | The loop waits forever. | Close it after all senders are done. |
| An unbuffered channel with a timeout | The sending goroutine leaks. | A buffer of 1, or cancel with a context |
| Calling the network while holding a lock | Everyone waits for one slow request. | Lock only around the data access |
| A big buffer “to make it faster” | The problem shows up later and bigger. | Fix the receiver, and measure. |
Summary in seven lines
- A goroutine is cheap, but nobody stops it from outside. Know when it ends.
- The scheduler runs Gs on Ps, and Ps on threads. The number of Ps is GOMAXPROCS.
- An unbuffered channel synchronizes, a buffered channel is a small queue. Only the sender closes a channel.
- The select statement waits on several channels and fits timeouts and cancellation.
- Every writable shared value needs a lock. Run tests with the race flag.
- Call Add before go, or use wg.Go in Go 1.25.
- Limit big work with a worker pool or errgroup with SetLimit, and watch the goroutine count for leaks.