Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
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.
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.
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.
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.
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.
ok == false.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.
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:
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:
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.
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.
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:
| Pattern | What happens |
|---|---|
| Send, no receiver | Send on unbuffered channel with no goroutine receiving → blocks forever → deadlock panic. |
| Receive, no sender | Receiving from an empty channel nobody will send to → blocks forever. |
| Range over unclosed channel | for v := range ch waits for more values; if the channel is never closed, it blocks at the end. |
| Circular wait | A 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.
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.
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?
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.
| Step | Operation | Buffer after | Who is blocked |
|---|---|---|---|
| 1 | send 1 | [1], len 1 < cap 2 | nobody |
| 2 | send 2 | [1, 2], len 2 | nobody |
| 3 | send 3 | [1, 2]: len 2 ≥ cap 2, so 3 waits | producer |
| 4 | consumer receives 1 | [2], then the waiting 3 enters: [2, 3] | producer wakes, nobody |
| 5 | send 4 | [2, 3] still full | producer |
| 6 | consumer receives 2 | [3, 4] | nobody; producer runs on |
| 7 | close(ch) | [3, 4], marked closed | nobody; producer exits |
| 8 | consumer receives 3, then 4 | [] | nobody |
| 9 | next receive | closed and empty: zero value, ok == false | range 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.
Cost and trade-offs: goroutines, channels and locks
| Case | Time | Space | Why |
|---|---|---|---|
| Goroutine | go f(): no system call; the Go scheduler runs it | Starts with a 2 KB stack that grows by copying | Cheap enough for one per request, connection or job. |
| OS thread | Created and switched by the kernel | A fixed stack reservation, commonly 8 MB of virtual memory on Linux | Why thread-per-task stops at a few thousand. |
| Unbuffered send | Waits for a receiver every time | No buffer | Each send is a hand-off; the sender knows it was received. |
| Buffered send, cap N | Immediate while there is room, then waits | N slots, allocated by make | Absorbs bursts up to N; does not fix a consumer that is slower on average. |
sync.Mutex | Uncontended: a few atomic operations; contended: waiting | 8 bytes | Right for guarding a counter or a map; no value hand-off. |
sync/atomic | One atomic CPU operation | One word | Counters and flags only; no compound updates. |
select over k cases | Checks the cases; picks uniformly at random among the ready ones | No extra storage | Random 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.
Where this shows up in production and interviews
- One goroutine per connection
Go’s
net/httpserver 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 canselecton it and exit. This is the standard “guaranteed exit” the pitfalls section asks for. - Finding races and leaks
go test -raceandgo run -racereport 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.
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.
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.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The System Design Fundamentals HandbookThe load-bearing ideas behind every distributed system — the CAP theorem and consistency models, concurrency and locking, partitioning and replication, and consensus and coordination — each tied to a real worked design you can study interactively.Read →
- CAP Theorem & Consistency ModelsWhat a distributed system can promise when the network splits — CP vs AP, why "CA" is a myth, PACELC, and the full spectrum from linearizable to eventual consistency. Part of System Design Fundamentals.Read →
- Partitioning, Sharding & ReplicationHow one dataset becomes many — range vs hash partitioning, consistent hashing and virtual nodes, hot partitions, replication topologies, replication lag, and quorums. Part of System Design Fundamentals.Read →
- Consensus, Transactions & CoordinationHow nodes that can crash still agree on one truth — majority quorums, Raft and Paxos, leader election, two-phase commit vs the saga pattern, and idempotency for exactly-once effects. Part of System Design Fundamentals.Read →
- The Kubernetes HandbookThe one idea under all the YAML — declare desired state, and a control loop makes reality match. Covers the orchestration problem, pods, deployments and replicasets, services and networking, the reconciliation loop and self-healing, the scheduler, config/secrets and health probes, autoscaling, and when you actually need Kubernetes.Read →
- The Observability HandbookSeeing inside production — monitoring vs observability, the three pillars (metrics, logs, traces) and what each answers, structured logging, metric types and the cardinality trap, distributed tracing, the golden signals and SLIs/SLOs/error budgets, alerting on symptoms not causes, and correlating all three during an incident.Read →