# Go Concurrency: 30-Day Roadmap (Go 1.27)

Nov 13, 2026 · @Shubhs

Sixty-two LeetCode-style problems, two per day for 30 days, take you from your first goroutine to lock-free queues, and every one is written against Go 1.27 (released August 2026), not the Go you learned from older blogs.

## How to use this roadmap

**Setup.** Use Go 1.27 and set `go 1.27` in `go.mod`. Several behaviours below (per-iteration loop variables, synchronous timer channels, goroutine labels in tracebacks) depend on the `go` line, so the version is part of the problem.

**Daily rhythm (about 2 hours).** 15 min reading the day's theme, 75 min solving both problems, 20 min review.

**Rules for every problem.**

1. Write the solution and a test. Run `go test -race -count=200 ./...` before you call it done.
2. For any problem that spawns goroutines, finish with a leak check: run the test with the `goroutineleak` profile (GA in Go 1.27) or assert `runtime.NumGoroutine()` returns to baseline.
3. Answer the **Follow-up** in writing, in two sentences. The follow-ups are where the edge cases live.
4. Do not look at standard-library solutions (`errgroup`, `singleflight`, `x/time/rate`) until you have your own version passing.

**Problem format.** Each problem has a difficulty tag, a task or signature, an example, constraints, and a follow-up. Problems marked *Predict* or *Debug* give you code and ask what it does or why it breaks, as in interview rounds.

| Tag | Meaning |
| --- | --- |
| Easy | One primitive, one idea. Under 20 minutes. |
| Medium | Two primitives interacting, or one subtle edge case. 30 to 45 minutes. |
| Hard | Design plus correctness argument plus tests. 60 minutes or more. |

**Phases.**

| Days | Phase | You can explain afterwards |
| --- | --- | --- |
| 1 to 7 | Foundations | How goroutines, channels and `select` behave, including nil and closed channels |
| 8 to 14 | Synchronisation | When to use a mutex, atomic, `Cond`, `context`, `errgroup` or timer, and why |
| 15 to 21 | Memory and internals | The memory model, the GC, escape analysis, the G-M-P scheduler, channel and mutex internals |
| 22 to 27 | Production | Leaks, testing without sleeping, profiling, shutdown, panics |
| 28 to 30 | Capstone | Design and defend a full concurrent system |

## What changed in Go 1.22 to 1.27

Many concurrency habits that were correct in 2022 are now unnecessary or wrong, and the questions below are framed around the new behaviour. Rows marked *older* are stable features I did not re-check against release notes today; every other row was checked against the official Go 1.23 to 1.27 notes.

| Release | Change | Status in Go 1.27 | Old advice it makes stale |
| --- | --- | --- | --- |
| 1.22 (older) | Loop variables are per-iteration; `range` over integers | Default when `go.mod` says 1.22 or later | The `i := i` shadow copy before `go func()` |
| 1.23 | Timer and ticker channels are synchronous (unbuffered), and unreferenced unstopped timers are garbage collected | The `asynctimerchan` GODEBUG was removed permanently in 1.27 | Draining `t.C` before `Reset`; polling `len(t.C)`; fear that `time.After` always leaks |
| 1.23 (older) | `iter` package and range-over-func; `iter.Pull` | Stable | Hand-built generator goroutines that leak when the consumer stops |
| 1.24 | `sync.Map` rebuilt on a concurrent hash-trie; built-in `map` moved to Swiss tables; new runtime-internal mutex | Default | The rule that `sync.Map` is only for two narrow cases, based on old benchmarks |
| 1.24 | `runtime.AddCleanup` and the `weak` package | Stable | `runtime.SetFinalizer` for resource cleanup and weak caches |
| 1.24 | `go vet` copylock reports a mutex declared in a three-clause `for` loop | Default | Assuming loop-scoped mutexes are fine |
| 1.25 | `testing/synctest`: `synctest.Test` runs a test in a bubble with a fake clock, and `synctest.Wait` waits until every goroutine in the bubble is blocked | GA; 1.27 adds `synctest.Sleep` and `httptest.NewTestServer` for in-memory networking | `time.Sleep` in concurrent tests; flaky timing assertions |
| 1.25 | `sync.WaitGroup.Go`; vet `waitgroup` analyzer flags misplaced `Add` | Default; the analyzer is renamed `waitgroupgo` in 1.27 `go fix` | The manual `Add(1)` plus `defer Done()` boilerplate |
| 1.25 | Container-aware `GOMAXPROCS`: respects the cgroup CPU limit on Linux and re-checks it periodically | Default unless you set `GOMAXPROCS` yourself | Importing `automaxprocs` just to match Kubernetes CPU limits |
| 1.25 | Green Tea garbage collector available as an experiment | Became the default in 1.26 | Tuning around the old collector's cost on small objects |
| 1.26 | Green Tea GC on by default (10 to 40% less GC overhead in GC-heavy programs, per the release notes) | Default | GC cost models from before 2026 |
| 1.26 | `goroutineleak` profile, experimental | GA in 1.27 via `runtime/pprof` and `/debug/pprof/goroutineleak` | Relying only on test-time leak checkers |
| 1.26 | New `runtime/metrics` entries under `/sched/goroutines`, plus `/sched/threads:threads` and `/sched/goroutines-created:goroutines` | Available | Estimating scheduler state from `runtime.NumGoroutine` alone |
| 1.26 | `signal.NotifyContext` cancels with a cause naming the signal; `errors.AsType`; `B.Loop` no longer blocks inlining | Available | Guessing which signal ended a context; `b.N` loops |
| 1.27 | Tracebacks include `runtime/pprof` goroutine labels (modules on go 1.27+) | Default; opt out with `tracebacklabels=0` | Reading anonymous identical goroutines in crash dumps |
| 1.27 | Size-specialised small allocations (under 80 bytes) up to 30% cheaper | Default | Micro-optimising small allocations by hand |
| 1.27 | HTTP/1 `Response.Body` drains unread bytes on `Close`, up to a limit | Default | Assuming skipping the body read always costs a connection |
| 1.27 | Goroutines created inside `runtime/secret` mode run in secret mode | Experimental package | Assuming secrecy stops at the creating goroutine |

**One caveat.** Flight recording (`runtime/trace.FlightRecorder`) arrived in 1.25 according to a secondary write-up; I did not open the official page for it, so confirm its API in the package docs before Day 25.

**What did not change.** The memory model, channel semantics, `select` randomness, `sync.Mutex` being non-reentrant, and the rule that a send on a closed channel panics are all unchanged. If a problem later asks about them, the answer is the same as in 2020.

## Phase 1: Foundations (Days 1 to 7)

By Day 7 you should be able to predict, without running it, what any small program with goroutines, channels and `select` prints or hangs on.

### Day 1: Goroutines and loop variables

A goroutine is a scheduled function call, not a thread, and when `main` returns the program ends whatever else is running.

#### 1.1 Parallel Squares (Easy)

**Task.** `func Squares(nums []int) []int` returns the square of each element, in the same order, computing each one in its own goroutine. Use `sync.WaitGroup.Go` (Go 1.25).

**Example.** `nums = [1,2,3]` returns `[1,4,9]`.

**Constraints.** `0 <= len(nums) <= 100000`, `|nums[i]| <= 10000`.

**Follow-up.** Each goroutine writes its own index of one shared slice with no lock. Why is that race-free, and why would `append` from the same goroutines not be? State exactly which operation makes the final read in the caller safe.

