Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Go
Handbook~16 min readConcurrencyworked math + runnable code
The Go Handbook

Share by
communicating.

Concurrency is where most languages get scary: threads, locks, race conditions, bugs that vanish when you look at them. Go's answer is a different mental model — don't communicate by sharing memory; share memory by communicating. You spin up thousands of near-free goroutines and let them pass data through channels, typed pipes that handle the synchronization for you. The whole thing hinges on one small idea: when does a send or receive block? Get that right and concurrency is safe by construction; get it wrong and you deadlock. This handbook is that rule, made runnable.

01

A different model

The traditional way to do concurrency is shared memory plus locks: many threads read and write the same variables, and you guard them with mutexes so they don't clobber each other. It works, but it's notoriously error-prone — forget a lock and you get a race; take locks in the wrong order and you deadlock; and the bugs are non-deterministic, appearing only under load. Go takes a deliberately different stance, summarized in its famous motto: "Don't communicate by sharing memory; share memory by communicating."

Instead of many threads poking at shared state behind locks, Go has independent goroutines that pass data to each other through channels. Ownership of a value moves along the channel from sender to receiver, so at any moment one goroutine is working with it — no simultaneous access to guard. The synchronization is baked into the send and receive operations themselves, so you often need no explicit locks at all. This is Go's whole concurrency philosophy (borrowed from a model called CSP): make the communication the primitive, and safety follows from it. Everything else — how cheap goroutines are, how channels block — serves that idea.

The one-sentence version

Go runs thousands of cheap goroutines that pass data through channels instead of sharing locked memory — and the one rule that makes it safe is when a send or receive blocks: unbuffered blocks until a partner is ready, buffered blocks only when full/empty.

02

Goroutines are cheap

A goroutine is a lightweight thread managed by the Go runtime, not the operating system. You start one by writing go f() — that's the entire syntax — and it runs concurrently with everything else. The magic is how cheap they are: a goroutine begins with a tiny stack of a few kilobytes that grows on demand, and the Go scheduler multiplexes many thousands of goroutines onto a small pool of real OS threads.

That cheapness changes how you design. Spawning an OS thread per task caps you at a few thousand before memory and context-switching overhead crush the machine; goroutines let you run hundreds of thousands comfortably. So in Go you don't ration concurrency — you use it liberally: a goroutine per incoming request, per connection, per background job, per item in a fan-out. The scheduler handles parking a goroutine that's blocked (say, waiting on a channel or I/O) and running another on that thread, so blocked goroutines cost almost nothing. The mental shift is that concurrency is abundant, which is exactly what makes the channel-based style practical: you can afford to give every unit of work its own goroutine and let channels coordinate them.

03

Channels & blocking

A channel is a typed pipe: one goroutine sends a value in, another receives it out. The crucial property — the thing you must internalize — is when an operation blocks, and that depends on the channel's buffer capacity.

When does a channel operation block?
Unbufferedcap 0: a send blocks until a receiver is ready — send & receive meet (a rendezvous).
Bufferedcap N: a send succeeds without blocking until the buffer is full, then it blocks.
ReceiveBlocks when the channel is empty (waits for a value); on a closed channel it still delivers any buffered values first; once closed and empty it returns the zero value with ok == false.
Why it mattersUnbuffered = tight synchronization; buffered = let a producer run ahead by up to N.

An unbuffered channel (capacity 0) has no storage, so a send can't complete until someone is there to receive — the two operations happen together as a rendezvous, which hands you synchronization for free (the sender knows the receiver got it). A buffered channel (capacity N) can hold up to N values, so sends succeed immediately while there's room and only block when the buffer fills; receives block only when it's empty. The choice is a design decision: use unbuffered when you want sender and receiver to march in lockstep, and buffered when you want to decouple them — let a fast producer get ahead of a slower consumer by a bounded amount. Everything about coordinating goroutines reduces to picking capacities and understanding these blocking conditions.

04

The blocking rules

A send blocks exactly when the buffer is full (which, for an unbuffered channel of capacity 0, is always — until a receiver takes the value); a receive blocks when the buffer is empty:

send blocks  ⟺  len(buf) ≥ capacity     receive blocks  ⟺  len(buf) = 0

Unbuffered (cap 0): len ≥ 0 is always true, so a send always waits for a receiver. Buffered (cap 2): first two sends don't block; the third does.

A deadlock is when a blocked operation has no counterpart that can ever unblock it — a send with no receiver, or a receive with no sender:

deadlock  ⟺  (send blocks ∧ no receivers)  ∨  (receive blocks ∧ no senders)