#### 1.2 Predict the Loop (Easy, Predict)

```go
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Println(i)
    }()
}
wg.Wait()
```

**Task.** List every possible output when `go.mod` says `go 1.21`, and every possible output when it says `go 1.27`. Then rewrite the loop as `for i := range 3` with `wg.Go`.

**Constraints.** No `i := i` copy allowed in your answer.

**Follow-up.** In Go 1.27, `go test` runs the `stdversion` vet check by default. What does it report if `go.mod` says `go 1.21` and your file calls `wg.Go`?

### Day 2: Channels

Sends and receives synchronise; closing is a broadcast that only the sender side may do.

#### 2.1 Ping-Pong Relay (Easy)

**Task.** `func PingPong(rounds int) []string` starts two goroutines that alternate using exactly two unbuffered channels and no mutex. Return the log of events.

**Example.** `rounds = 2` returns `[ping pong ping pong]`.

**Constraints.** `1 <= rounds <= 10000`. Both goroutines must have exited when the function returns.

**Follow-up.** Which side closes, and what happens to the other goroutine if you forget? How would you see it in a goroutine dump?

#### 2.2 Channel State Table (Medium, Predict)

**Task.** `func Probe(state, op string) string` where `state` is one of `nil`, `open-empty`, `open-full`, `closed-empty`, `closed-with-data` and `op` is one of `send`, `recv`, `close`, `range`. Return `ok`, `blocks`, or `panic: <message>`. Detect blocking with a 50 ms timeout.

**Example.** `Probe(closed-with-data, recv)` returns `ok` (the buffered value, then zero values with `ok == false`).

**Constraints.** Recover panics inside the probe. Record all 20 results in a table before you run the code, then compare.

**Follow-up.** A probe that blocks leaks its goroutine. How can the test unblock it, and which of the 20 cases can never be unblocked from outside?

### Day 3: `select`

`select` picks uniformly at random among ready cases, and a nil channel is never ready.

#### 3.1 Merge Two Channels (Medium)

**Task.** `func Merge(a, b <-chan int) <-chan int` forwards every value from both inputs to the output, using one goroutine and one `select`. The output closes after both inputs have closed.

**Example.** `a` sends `1,2`, `b` sends `3`; the output yields `1,2,3` in some order, then closes.

**Constraints.** Values are never dropped. No busy loop: CPU use must be near zero while both inputs are idle.

**Follow-up.** What goes wrong, and how fast, if you do not set a closed input to `nil`?

#### 3.2 Priority Select (Medium)

**Task.** `func Recv(high, low <-chan int, quit <-chan struct{}) (v int, ok bool)` returns a value from `high` whenever one is ready, otherwise from `low`, and returns `ok == false` if `quit` fires first.

**Example.** Both `high` and `low` hold a value: always return the `high` one.

**Constraints.** A plain three-case `select` is not allowed, because it chooses randomly.

**Follow-up.** A busy `high` starves `low`. Add a bound so that after `N` consecutive `high` receives, one `low` value is served if available.

### Day 4: `WaitGroup`

`Add` must happen before the goroutine can possibly call `Done`, and Go 1.25's `wg.Go` makes that rule impossible to break.

#### 4.1 Parallel Sum (Easy)

**Task.** `func ParallelSum(nums []int, k int) int` splits `nums` into `k` chunks, sums each in a goroutine with `wg.Go`, then adds the partial sums.

**Example.** `nums = [1..10]`, `k = 3` returns `55`.

**Constraints.** `1 <= k <= 64`, `len(nums) <= 10000000`.

**Follow-up.** Compare against one shared `atomic.Int64` that every goroutine adds to element by element. Benchmark both and explain the gap. What `k` is best on your machine, and how does it relate to `GOMAXPROCS`?

#### 4.2 Debug the Add (Medium, Debug)

```go
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
    go func() {
        wg.Add(1)
        defer wg.Done()
        work(i)
    }()
}
wg.Wait()
```

**Task.** Explain why `Wait` can return before any `work` runs. Name the vet analyzer that reports this, fix it by hand, then fix it with `wg.Go`.

**Constraints.** Your explanation must reference the happens-before rule between `Add` and `Wait`, not just 'a race'.

**Follow-up.** What panics if the counter goes negative? Can a `WaitGroup` be reused for a second batch while a goroutine from the first batch is still inside `Wait`? Run `go fix` from Go 1.27 on your buggy file and note what the `waitgroupgo` modernizer changes.

### Day 5: Pipelines

Every stage owns the channel it writes to and closes it when it is done or cancelled.

#### 5.1 Cancelable Pipeline (Medium)

**Task.** `func Pipeline(ctx context.Context, nums []int) (int, error)` runs three goroutines: generate, square, sum, connected by unbuffered channels. Return the sum of squares, or `ctx.Err()` if the context ends first.

**Example.** `nums = [1,2,3]` returns `14, nil`.

**Constraints.** `len(nums) <= 1000000`. After cancellation, zero goroutines remain, verified with the `goroutineleak` profile.

**Follow-up.** If the consumer stops reading early, which stage blocks, and where exactly in the send must you add `ctx.Done()`?

#### 5.2 Ordered Fan-Out (Medium)

**Task.** `func MapOrdered[T, R any](in []T, workers int, f func(T) R) []R` applies `f` with `workers` goroutines and returns results in input order.

**Example.** `in = [3,1,2]`, `f = double` returns `[6,2,4]` even if `f(3)` takes the longest.

**Constraints.** `1 <= workers <= 1000`, `f` may take 1 ms to 1 s.

**Follow-up.** Now change the signature to stream `<-chan T` in and `<-chan R` out while still preserving order. What bounds the reorder buffer, and what happens to memory if the first item is very slow?

### Day 6: Worker pools and bounded concurrency

Unbounded goroutines are cheap but unbounded downstream calls are not.

#### 6.1 Bounded Web Crawler (Medium)

**Task.** `func Crawl(start string, fetch func(string) []string, limit int) []string` returns every URL reachable from `start` exactly once, with at most `limit` fetches in flight.

**Example.** Graph `a -> b,c`; `b -> c,d`; `c -> a`. `Crawl(a, ..., 2)` returns `{a,b,c,d}` in any order.

**Constraints.** Up to 10000 nodes, cycles allowed, `fetch` takes 1 to 100 ms.

**Follow-up.** The visited check and insert must be one critical section; show the two-goroutine interleaving that duplicates a fetch otherwise. How does your code know the crawl is finished (termination detection)?

#### 6.2 Weighted Semaphore (Medium)

**Task.** Implement `NewSem(n int64)`, `Acquire(ctx context.Context, w int64) error`, `Release(w int64)` using a mutex and channels. Waiters are served first-in first-out.

**Example.** `n = 10`; goroutine A holds 8, B waits for 5, C waits for 1. When A releases 8, B is served before C.

**Constraints.** `w <= n`. Releasing more than is held panics. A cancelled waiter must leave the queue without losing tokens.

**Follow-up.** Why can a channel of capacity `n` not implement `Acquire(w)` by receiving `w` tokens one at a time? Construct the deadlock with two goroutines.

### Day 7: LeetCode concurrency classics in Go

Three official LeetCode concurrency problems, solved with channels rather than the semaphores the LeetCode solutions use.

#### 7.1 Print in Order, LC 1114 (Easy)

**Task.** A struct has methods `First`, `Second`, `Third`. Three goroutines call them in arbitrary order. The output must always be `firstsecondthird`.

**Example.** Call order `3,1,2` prints `firstsecondthird`.

**Constraints.** No `time.Sleep`. Each method is called exactly once.

**Follow-up.** Why is closing a channel a better signal here than sending a value? What breaks if a method were called twice?

#### 7.2 Print Zero Even Odd, LC 1116 (Medium)

**Task.** Three goroutines call `Zero`, `Even`, `Odd`. For input `n`, print `0` then the next number, alternating, until `n` numbers are printed.

**Example.** `n = 5` prints `0102030405`.

**Constraints.** `1 <= n <= 1000`. Exactly three goroutines; all exit when done.

**Follow-up.** Show the minimum number of channels that works, and the point at which an off-by-one leaves one goroutine blocked forever.

#### 7.3 The Dining Philosophers, LC 1226 (Medium)

**Task.** Five philosophers share five forks. Each must pick up both neighbouring forks, eat, and put them down. No deadlock for any scheduling.

**Example.** Each philosopher eats 3 times; the program terminates.

**Constraints.** No philosopher may starve under a fair scheduler. You may not use a global lock held while eating.

**Follow-up.** Prove deadlock freedom for your solution (lock ordering, or a semaphore of size 4). Then describe a livelock that a naive 'put the fork back and retry' fix can cause.

## Phase 2: Synchronisation (Days 8 to 14)

By Day 14 you should be able to choose between a channel, mutex, atomic, `Cond`, `context` and timer for a given problem, and defend the choice with a failure scenario for the alternatives.

### Day 8: Mutexes

`sync.Mutex` is not reentrant, must not be copied after first use, and protects data, not code.

#### 8.1 Bank Transfer (Medium)

**Task.** `func (b *Bank) Transfer(from, to int, amt int64) error` moves money between accounts, each guarded by its own mutex. Return an error on insufficient funds.

**Example.** Two goroutines run `Transfer(1,2,10)` and `Transfer(2,1,10)` 100000 times each. The program finishes and the total balance is unchanged.

**Constraints.** Up to 10000 accounts, 1000 goroutines, no global lock.

**Follow-up.** Show the interleaving that deadlocks a naive version, then fix it with lock ordering by account id. What does `Transfer(3,3,5)` do to a non-reentrant mutex, and how do you handle it?

#### 8.2 Copy Lock (Medium, Debug)

```go
type Counter struct {
    mu sync.Mutex
    n  int
}

func (c Counter) Inc() {
    c.mu.Lock()
    c.n++
    c.mu.Unlock()
}
```

**Task.** One thousand goroutines call `Inc` on one shared `Counter`. Explain why the final count is wrong and why the lock does nothing. Name the vet check that finds it.

**Example.** Expected `n == 1000`; observed `n == 0`.

**Constraints.** Explain what happens if the struct is copied while the mutex is held.

**Follow-up.** Since Go 1.24, `copylock` also reports a `sync.Mutex` declared in the init clause of a three-clause `for` loop. Go 1.22 made that variable per-iteration. Explain how those two facts combine into a real bug.

### Day 9: Read-mostly data and `sync.Map`

`RWMutex` is not automatically faster than `Mutex`, and `sync.Map` was rebuilt in Go 1.24, so old benchmark folklore is out of date.

#### 9.1 Concurrent LRU Cache (Hard)

**Task.** `NewLRU[K comparable, V any](capacity int)` with `Get(k) (V, bool)` and `Put(k, v)`, safe for concurrent use, O(1) per operation.

**Example.** Capacity 2: `Put(1)`, `Put(2)`, `Get(1)`, `Put(3)` evicts key 2.

**Constraints.** `1 <= capacity <= 1000000`. 99% of operations are `Get`.

**Follow-up.** `Get` mutates recency order, so can it use `RLock`? Benchmark a single `Mutex`, an `RWMutex`, and a sharded version at 1, 8 and 64 goroutines. Then benchmark a plain `sync.Map` with no eviction. Which of your old assumptions about `sync.Map` survive the Go 1.24 rewrite?

#### 9.2 Cache Stampede (Medium)

**Task.** `func (m *Memo[K, V]) Get(k K, load func() (V, error)) (V, error)` runs `load` at most once at a time per key. Concurrent callers for the same key wait and share the result.

**Example.** 100 goroutines call `Get(a, slowLoad)`; `slowLoad` runs once.

**Constraints.** Errors must not be cached forever: the next call after a failure retries.

**Follow-up.** Build it first with a per-key `sync.OnceValues`, then without. What happens to every waiter if `load` panics? How does your map avoid growing forever?

### Day 10: Atomics

An atomic makes one memory word safe; it does not make two words consistent with each other.

#### 10.1 Lock-Free Stats (Medium)

**Task.** `type Stats` with `Add(v int64)`, `Max() int64`, `Count() int64`, using typed atomics (`atomic.Int64`) and no mutex. `Max` must be correct under concurrent `Add`.

**Example.** 1000 goroutines each add one value between 1 and 1000000; `Max()` returns the true maximum.

**Constraints.** Implement max with a compare-and-swap loop.

**Follow-up.** A `Snapshot()` reading count and sum with two loads can return a torn pair. Fix it with an `atomic.Pointer` to an immutable struct. Then run `go fix` (Go 1.27 adds the `atomictypes` modernizer) on a version that uses `atomic.AddInt64(&x, 1)` and describe the rewrite.

#### 10.2 Hot-Reload Config (Medium)

**Task.** `type Store` with `Load() *Config` and `Update(func(Config) Config)` using `atomic.Pointer[Config]`. Readers never block.

**Example.** 100 goroutines each call `Update` to increment a counter field once; afterwards the field equals 100.

**Constraints.** No lost updates, no mutex. `Config` is a struct of 10 fields.

**Follow-up.** Why is mutating the struct returned by `Load()` a data race even though the pointer swap is atomic? Add a flag word using `atomic.Uint32` and its `And` and `Or` methods (Go 1.23). Where could the ABA problem appear in a lock-free stack but not here?

### Day 11: `sync.Cond`

A `Cond` wakes waiters but carries no data and cannot be combined with `select`; the condition itself lives in your own state under the lock.

#### 11.1 Bounded Blocking Queue, LC 1188 (Medium)

**Task.** `NewBQ(capacity int)` with `Enqueue(x int)` that blocks when full, `Dequeue() int` that blocks when empty, and `Size() int`, using `sync.Cond`.

**Example.** Capacity 2: three `Enqueue` calls, the third blocks until a `Dequeue`.

**Constraints.** `1 <= capacity <= 1000`, up to 100 producer and consumer goroutines.

**Follow-up.** Why must the wait be in a `for` loop, not an `if`? When is `Broadcast` required instead of `Signal`? Add cancellation: why is that awkward with `Cond` and easy with channels?

#### 11.2 Cyclic Barrier (Medium)

**Task.** `NewBarrier(n int)` and `Wait()`. Each call blocks until `n` goroutines have called it, then all are released. The barrier is reusable for the next round.

**Example.** `n = 3`, 5 rounds: no goroutine starts round `r+1` before all three finish round `r`.

**Constraints.** Fast goroutines must not lap slow ones.

**Follow-up.** Show the interleaving where a version without a generation counter lets one goroutine pass the barrier twice. How would you add timeout support?

### Day 12: `context`

A context carries cancellation, a deadline and a cause down a call tree; it never carries optional parameters.

#### 12.1 Retry With Backoff (Medium)

**Task.** `func Retry(ctx context.Context, attempts int, base time.Duration, f func(context.Context) error) error` retries `f` with exponential backoff and jitter. Return nil on success, or the last error joined with the context error on cancellation.

**Example.** `f` fails twice then succeeds: three calls, two waits.

**Constraints.** `1 <= attempts <= 20`. Cancellation during a wait returns within 1 ms. No sleep after the final attempt. Use a timer, not `time.Sleep`.

**Follow-up.** Using Go 1.23 timer semantics, is it safe to `Reset` a timer without draining it first? Return `context.Cause(ctx)` rather than `ctx.Err()` and explain when they differ.

#### 12.2 Cancel Cause (Medium, Predict)

```go
parent, cancel := context.WithCancelCause(context.Background())
child, stop := context.WithTimeoutCause(parent, time.Hour, errors.New("slow"))
defer stop()
cancel(errors.New("shutdown"))
fmt.Println(child.Err(), context.Cause(child))
detached := context.WithoutCancel(child)
fmt.Println(detached.Err())
```

**Task.** Predict both lines. Then register `context.AfterFunc(child, f)` and state whether `f` runs, in which goroutine, and what its stop function returns after `f` has started.

**Constraints.** Answer before running.

**Follow-up.** Since Go 1.26, `signal.NotifyContext` cancels with a cause naming the signal. Write the shutdown log line that uses it to say which signal ended the process.

### Day 13: `errgroup`

The first error wins and cancels everyone else, but only goroutines that watch the context actually stop.

#### 13.1 Mini errgroup (Medium)

**Task.** Implement `Group` with `WithContext(ctx)`, `Go(f func() error)`, `SetLimit(n)`, `TryGo`, and `Wait() error` that returns the first non-nil error.

**Example.** Three tasks, the second fails at 10 ms: `Wait` returns that error, and the derived context is cancelled when it fails.

**Constraints.** `SetLimit(n)` makes `Go` block when `n` goroutines are running. Calling `Go` after `Wait` is out of scope.

**Follow-up.** How can code that calls `Go` from inside a goroutine already in a limited group deadlock? What should happen if a task panics?

#### 13.2 Parallel File Hasher (Medium)

**Task.** `func HashAll(ctx context.Context, paths []string, limit int) (map[string]string, error)` hashes files with at most `limit` in flight and returns path to hash, or the first error.

**Example.** 1000 files, `limit = 8`. One unreadable file aborts the rest.

**Constraints.** The result map must be safe to write from multiple goroutines.

**Follow-up.** After the first error, how long until the other goroutines stop, and what decides that? Does a large `io.Copy` notice cancellation?

### Day 14: Timers and tickers

Since Go 1.23, timer channels are synchronous, so no stale value can be received after `Stop` or `Reset` returns; Go 1.27 removed the old behaviour completely.

#### 14.1 Debouncer (Medium)

**Task.** `NewDebouncer(d time.Duration, f func())` with `Trigger()` and `Stop()`. `f` runs once, `d` after the last trigger.

**Example.** Five triggers within 10 ms, `d = 50ms`: `f` runs once, about 60 ms after the first trigger.

**Constraints.** `Trigger` is safe from many goroutines, and `Stop` guarantees `f` does not start afterwards.

**Follow-up.** A `time.AfterFunc` callback runs in its own goroutine. Can two runs of a slow `f` overlap, and what would you change to prevent it?

#### 14.2 Token Bucket (Medium)

**Task.** `NewLimiter(rate float64, burst int)` with `Allow() bool` and `Wait(ctx context.Context) error`, computed lazily from elapsed time with no background goroutine.

**Example.** Rate 10 per second, burst 5: 5 immediate `Allow` calls succeed, the sixth fails, and one more succeeds 100 ms later.

**Constraints.** Thread-safe, monotonic-clock safe, `Wait` honours cancellation.

**Follow-up.** Why does a ticker-goroutine design leak a goroutine per limiter? In Go 1.27, can `len(t.C)` or `cap(t.C)` of a timer ever be non-zero, and can a stale value appear after `Reset`?

## Phase 3: Memory and internals (Days 15 to 21)

By Day 21 you should be able to explain what the runtime does underneath a `go` statement, a channel send, a mutex lock and an allocation, and use that to predict performance and bugs.

### Day 15: The Go memory model

A read is only guaranteed to see a write if a happens-before edge connects them; without one the program has a data race, even if it 'works'.

#### 15.1 Spot the Race (Medium, Debug)

```go
// A
var done bool
go func() { done = true }()
for !done {}

// B
var msg string
var ready bool
go func() { msg = "hello"; ready = true }()
for !ready {}
println(msg)

// C
var inst *T
func Get() *T {
    if inst == nil {
        mu.Lock()
        if inst == nil { inst = &T{x: 1} }
        mu.Unlock()
    }
    return inst
}
```

**Task.** For A, B and C say whether each is a data race, which happens-before edge is missing, and give a fix. For A, explain how the compiler may turn the loop into an infinite loop.

**Example.** For B, a correct answer names the exact two operations that are unordered and gives a version using a channel close.

**Constraints.** Each fix must use a different primitive: channel, `sync.Once`, `atomic`.

**Follow-up.** In C, a reader can see `inst != nil` yet read `x == 0`. Explain why the lock on the write side does not protect the unlocked read.

#### 15.2 Safe Publication (Medium)

**Task.** Implement a lazy singleton `Get() *Config` three ways: `sync.Once`, `sync.OnceValue`, and `atomic.Pointer` with compare-and-swap.

**Example.** 1000 goroutines call `Get` at once and all receive the same pointer, and the constructor ran once.

**Constraints.** With the CAS version the constructor may run more than once; the result must still be a single winner.

**Follow-up.** State the happens-before guarantee that `Once.Do` gives, in one sentence. Which of your three versions allocates an unused `Config` under contention, and what is the cost?

### Day 16: Maps and races

A concurrent map access is not an ordinary panic: the runtime treats it as fatal, and you cannot recover from it.

#### 16.1 Concurrent Map Fatal (Medium, Debug)

**Task.** Write three programs that trigger a map misuse: two writers, a reader and a writer, and an iteration during a write. Run each on Go 1.27 and record which print a `fatal error`, which silently corrupt, and which pass.

**Example.** Show that wrapping the map access in `defer recover()` does not stop the process.

**Constraints.** Fix each program three ways: `sync.Mutex`, `sync.Map`, and a channel-owned map goroutine.

**Follow-up.** Detection of misuse is best effort, not a guarantee. What does that mean for relying on it in tests, and which tool is the real detector? Go 1.24 replaced the built-in map with Swiss tables; did your results differ from what older write-ups say?

#### 16.2 Sharded Map (Medium)

**Task.** `NewShardedMap[K comparable, V any](shards int)` with `Get`, `Set`, `Delete`, `Range(func(K, V) bool)`, choosing the shard with `maphash.Comparable` (Go 1.24).

**Example.** 64 goroutines do 1000000 mixed operations; results match a single-mutex reference map.

**Constraints.** `shards` is a power of two between 1 and 1024. `Range` must not hold all shard locks at once.

**Follow-up.** What does `Range` guarantee about entries added during the walk? What happens to your distribution if the key type hashes poorly? Benchmark against `sync.Map` for read-heavy and write-heavy mixes.

### Day 17: Garbage collection and goroutine memory

The Green Tea collector became the default in Go 1.26, so older advice about GC cost for small objects needs re-measuring.

#### 17.1 Goroutine Footprint (Medium)

**Task.** Park 1000000 goroutines on a channel and report bytes per goroutine, using `runtime/metrics` stack and heap numbers rather than `Sys`.

**Example.** Output such as `goroutines=1000000 stack_bytes=... per_goroutine=...`.

**Constraints.** Run with `GOMEMLIMIT` set, and report the value you chose.

**Follow-up.** Why is the per-goroutine cost not simply the minimum stack size? How does stack growth work (copy, not segments), and when does the GC shrink stacks? If your toolchain still honours `GOEXPERIMENT=nogreenteagc`, run the allocation-heavy part of your program under both collectors and report the difference.

#### 17.2 Weak Cache (Hard)

**Task.** `NewWeakCache[K comparable, V any]()` with `Get(k K, load func() *V) *V` and `Len() int`. Entries are held through `weak.Pointer[V]`, so the GC can reclaim a value nobody else references. Use `runtime.AddCleanup` to delete dead entries.

**Example.** Store 1000 values, drop every strong reference, call `runtime.GC()`; `Len()` reaches 0 within a bounded number of tries.

**Constraints.** Thread-safe. A reader that gets a nil from `weak.Pointer.Value()` must reload, not return nil.

**Follow-up.** Why is `AddCleanup` preferred over `SetFinalizer` (multiple cleanups, no resurrection, cycles)? What happens if the cleanup function or its argument references the object itself?

### Day 18: Escape analysis and cache lines

Whether a value lives on a goroutine stack or the heap decides both GC load and whether it is safe to share.

#### 18.1 False Sharing (Medium)

**Task.** Eight goroutines each increment their own counter 10000000 times. Version A: `[8]int64`. Version B: each counter padded to its own cache line. Benchmark with `b.Loop()`.

**Example.** Report ns/op for both versions at 1, 2, 4 and 8 goroutines.

**Constraints.** Do not use atomics in either version. State the cache line size you assumed and where you found it for your CPU.

**Follow-up.** Why does `b.Loop()` (whose inlining problem was fixed in Go 1.26) matter for this benchmark? Show how a per-core sharded atomic counter combines padding with atomics.

#### 18.2 Escape or Not (Medium, Predict)

```go
func a() *int { x := 1; return &x }
func b() { x := 1; go func() { println(x) }() }
func c(ch chan *int) { x := 1; ch <- &x }
func d(n int) { s := make([]int, n); _ = s }
func e() any { x := 1; return x }
func f() { x := 1; p := &x; _ = *p }
```

**Task.** Predict for each function whether `x` or `s` is heap allocated. Then check with `go build -gcflags=-m=2` and explain every difference.

**Example.** For `d`, note whether the result changes when `n` is a constant, and whether the Go 1.26 change to stack allocation of slice backing stores applies.

**Constraints.** Write predictions before running the compiler.

**Follow-up.** Why does sending a pointer on a channel force an escape but sending an `int` does not? Which of these lifetimes does a goroutine's closure extend?

### Day 19: The scheduler

Goroutines (G) run on OS threads (M) that hold a processor (P); the number of Ps is `GOMAXPROCS`.

#### 19.1 Preemption and Run Order (Medium, Predict)

```go
runtime.GOMAXPROCS(1)
for i := 0; i < 3; i++ {
    go func() { println(i) }()
}
time.Sleep(10 * time.Millisecond)
```

**Task.** Predict the usual print order with one P and explain it (the `runnext` slot). Then add a goroutine running `for {}` and decide whether the program finishes in Go 1.27.

**Example.** Explain what async preemption does and what `GODEBUG=asyncpreemptoff=1` would change.

**Constraints.** Verify with `GODEBUG=schedtrace=1000`.

**Follow-up.** What does `sysmon` do for a goroutine that runs longer than 10 ms, and for a goroutine blocked in a system call?

#### 19.2 Threads Under Blocking (Hard)

**Task.** Start 1000 goroutines each doing (a) `time.Sleep`, (b) a network read on an idle socket, (c) a blocking system call such as a slow file read or a cgo sleep. Record the OS thread count for each using `/sched/threads:threads` from `runtime/metrics` (Go 1.26).

**Example.** (a) and (b) use few threads; (c) can use many. Explain why.

**Constraints.** Report the metric before, during and after.

**Follow-up.** What does `runtime.LockOSThread` change about this? What is the default thread limit and what happens when it is hit?

### Day 20: `GOMAXPROCS` in containers

Since Go 1.25 the default `GOMAXPROCS` follows the cgroup CPU limit and updates while the program runs, unless you set it explicitly.

#### 20.1 Effective GOMAXPROCS (Medium)

**Task.** `func EffectiveProcs(logicalCPUs int, quota, period int64, explicit bool) int` models the Go 1.25 default: the lower of the logical CPU count and the cgroup CPU limit, unless `GOMAXPROCS` was set by environment variable or call.

**Example.** 16 CPUs, quota 200000, period 100000 returns 2. 16 CPUs, `explicit = true` returns the explicit value.

**Constraints.** Verify against a real container started with `--cpus=1.5`, and record the rounding rule you observe for a fractional limit.

**Follow-up.** The runtime ignores the Kubernetes CPU request and uses only the limit. What throttling symptom appears if the limit is far below the node's core count? Which two `GODEBUG` settings turn off the container and the periodic-update behaviour?

#### 20.2 Scheduler Dashboard (Medium)

**Task.** Build a program that prints once per second: goroutines by state (the `/sched/goroutines` metrics), thread count, goroutines created, and the scheduling-latency p99.

**Example.** Start `2 * GOMAXPROCS` CPU-bound goroutines and show runnable goroutines and latency rise.

**Constraints.** Read metrics with `runtime/metrics`, not `runtime.NumGoroutine`.

**Follow-up.** Many runnable goroutines with low measured CPU use: what does that suggest about the container? How would you tell it apart from a genuine overload?

### Day 21: Channel and mutex internals

A channel is a locked ring buffer plus two wait queues; a mutex is a state word with a slow path that parks goroutines.

#### 21.1 Build a Channel (Hard)

**Task.** Implement `Chan[T]` with `Send`, `Recv() (T, bool)`, `Close`, and `Len`, supporting capacity 0 and N. Keep FIFO wait queues for blocked senders and receivers.

**Example.** Capacity 0: `Send` blocks until a receiver arrives and hands the value over directly.

**Constraints.** Sending on a closed channel panics, `Close` of a closed channel panics, receiving after close drains the buffer then returns `(zero, false)`. Use only `sync.Mutex` and per-waiter signalling.

**Follow-up.** How would a multi-channel `select` acquire several channel locks without deadlocking? (Think ordering.) Where does a woken sender re-check state?

#### 21.2 Mutex Starvation Mode (Hard, Predict)

**Task.** One goroutine runs `for { mu.Lock(); mu.Unlock() }`. A second goroutine tries to lock once per millisecond and records how long each lock took. Predict, then measure, the maximum wait.

**Example.** Explain normal mode versus starvation mode in `sync.Mutex`, and the waiting time that triggers the switch.

**Constraints.** Run with `GOMAXPROCS=2` and with `GOMAXPROCS=1`, and compare.

**Follow-up.** The Go 1.24 release notes mention a new runtime-internal mutex. Why does that not change how `sync.Mutex` behaves in your program?

## Phase 4: Production concurrency (Days 22 to 27)

By Day 27 you should be able to find a leak or a stall from a profile, test time-dependent concurrent code without sleeping, and shut a service down cleanly.

### Day 22: Iterators and concurrency

A range-over-func loop body runs as the `yield` callback, so concurrency around iterators has rules that channels do not have.

#### 22.1 Parallel Map Over a Sequence (Medium)

**Task.** `func ParMap[T, R any](seq iter.Seq[T], workers int, f func(T) R) iter.Seq[R]` yields results in input order, computed by `workers` goroutines.

**Example.** `seq = 1..5`, `f = double` yields `2,4,6,8,10`.

**Constraints.** When the consumer breaks out of the loop, all workers stop within one `f` call and no goroutine remains.

**Follow-up.** Why must `yield` be called only from the goroutine that is running the loop, and what happens if a worker goroutine calls it? What does the runtime do if `yield` is called after the loop has exited?

#### 22.2 `iter.Pull` Leak (Medium, Debug)

**Task.** Implement `Zip[A, B any](a iter.Seq[A], b iter.Seq[B]) iter.Seq2[A, B]` using `iter.Pull` on both inputs. Then show how a version that forgets `stop()` on an early break leaves goroutines behind.

**Example.** `Zip([1,2,3], [x,y])` yields `(1,x), (2,y)` and ends.

**Constraints.** `stop` is called on every path, including a panic in the consumer. Verify with a goroutine dump after 1000 early breaks.

**Follow-up.** Benchmark `iter.Pull` against a goroutine-plus-channel generator. What do you measure, and why does one switch of control cost less than the other?

### Day 23: Goroutine leaks

A leaked goroutine is one blocked forever on something nobody can reach; since Go 1.27 the runtime can report many of them.

#### 23.1 Fix the Fan-In Leak (Medium)

```go
func processWorkItems(ws []workItem) ([]workResult, error) {
    ch := make(chan result)
    for _, w := range ws {
        go func() {
            res, err := processWorkItem(w)
            ch <- result{res, err}
        }()
    }
    var results []workResult
    for range len(ws) {
        r := <-ch
        if r.err != nil {
            return nil, r.err
        }
        results = append(results, r.res)
    }
    return results, nil
}
```

**Task.** The Go 1.26 release notes use this example. Show how many goroutines leak when item 3 of 1000 fails, then fix it three ways: a buffered channel, a context with a select on every send, and `errgroup`.

**Example.** After the fix, `runtime.NumGoroutine()` returns to its starting value.

**Constraints.** Remaining work must stop early in at least one of your fixes.

**Follow-up.** The buffered-channel fix stops the leak but not the wasted work. Explain the difference and when each is acceptable.

#### 23.2 What the Leak Profile Sees (Hard, Predict)

**Task.** For each case, predict whether the `goroutineleak` profile reports the goroutine, then run it and record the result.

1. A goroutine blocked on a channel that only it references.
2. A goroutine blocked on a channel stored in a package-level variable.
3. A goroutine waiting on a `sync.Mutex` that an exited goroutine never unlocked.
4. A goroutine blocked on a channel referenced by another goroutine that is still running a loop.
5. A goroutine in `sync.WaitGroup.Wait` whose counter never reaches zero.
6. A goroutine blocked reading an idle network connection.

**Example.** Case 1 is detectable because the channel is unreachable from every runnable goroutine.

**Constraints.** Enable the profile through `runtime/pprof` and through `/debug/pprof/goroutineleak`.

**Follow-up.** The detector works by reachability. Explain, using cases 2 and 4, why it can miss a leak that a human sees at once, and what that means for how you use it alongside a test-time leak checker.

### Day 24: Testing concurrent code

`testing/synctest` runs code in a bubble with a fake clock, so a 30-second timeout test finishes in milliseconds and without flakiness.

#### 24.1 Test the Debouncer Without Sleeping (Medium)

**Task.** Write tests for your Day 14 debouncer with `synctest.Test`, using `time.Sleep` for virtual time and `synctest.Wait` to let goroutines settle.

**Example.** Trigger 5 times 10 ms apart with `d = 50ms`. Assert `f` has not run at 89 ms and has run exactly once at 91 ms of fake time.

**Constraints.** Real run time under 50 ms. No `time.Sleep` outside the bubble. Try `synctest.Sleep` from Go 1.27.

**Follow-up.** Which blocking operations count as durably blocked for the bubble (check the package docs), and which do not, such as a mutex or real network I/O? What happens in your test if a goroutine in the bubble outlives it?

#### 24.2 Timeouts Over an In-Memory Network (Medium)

**Task.** Test a client with a 30 s request timeout and 3 retries against `httptest.NewTestServer` (Go 1.27), whose network is in memory and usable inside a bubble.

**Example.** The server delays 31 s on the first two calls and answers on the third; the test passes in under 100 ms of real time.

**Constraints.** Assert the exact fake time at which each attempt started.

**Follow-up.** Make the client wait on a channel nobody sends to, and record what the bubble does when every goroutine is durably blocked and no timers are pending.

### Day 25: Profiling and tracing

The goroutine, block and mutex profiles and the execution trace answer different questions; knowing which to open first is the skill.

#### 25.1 Read the Goroutine Dump (Hard, Debug)

```
goroutine 1 [semacquire, 4 minutes]:
main.main()

goroutine 18 [sync.Mutex.Lock, 4 minutes]:
main.transfer(0xc000010000, 0xc000010020)

goroutine 19 [sync.Mutex.Lock, 4 minutes]:
main.transfer(0xc000010020, 0xc000010000)

goroutine 22 [chan receive, 4 minutes]:
main.worker(0xc00007e060)
```

**Task.** Identify the deadlock cycle between goroutines 18 and 19, what goroutine 1 is waiting for, and why goroutine 22 is a separate symptom. (Wait-reason text varies by Go version.)

**Example.** The root cause is lock acquisition in argument order, as in problem 8.1.

**Constraints.** Reproduce the dump yourself and get it with `SIGQUIT` and with the pprof endpoint.

**Follow-up.** In a module on Go 1.27 or later, tracebacks include `runtime/pprof` goroutine labels. Set labels with `pprof.Do` on two identical workers and show how the dump now tells them apart. Which `GODEBUG` setting turns that off?

#### 25.2 Flight Recorder (Hard)

**Task.** Add a flight recorder to an HTTP service so that when a request takes longer than 500 ms, the last few seconds of execution trace are written to a file. Confirm the exact `runtime/trace` API in the package docs first.

**Example.** A handler that sleeps 600 ms produces one trace file containing that request's goroutines.

**Constraints.** At most one snapshot per 10 seconds. Overhead in the fast path must be measurable and reported.

**Follow-up.** Open the trace with `go tool trace`. Since Go 1.27, passing only a port to `-http` listens on localhost only; why is that a sensible default? Where in the trace do you look for scheduler latency and GC pauses?

### Day 26: Production patterns

Backpressure and ownership decisions, not primitives, are where concurrent services usually fail.

#### 26.1 Pub/Sub Broker (Hard)

**Task.** `Subscribe(topic string, buf int) (<-chan Msg, func())` and `Publish(topic string, m Msg)`. The publisher never blocks. If a subscriber's buffer is full, drop its oldest message and count the drop.

**Example.** A slow subscriber with `buf = 2` receiving 10 messages sees the last 2, and the drop counter reads 8.

**Constraints.** Calling the cancel function during a concurrent `Publish` must never cause a send on a closed channel.

**Follow-up.** Who closes each subscriber channel and why must it be the broker? Explain the race between `cancel` and `Publish` and how you removed it, then prove it with `-race -count=500`.

#### 26.2 `sync.Pool` Pitfalls (Medium, Debug)

```go
var pool = sync.Pool{New: func() any { return new(bytes.Buffer) }}

func render(w io.Writer, v any) []byte {
    b := pool.Get().(*bytes.Buffer)
    defer pool.Put(b)
    json.NewEncoder(b).Encode(v)
    return b.Bytes()
}
```

**Task.** Find the bug (the returned slice aliases a buffer that goes back into the pool), a second bug (no `Reset`), and a memory bloat problem after one huge response. Fix all three.

**Example.** Two concurrent calls return corrupted output under load without the fix.

**Constraints.** Discard buffers over 64 KiB instead of pooling them.

**Follow-up.** Why must a `sync.Pool` never be used as a connection pool? What does a garbage collection do to its contents?

### Day 27: Shutdown and failure

Shutdown is a protocol: stop accepting, drain, release, in that order, with a deadline.

#### 27.1 Graceful Shutdown Manager (Hard)

**Task.** `type Runner` with `Add(name string, run func(ctx context.Context) error, stopTimeout time.Duration)` and `Run(ctx context.Context) error`. On `SIGINT` or `SIGTERM` it cancels every component, waits up to each component's timeout, and returns the joined errors.

**Example.** An HTTP server with in-flight requests drains within its timeout, then a database closer runs after it.

**Constraints.** A second signal forces immediate exit. Use `signal.NotifyContext` and log `context.Cause` to name the signal (Go 1.26).

**Follow-up.** How do you order shutdown when component B depends on A? What does your manager do with a component that ignores its context, and how does the process still exit?

#### 27.2 Panic Containment (Medium, Predict)

```go
// a
defer recover()
panic(1)

// b
go func() { panic(2) }()
defer func() { recover() }()
time.Sleep(time.Second)

// c
runtime.Goexit()   // called in main, other goroutines finished

// d
select {}          // no other goroutines exist
```

**Task.** Predict what each fragment does. Then write `Go(f func() error) <-chan error` that runs `f` in a goroutine, converts a panic into an error carrying `debug.Stack()`, and works with `errgroup`.

**Example.** `Go(func() error { panic(x) })` returns an error whose text includes the panic value and a stack.

**Constraints.** Explain which of a to d the program can survive and which end in a fatal error that no `recover` can intercept.

**Follow-up.** Why does `defer recover()` not stop a panic, while `defer func() { recover() }()` does? Why can a parent goroutine never recover a child's panic?

## Phase 5: Capstone (Days 28 to 30)

These seven problems combine everything above. Budget 90 minutes each, write tests first, and finish each with a one-paragraph design note you could read aloud in an interview.

### Day 28: Systems design in code

A scheduler and a resilient client are the two most common concurrent components in real services.

#### 28.1 Delayed Task Scheduler (Hard)

**Task.** `Schedule(at time.Time, f func(context.Context)) ID`, `Cancel(id ID) bool`, and `Stop(ctx context.Context) error`. One timer goroutine owns a min-heap; a bounded worker pool runs tasks.

**Example.** Schedule 100000 tasks at random offsets within 10 s of fake time; each runs once, in due order within a tolerance of one tick, and `Stop` waits for running tasks.

**Constraints.** Inserting a task earlier than the current heap top must wake the timer. Tests use `testing/synctest`, not real sleeps. No goroutine remains after `Stop`.

**Follow-up.** How do you reset the timer when the top changes, and why is that simpler on Go 1.23 and later? What goes wrong if you schedule from wall-clock time and the system clock steps?

#### 28.2 Resilient HTTP Client (Hard)

**Task.** Wrap `http.Client` with: a global in-flight limit, a per-host token bucket, retries with backoff on 5xx and 429 honouring `Retry-After`, a circuit breaker (closed, open, half-open), and deduplication of identical concurrent GETs.

**Example.** A test server fails 5 times in a row: the breaker opens, calls fail fast for 30 s of fake time, then one probe request closes it.

**Constraints.** Test with `httptest.NewTestServer` inside a `synctest` bubble. Context cancellation must abort waits and in-flight calls.

**Follow-up.** Where in this design can a goroutine leak, and which of your tests would catch it? Go 1.27 drains unread HTTP/1 response bodies on `Close` up to a limit; does that change what your client must do when it ignores a body?

### Day 29: Performance engineering

Lock-free code is a tool you earn with a benchmark, not a default.

#### 29.1 Bounded MPMC Queue (Hard)

**Task.** `NewQueue[T any](capacity int)` with `Enqueue(v T) bool` and `Dequeue() (T, bool)`, lock-free, multiple producers and consumers. Use a ring buffer with a per-slot sequence number and `atomic.Uint64` head and tail.

**Example.** 8 producers and 8 consumers move 10000000 items; every item is received exactly once.

**Constraints.** `capacity` is a power of two. Both operations are non-blocking and return false when full or empty. Pass `-race` under stress.

**Follow-up.** Benchmark against a buffered channel and a mutex-protected slice at 1, 4 and 16 goroutines. Which wins, when, and why? Add padding between head and tail and measure the effect.

#### 29.2 Read-Mostly Routing Table (Hard)

**Task.** A routing table is read about a million times per second and updated about once a minute with a new full snapshot. Build it with `atomic.Pointer` to an immutable snapshot and a serialised writer.

**Example.** 64 reader goroutines resolve keys continuously while a writer swaps in a new table every 10 ms; no reader ever sees a half-updated table.

**Constraints.** Readers take no locks and do no allocation. Compare with an `RWMutex` version at 64 goroutines.

**Follow-up.** Who frees the old snapshot, and when? How does a large snapshot change GC pressure under the Green Tea collector? Add a version number and explain how a reader can detect that it is working with a stale snapshot.

### Day 30: Mock interview

Set a 3-hour timer, open no notes, and speak your reasoning aloud.

#### 30.1 Building H2O, LC 1117 (Medium)

**Task.** Many goroutines call `Hydrogen()` and `Oxygen()`. Release them so every group of three consists of two hydrogens and one oxygen before the next group starts.

**Example.** Input stream `HOH` forms `HHO` in any order within the group. Input `OOHHHH` produces two complete molecules.

**Constraints.** Up to 1000 goroutines. No busy waiting. No goroutine may be left blocked at the end when counts match.

**Follow-up.** Argue that your solution cannot deadlock when the input is `HHHHHH` followed by `OO` arriving later.

#### 30.2 Fizz Buzz Multithreaded, LC 1195 (Medium)

**Task.** Four goroutines handle `fizz`, `buzz`, `fizzbuzz` and the plain number. For `1..n` the combined output must be the ordinary FizzBuzz sequence in order.

**Example.** `n = 15` prints `1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz`.

**Constraints.** `1 <= n <= 50`. All four goroutines exit when `n` is reached.