The classic beginner deadlock: send on an unbuffered channel with no goroutine receiving → "all goroutines are asleep - deadlock!". The runnable version below models channels, blocking, and deadlock detection.

RUN IT YOURSELF

Channel blocking, modeled

Go's concurrency safety comes down to one rule: when does a channel operation block? An unbuffered channel (capacity 0) blocks every send until a receiver is ready — a rendezvous that synchronizes the two goroutines. A buffered channel (capacity N) lets sends succeed until the buffer is full, then blocks; receives block when it's empty. And a deadlock is a blocked operation with no partner to unblock it — a send with no receiver is the classic one. Change the capacity, the number of sends, or the waiting senders/receivers and watch which operations block and when it deadlocks.

CPython · WebAssembly
05

Deadlocks

A deadlock is when goroutines are all blocked waiting on each other and none can move — and Go is unusually helpful here: its runtime detects the case where every goroutine is asleep and panics with fatal error: all goroutines are asleep - deadlock! rather than hanging silently. The most common cause is the beginner mistake of sending on an unbuffered channel with nothing set up to receive:

PatternWhat happens
Send, no receiverSend on unbuffered channel with no goroutine receiving → blocks forever → deadlock panic.
Receive, no senderReceiving from an empty channel nobody will send to → blocks forever.
Range over unclosed channelfor v := range ch waits for more values; if the channel is never closed, it blocks at the end.
Circular waitA waits on B while B waits on A → neither proceeds.

The unifying cure is understanding the blocking rules well enough to guarantee every blocking operation has a partner. Send on an unbuffered channel? Make sure a receiver is running (usually in another goroutine). Range over a channel? Make sure someone close()s it when done, so the loop can end. Reading from N workers? Know how many values will arrive. Deadlocks aren't mysterious in Go — they're the direct, mechanical consequence of a blocked operation with no counterpart, which is why internalizing "when does this block?" is the entire skill. The runtime's deadlock detector turns what would be a silent hang in other languages into a loud, immediate error, which is a genuine gift once you learn to read it.

06

Pitfalls

The first is the goroutine leak. Goroutines are so cheap that it's easy to start one that blocks forever — waiting on a channel that never receives another value, say — and never notice. It doesn't crash; it just sits there holding memory and whatever it referenced, and in a long-running server these accumulate until you're out of memory. Every goroutine you start needs a guaranteed way to finish (a closed channel, a context cancellation, a done signal). "Cheap to start" does not mean "free to abandon."

Two more. Assuming buffered means non-blocking: a buffered channel only defers blocking until the buffer fills — size it wrong and you still block, or worse, you paper over a producer/consumer imbalance that then bites under load. And reaching back for shared memory and mutexes out of habit: Go has sync.Mutex and sometimes it's the right tool (protecting a simple counter, say), but defaulting to shared-state-plus-locks throws away the whole point of the channel model and reintroduces exactly the race conditions Go was designed to avoid. Prefer communicating over sharing until you have a concrete reason not to. The payoff for learning the model is large: concurrency, the thing that terrifies people in other languages, becomes a set of small, composable, mechanically-reasoned pieces. The whole handbook is one question you can now always answer — when does this send or receive block? — and from that, safe concurrency follows.

Worth knowing

Give every goroutine a guaranteed exit (closed channel / context cancel) or it leaks; remember buffered channels only defer blocking until full; and prefer channels over shared-memory+mutex unless you have a specific reason. Safe concurrency reduces to one question: when does this send/receive block?

By the numbers

Worked example: a cap-2 channel, step by step

A producer sends 1, 2, 3, 4 into ch := make(chan int, 2), then calls close(ch). A slower consumer runs for v := range ch. Trace the buffer and who is blocked.

StepOperationBuffer afterWho is blocked
1send 1[1], len 1 < cap 2nobody
2send 2[1, 2], len 2nobody
3send 3[1, 2]: len 2 ≥ cap 2, so 3 waitsproducer
4consumer receives 1[2], then the waiting 3 enters: [2, 3]producer wakes, nobody
5send 4[2, 3] still fullproducer
6consumer receives 2[3, 4]nobody; producer runs on
7close(ch)[3, 4], marked closednobody; producer exits
8consumer receives 3, then 4[]nobody
9next receiveclosed and empty: zero value, ok == falserange loop ends

Two things this trace makes concrete. First, closing does not throw away buffered values: steps 8 and 9 show a receive on a closed channel returns what is left in the buffer first, and only then the zero value with ok == false. Second, the buffer only let the producer run two values ahead. From step 3 on, it moves at the consumer’s pace, which is the page’s “buffered only defers blocking” in action. If the consumer had stopped at step 4 and nobody else could receive, the producer would block at step 5 forever: a leak in a server, or the deadlock panic if it were the last goroutine running.