**Follow-up.** Compare a design with one coordinator goroutine and one channel per worker against one where workers poll a shared counter. Which is easier to prove correct?

#### 30.3 Production Incident (Hard, open-ended)

**Scenario.** A Go 1.27 service in a container limited to 2 CPUs on a 32-core node shows these symptoms over six hours: goroutine count rises from 2000 to 400000, memory climbs steadily, request latency p99 grows from 80 ms to 9 s, and CPU use stays near 50% of the limit.

**Task.** Write a one-page diagnosis plan: your top five hypotheses ranked by likelihood, the exact profile, metric or trace that confirms or rejects each, the fix, and the regression test (with `synctest` where possible).

**Example of a strong answer.** It names the goroutine leak profile and the `/sched/goroutines` metrics as the first check, separates a leak from a slow downstream (many goroutines legitimately blocked), and checks the scheduling-latency histogram and cgroup throttling before touching the code.

**Constraints.** No hypothesis may be 'add more CPU'. Each needs a falsifiable check.

**Follow-up.** Choose one hypothesis and write the smallest reproduction as a test that fails on the buggy code and passes on the fix.

## Things to avoid

Twenty patterns cause most real Go concurrency failures, and every one of them appears as a problem above.

| Avoid | Why it fails | Do instead | Day |
| --- | --- | --- | --- |
| Goroutines with no owner and no stop path | They leak, hold memory and block shutdown | Tie each to a `context`, an `errgroup` or a `WaitGroup` | 23 |
| `wg.Add` inside the goroutine | `Wait` can return before `Add` runs | `wg.Go` (Go 1.25) or `Add` before `go` | 4 |
| Copying a struct that holds a `sync.Mutex` | The copy has its own lock, so nothing is protected | Pointer receivers; run `go vet` | 8 |
| `time.Sleep` to wait for another goroutine | Flaky and slow | Channels, `WaitGroup`, or `synctest` in tests | 24 |
| Closing a channel from the receiving side, or from several senders | Panic on double close or send after close | One owner closes, after all sends finish | 2, 26 |
| Unbuffered send on a path that can return early | Leaks the sender | Select on `ctx.Done()`, or `errgroup` | 23 |
| One goroutine per item of unbounded input | Overwhelms the downstream even if goroutines are cheap | A bounded pool or `SetLimit` | 6, 13 |
| Holding a lock across I/O or a callback | Stalls everyone and invites deadlock | Copy data out, then call | 8 |
| A plain map shared between goroutines | Fatal error, or silent corruption | Mutex, sharding, `sync.Map`, or one owning goroutine | 16 |
| Mutating the object returned by `atomic.Pointer.Load` | Atomic swap does not protect the pointee | Copy-on-write snapshots | 10, 29 |
| Deciding anything from `len(ch)` | Stale the moment you read it | Non-blocking `select` | 14 |
| Draining a timer channel before `Reset` | Obsolete since Go 1.23; adds bugs | Just call `Reset` or `Stop` | 14 |
| Ignoring `ctx` inside loops and blocking calls | Cancellation never arrives | Check `ctx.Done()` in every wait | 12, 13 |
| Using `sync.Pool` as a connection pool, or pooling huge buffers | The GC may empty it; bloat | Real pool; cap buffer size | 26 |
| `runtime.SetFinalizer` for new cleanup code | One per object, delays freeing, breaks on cycles | `runtime.AddCleanup` | 17 |
| Relying on `Gosched` or `GOMAXPROCS(1)` for correctness | Preemption and scheduling are not a contract | Real synchronisation | 19 |
| Expecting a parent to `recover` a child's panic | It crashes the process | `recover` in each goroutine | 27 |
| Importing `automaxprocs` or hard-coding `GOMAXPROCS` on Go 1.25 or later | The runtime already follows the cgroup limit | Remove it; measure | 20 |
| Calling `yield` from another goroutine | Breaks range-over-func rules | Collect in workers, yield from the loop goroutine | 22 |
| Lock-free code before measuring | Hard to prove, often no faster | Mutex or channel first, benchmark, then decide | 29 |

## Coverage map

Every concurrency topic in the language and runtime is mapped to the days that drill it.

| Area | Topics | Days |
| --- | --- | --- |
| Language basics | `go` statement, loop variables, channels (nil, closed, buffered), `select`, `range` over channels | 1 to 3 |
| Coordination | `WaitGroup`, `WaitGroup.Go`, `Once`, `OnceFunc`, `OnceValue`, pipelines, fan-out, worker pools, semaphores | 4 to 7, 9 |
| Locks | `Mutex`, `RWMutex`, lock ordering, copy-lock vet, `Cond`, barriers | 8, 9, 11 |
| Lock-free | `sync/atomic` typed atomics, CAS loops, `And` and `Or`, `atomic.Pointer`, MPMC queue | 10, 29 |
| Cancellation and time | `context` (cause, deadline, `AfterFunc`, `WithoutCancel`), `errgroup`, timers, tickers, `NotifyContext` | 12 to 14, 27 |
| Maps and caches | `sync.Map`, sharded maps, LRU, memoisation, weak caches | 9, 16, 17 |
| Memory model | Happens-before, data races, safe publication, race detector | 15, 16 |
| Memory management | GC (Green Tea), goroutine stacks, escape analysis, false sharing, `weak`, `AddCleanup`, pools | 17, 18, 26 |
| Runtime internals | G-M-P scheduler, preemption, syscalls and threads, `GOMAXPROCS` and cgroups, channel and mutex internals | 19 to 21 |
| Iterators | Range-over-func, `iter.Pull`, parallel iteration | 22 |
| Diagnosis | Leak detection, goroutine dumps, pprof, trace, flight recorder, `runtime/metrics`, labels | 23, 25, 30 |
| Testing | `synctest`, `-race`, in-memory HTTP, benchmarks with `b.Loop` | 18, 24, 28 |
| Failure and shutdown | Panics, `Goexit`, fatal deadlock, graceful shutdown | 27 |
| Design | Schedulers, resilient clients, pub/sub, routing tables, interview classics | 7, 26, 28 to 30 |

**Not covered.** `cgo` threading details, `unsafe`-based tricks, WebAssembly and `GOOS`-specific scheduling behaviour. Add them after Day 30 if your work needs them.

## Sources

Checked on 13 November 2026. The first two pages were opened in full; the rest were read as search excerpts, so verify details against the full page before relying on them.

- [Go 1.27 Release Notes](https://go.dev/doc/go1.27) (opened in full)
- [Go 1.26 Release Notes](https://go.dev/doc/go1.26) (opened in full)
- [Go 1.25 Release Notes](https://tip.golang.org/doc/go1.25) (search excerpt)
- [Go 1.24 Release Notes](https://go.dev/doc/go1.24) (search excerpt)
- [Go 1.23 Timer Channel Changes, Go wiki](https://go.dev/wiki/Go123Timer) (search excerpt)
- [InfoQ: Go 1.24 brings generic type aliases, weak pointers, improved finalizers](https://www.infoq.com/news/2025/02/go-1-24-generic-aliases) (search excerpt; source for the `sync.Map` rewrite)

**Not verified against an official page:** the Go 1.22 loop variable change, `iter` and range-over-func (1.23), `atomic.And` and `atomic.Or` (1.23), and the `runtime/trace` flight recorder API (1.25). These are stable or documented in the package docs, and the problems that use them tell you to confirm the API first.