Trade-offs

Cost and trade-offs: goroutines, channels and locks

CaseTimeSpaceWhy
Goroutinego f(): no system call; the Go scheduler runs itStarts with a 2 KB stack that grows by copyingCheap enough for one per request, connection or job.
OS threadCreated and switched by the kernelA fixed stack reservation, commonly 8 MB of virtual memory on LinuxWhy thread-per-task stops at a few thousand.
Unbuffered sendWaits for a receiver every timeNo bufferEach send is a hand-off; the sender knows it was received.
Buffered send, cap NImmediate while there is room, then waitsN slots, allocated by makeAbsorbs bursts up to N; does not fix a consumer that is slower on average.
sync.MutexUncontended: a few atomic operations; contended: waiting8 bytesRight for guarding a counter or a map; no value hand-off.
sync/atomicOne atomic CPU operationOne wordCounters and flags only; no compound updates.
select over k casesChecks the cases; picks uniformly at random among the ready onesNo extra storageRandom choice prevents starvation; a default case makes it non-blocking.

Channels cost more per operation than a mutex because they move a value and may park and wake goroutines. That cost buys ownership transfer and a natural place to block. Use a channel when a value or a signal changes hands, and a mutex when several goroutines only need short, safe access to one shared value.

In the wild

Where this shows up in production and interviews

  • One goroutine per connection

    Go’s net/http server starts a new goroutine for each incoming connection, and your handler runs inside it. This is the page’s “concurrency is abundant” used as the default, and it is why a handler that blocks forever leaks one goroutine per request.

  • Cancellation with context

    ctx.Done() returns a channel that is closed when the request is cancelled or times out. Closing a channel wakes every receiver at once, so every goroutine working on the request can select on it and exit. This is the standard “guaranteed exit” the pitfalls section asks for.

  • Finding races and leaks

    go test -race and go run -race report data races that actually happen during the run. runtime.NumGoroutine() and the pprof goroutine profile (/debug/pprof/goroutine) show goroutine counts and where each one is blocked. A count that climbs with traffic and never falls is a leak.

  • The interview version

    Common asks: a worker pool reading jobs from one channel, a fan-in that merges several channels, or a limit on concurrent calls. The last one is a buffered channel used as a semaphore, sem := make(chan struct{}, 10): send to acquire, receive to release. Then say who closes each channel and how every goroutine exits.

Self-check

Check yourself

In main, with no other goroutines: ch := make(chan int, 3), then five sends. What happens, and on which send?

Sends 1 to 3 fill the buffer. Send 4 blocks, since len 3 ≥ cap 3. Main is the only goroutine and it is asleep, so the runtime reports fatal error: all goroutines are asleep - deadlock!. Send 5 never runs.

The same blocked send happens inside an HTTP handler on a running server. Does the runtime panic?

No. The detector fires only when every goroutine is asleep, and the server’s listener goroutine is still waiting for connections. The handler goroutine just sits there forever: a silent leak, one per request. This is why leaks are found with goroutine profiles, not panics.

A channel holds 7 and 8 and is then closed. A goroutine runs v, ok := <-ch three times. What does it get?

(7, true), (8, true), (0, false). Buffered values are delivered first even after close; only a closed and empty channel returns the zero value with ok == false. A send on that closed channel, by contrast, panics.

You must download 1,000 files with at most 10 in flight. Which tool?

Either 10 worker goroutines reading URLs from a jobs channel, or one goroutine per file gated by a make(chan struct{}, 10) semaphore. Both cap concurrency at 10. A 1,000-slot buffered channel does not: buffering limits how far a producer runs ahead, not how many downloads run at once.

Frequently asked

Quick answers

What is a goroutine?

A lightweight thread managed by the Go runtime — started with "go f()", cheap enough to run hundreds of thousands, multiplexed onto a few OS threads.

What is a channel?

A typed pipe goroutines use to pass values and synchronize — sharing memory by communicating instead of locking shared state.

Buffered vs unbuffered?

Unbuffered (cap 0) blocks a send until a receiver is ready (rendezvous); buffered (cap N) blocks a send only when the buffer is full.

What causes a deadlock?

A blocked operation with no partner — e.g. sending on an unbuffered channel with no receiver. Go's runtime detects and panics instead of hanging.

Finished this one? 0 / 209 Handbooks done
NextThe Rust Handbook Next on the “The languages you ship in” ladder · rung 7 of 7

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks