Patterns
Concurrent services repeat about ten shapes. For each one: when to use it, the tested code, the bug people write, and a test that catches that bug.
- 1Bound everything: goroutines, queues, retries and waits. A spike finds each thing with no bound.
- 2Each blocking send needs a way out. Each goroutine needs a test that proves it exits.
- 3Stop in dependency order: first the thing that feeds work, then the thing that does it.
- 4Workers for CPU work: the core count. Workers for waiting work: rate times latency.
package main
import (
"fmt"
"sync"
)
func main() {
jobs := make(chan int)
results := make(chan int)
var wg sync.WaitGroup
for range 3 {
wg.Go(func() {
for j := range jobs {
results <- j * 21
}
})
}
for i := range 5 {
jobs <- i2
}
close(jobs)
wg.Wait()3
close(results)
sum := 0
for r := range results {
sum += r
}
fmt.Println("sum:", sum)
}- 1Each worker blocks here on its first result. No one reads results yet.
- 2Main feeds the jobs. After 3 jobs every worker is stuck, so the fourth send never completes.
- 3The order looks right, but main never reaches this line.
| version | recorded output | status |
|---|---|---|
| Main sends, then reads | fatal error: all goroutines are asleep - deadlock! | Deadlock |
| A goroutine sends, main reads | sum: 20 | Approved |
- The fix moves the sends, the close and the Wait into one goroutine. Main only reads.
- One job is enough to deadlock this program: main reads results only after Wait, and Wait needs a reader.
- The runtime reports this deadlock because every goroutine is blocked. In a server, an idle listener keeps the program alive, and requests hang with no report.
Unbuffered channels connect the producer and the consumer, so one goroutine cannot do both. I move one side to its own goroutine.
Step 1: Admit
- Each client has a token bucket. A request spends one token or gets 429.
- The check runs first, so a rejected request costs almost nothing.
If it fails
The map of buckets grows with every new client. A sweep removes idle clients.
I walk a request through the service and name the pattern at each stage, then the stop order.
| you need | use | status |
|---|---|---|
| Run N known tasks and stop at the first error | errgroup + SetLimit | Approved |
| Process jobs that arrive over time, off the request path | Worker pool with a bounded queue | Approved |
| Stages that each transform a stream | Pipeline with cancel | More than one stage |
| Limit callers of one dependency, in any code path | Semaphore | Approved |
| Limit by bytes or by cost, not by count | semaphore.Weighted | Approved |
| Stop a cache stampede | singleflight | Approved |
| Reject clients above a rate | rate.Limiter, Allow | Approved |
| Slow yourself down to fit a quota | rate.Limiter, Wait | Approved |
| One writer per key, with keys unknown in advance | Per-key lock | Approved |
| Start one goroutine per request or per item, with no limit | go f() | Not approved |
| Retry with no backoff, or on a permanent error | Plain loop | Not approved |
I pick the smallest pattern that bounds the work. Most fan-out in a request is errgroup with a limit.
// leaked runs fn and returns how many goroutines it left blocked for good.
// The goroutineleak profile asks the garbage collector which blocked
// goroutines nothing can reach.
func leaked(t *testing.T, fn func()) int {
t.Helper()
before := leakCount(t)
base := runtime.NumGoroutine()
go fn()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
if n := leakCount(t) - before; n > 0 {
return n
}
if runtime.NumGoroutine() <= base {
return 0
}
}
t.Fatal("goroutines still running, neither finished nor leaked")
return 0
}
func leakCount(t *testing.T) int {
t.Helper()
p := pprof.Lookup("goroutineleak")1
if err := p.WriteTo(io.Discard, 0)2; err != nil { // runs the detection
t.Fatalf("leak profile: %v", err)
}
return p.Count()
}- 1Generally available since Go 1.27. Go 1.26 had it behind an experiment.
- 2Writing the profile runs a special collection, which marks the leaked goroutines.
- A blocked goroutine is leaked when no running goroutine can reach what it waits on.
- A goroutine can hide from the check. A channel in a global variable stays reachable.
- For leaks of this kind, also compare runtime.NumGoroutine before and after.
- Each table below runs the correct code and the bug through one check. A row named "the bug" must fail the check, so the test proves it can catch the bug.
- Tests that depend on time run in a synctest bubble, on a fake clock.
My tests ask the runtime for leaked goroutines. Go 1.27 made the goroutineleak profile generally available.
- Use it when jobs arrive over time and the work must stay bounded. The workers bound the concurrency, and the queue bounds the backlog.
- Submit makes the caller wait. TrySubmit sheds the job. Choose per call site.
// ErrClosed: the pool takes no more jobs. ErrBusy: its queue is full.
var (
ErrClosed = errors.New("pool closed")
ErrBusy = errors.New("queue full")
)
// Pool runs jobs on a fixed set of workers.
type Pool struct {
mu sync.RWMutex1 // Submit holds it to read, Close to write
closed bool
jobs chan func()
wg sync.WaitGroup
}
// NewPool starts the workers. The queue holds jobs no worker has taken.
func NewPool(workers, queue int) *Pool {
p := &Pool{jobs: make(chan func(), queue)}
for range workers {
p.wg.Go(func() {
for job := range p.jobs2 {
job()
}
})
}
return p
}
// Submit waits for room in the queue. Use it when the caller can wait.
func (p *Pool) Submit(ctx context.Context, job func()) error {
p.mu.RLock()
defer p.mu.RUnlock()
if p.closed {
return ErrClosed
}
select {
case p.jobs <- job:
return nil
case <-ctx.Done():3
return context.Cause(ctx)
}
}
// TrySubmit fails at once when the queue is full. Use it to shed load.
func (p *Pool) TrySubmit(job func()) error {
p.mu.RLock()
defer p.mu.RUnlock()
if p.closed {
return ErrClosed
}
select {
case p.jobs <- job:
return nil
default:4
return ErrBusy
}
}
// Close stops new jobs, runs the queued ones, and waits for the workers.
func (p *Pool) Close() {
p.mu.Lock()
if !p.closed {
p.closed = true
close(p.jobs)
}
p.mu.Unlock()
p.wg.Wait()5
}- 1Submit holds the read side during its send, so Close cannot close the channel under it.
- 2The loop ends when the channel is closed and empty, so queued jobs still run.
- 3The caller stops waiting. A full queue must not hang a request.
- 4No room: fail now. The caller can answer 429 or 503.
- 5Close returns after the last job. A job must not call Submit on its own pool.
// unguardedPool closes jobs while Submit may still send on it.
type unguardedPool struct{ jobs chan func() }
func (p *unguardedPool) Submit(ctx context.Context, job func()) error {
select {
case p.jobs <- job:1 // panics when Close has run
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (p *unguardedPool) Close() { close(p.jobs) }- 1A send on a closed channel panics, and select does not help.
func TestSubmitAfterClose(t *testing.T) {
tests := []struct {
name string
pool submitter
wantPanic bool
}{
{"guarded pool", NewPool(1, 1), false},
{"the bug", &unguardedPool{jobs: make(chan func(), 1)}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.pool.Close()
defer func() {
if got := recover() != nil; got != tt.wantPanic {
t.Fatalf("panic = %v, want %v", got, tt.wantPanic)
}
}()
err := tt.pool.Submit(t.Context(), func() {})
if !tt.wantPanic && !errors.Is(err, ErrClosed) {
t.Fatalf("err = %v, want ErrClosed", err)
}
})
}
}A pool bounds work twice: workers bound concurrency, and the queue bounds backlog. Close stops new jobs and then drains the queue.
- Use it when each stage transforms a stream and stages run at different speeds.
- For a single loop over one list, do not use it. A plain function is shorter.
// Source sends 0 to n-1, then closes its channel.
func Source(ctx context.Context, n int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := range n {
select {
case out <- i:
case <-ctx.Done():
return
}
}
}()
return out
}
// Stage applies f to each value. It owns out and closes it on every exit.
func Stage[In, Out any]3(
ctx context.Context, in <-chan In, f func(In) Out,
) <-chan Out {
out := make(chan Out)
go func() {
defer close(out)1
for v := range in {
select {
case out <- f(v):2
case <-ctx.Done():
return
}
}
}()
return out
}- 1Closing flows downstream: each stage ends when its input ends.
- 2The send has a way out. Every stage needs this select.
- 3Generic stages compose: the output of one is the input of the next.
// stageNoCancel leaks when the consumer stops: the send has no way out.
func stageNoCancel[In, Out any](in <-chan In, f func(In) Out) <-chan Out {
out := make(chan Out)
go func() {
defer close(out)
for v := range in {
out <- f(v)1
}
}()
return out
}- 1If the consumer leaves, this send blocks forever.
func TestConsumerStopsEarly(t *testing.T) {
double := func(v int) int { return v * 2 }
correct := func(ctx context.Context, in <-chan int) <-chan int {
return Stage(ctx, in, double)
}
buggy := func(_ context.Context, in <-chan int) <-chan int {
return stageNoCancel(in, double)
}
tests := []struct {
name string
stage func(context.Context, <-chan int) <-chan int
leaks bool
}{
{"stage with cancel", correct, false},
{"the bug", buggy, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
n := leaked(t, func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
in := make(chan int, 2)
in <- 1
in <- 2
close(in)
<-tt.stage(ctx, in) // read one value, then leave
})
if (n > 0) != tt.leaks {
t.Fatalf("leaked %d goroutines, want leak = %v", n, tt.leaks)
}
})
}
}Each stage closes its output and selects on ctx.Done beside its send. A consumer that leaves cancels the context, and every stage exits.
- Use it when one stage is slow and its work can run in parallel. Many workers read one channel, which fans out. They share one output, which fans in.
- Order is lost. If order matters, tag each job with its index and sort, or write to a slice by index.
// Parallel fans out to n workers and fans their results in to one channel.
// The results arrive in any order.
func Parallel[In, Out any](
ctx context.Context, in <-chan In, n int, f func(In) Out,
) <-chan Out {
out := make(chan Out)
var wg sync.WaitGroup
for range n {
wg.Go(func() {
for v := range in1 {
select {
case out <- f(v):
case <-ctx.Done():
return
}
}
})
}
go func() {
wg.Wait()2
close(out)3
}()
return out
}- 1Workers compete for values. A channel gives each value to one reader.
- 2In its own goroutine, so the function returns and the caller can read.
- 3One closer, after every sender has finished.
// parallelWaitFirst waits for the workers before anyone reads.
func parallelWaitFirst[In, Out any](
in <-chan In, n int, f func(In) Out,
) <-chan Out {
out := make(chan Out)
var wg sync.WaitGroup
for range n {
wg.Go(func() {
for v := range in {
out <- f(v)
}
})
}
wg.Wait() // every worker blocks on its first send
close(out)
return out
}- 1This is the trap from panel A in a helper.
func TestParallelReturnsAtOnce(t *testing.T) {
identity := func(v int) int { return v }
correct := func(ctx context.Context, in <-chan int) <-chan int {
return Parallel(ctx, in, 4, identity)
}
buggy := func(_ context.Context, in <-chan int) <-chan int {
return parallelWaitFirst(in, 4, identity)
}
tests := []struct {
name string
parallel func(context.Context, <-chan int) <-chan int
leaks bool
}{
{"closer goroutine", correct, false},
{"the bug", buggy, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
n := leaked(t, func() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for range tt.parallel(ctx, Source(ctx, 10)) {
}
})
if (n > 0) != tt.leaks {
t.Fatalf("leaked %d goroutines, want leak = %v", n, tt.leaks)
}
})
}
}One goroutine waits for the workers and closes the output. It must be a separate goroutine, because the caller has to read.
- Use it for a known list of tasks where the first error stops the rest.
- errgroup comes from golang.org/x/sync. Go blocks at the limit, and TryGo reports false.
- A panic in a function crashes the program. The group does not carry it to Wait.
// ForEach runs fn on every item, at most limit at a time.
// The first error cancels the rest, and ForEach returns that error.
func ForEach[T any](
ctx context.Context, items []T, limit int,
fn func(context.Context, T) error,
) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(limit)1
for _, item := range items {
if ctx.Err() != nil2 {
break
}
g.Go(func() error { return fn(ctx, item)3 })
}
return g.Wait()4
}- 1Call it before the first Go. g.Go now blocks while limit functions run.
- 2Stop starting new work after the first failure.
- 3Pass the derived ctx, so that running tasks see the cancel.
- 4The derived ctx ends here too. Do not use it after this line.
// forEachUnbounded starts one goroutine per item, at any list length.
func forEachUnbounded[T any](
ctx context.Context, items []T, fn func(context.Context, T) error,
) error {
g, ctx := errgroup.WithContext(ctx)
for _, item := range items {
g.Go(func() error { return fn(ctx, item) })1
}
return g.Wait()
}- 1One goroutine per item. A list of 100,000 opens 100,000 connections.
func TestForEachPeak(t *testing.T) {
const limit = 4
items := make([]int, 100)
type work = func(context.Context, int) error
limited := func(ctx context.Context, in []int, fn work) error {
return ForEach(ctx, in, limit, fn)
}
tests := []struct {
name string
run func(context.Context, []int, work) error
maxPeak int64
}{
{"SetLimit", limited, limit},
{"the bug", forEachUnbounded[int], 100},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
var p peak
sleep := func(context.Context, int) error {
p.enter()
defer p.leave()
time.Sleep(time.Millisecond)
return nil
}
err := tt.run(t.Context(), items, sleep)
if err != nil || p.top.Load() != tt.maxPeak {
t.Fatalf("peak %d, want %d", p.top.Load(), tt.maxPeak)
}
})
})
}
}errgroup with SetLimit bounds the fan-out, cancels on the first error, and returns that error. It is my default inside a request.
- Use a buffered channel to limit callers of one dependency across code paths.
- Use semaphore.Weighted from golang.org/x/sync when each job has a different cost, such as bytes in memory.
- A weighted request above the total size blocks until its context ends.
// Sem is a counting semaphore: a channel with one slot per permit.
type Sem chan struct{}1
// Acquire waits for a permit or for ctx to end.
func (s Sem) Acquire(ctx context.Context) error {
select {
case s <- struct{}{}:
return nil
case <-ctx.Done():
return context.Cause(ctx)
}
}
// Release returns a permit.
func (s Sem) Release() { <-s }
// RunBudget runs work on each size. The sizes in flight stay within budget.
func RunBudget(
ctx context.Context, budget int64, sizes []int64, work func(int64),
) error {
sem := semaphore.NewWeighted(budget)
var wg sync.WaitGroup
defer wg.Wait()4
for _, size := range sizes {
if err := sem.Acquire(ctx, size)2; err != nil {
return err
}
wg.Go(func() {
defer sem.Release(size)3
work(size)
})
}
return nil
}- 1Capacity is the permit count. A send acquires, and a receive releases.
- 2Before the go statement: the loop itself waits, and goroutines stay bounded.
- 3Release exactly what was acquired, also on a panic.
- 4An early return on a cancelled ctx still waits for running work.
// runSemInside takes the permit inside the goroutine.
// The work is bounded; the goroutines are not.
func runSemInside[T any](
ctx context.Context, sem Sem, items []T, work func(T),
) {
var wg sync.WaitGroup
for _, item := range items {
wg.Go(func() {1
if sem.Acquire(ctx) != nil {
return
}
defer sem.Release()
work(item)
})
}
wg.Wait()
}- 1Starts now, for every item. The goroutines wait in memory for a permit.
func TestSemaphoreBoundsGoroutines(t *testing.T) {
const permits, items = 4, 1000
first := func(ctx context.Context, s Sem, in []int, w func(int)) {
_ = RunSem(ctx, s, in, w)
}
tests := []struct {
name string
run func(context.Context, Sem, []int, func(int))
bounded bool
}{
{"acquire first", first, true},
{"the bug", runSemInside[int], false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
base := runtime.NumGoroutine()
release := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
in := make([]int, items)
wait := func(int) { <-release }
tt.run(t.Context(), make(Sem, permits), in, wait)
}()
synctest.Wait() // every goroutine in the test now waits
parked := runtime.NumGoroutine() - base
close(release)
<-done
if got := parked <= 2*permits; got != tt.bounded {
t.Fatalf("%d parked, want bounded = %v", parked, tt.bounded)
}
})
})
}
}A semaphore bounds work across code paths. I acquire before I start the goroutine, so goroutines are bounded too.
- Use it when many callers miss on one key at once. They share one load instead of a stampede.
- It is not a cache: it only joins calls that overlap. Put it in front of a real load, behind a cache.
- singleflight comes from golang.org/x/sync. Each result is shared, so callers must not change it.
// Loader makes concurrent callers of one key share a single load.
type Loader struct {
group singleflight.Group
load func(context.Context, string) (string, error)
timeout time.Duration
}
// NewLoader returns a Loader. Each shared load runs for at most timeout.
func NewLoader(
timeout time.Duration,
load func(context.Context, string) (string, error),
) *Loader {
return &Loader{load: load, timeout: timeout}
}
// Get returns the value. Each caller stops waiting when its own ctx ends.
func (l *Loader) Get(ctx context.Context, key string) (string, error) {
ch := l.group.DoChan1(key, func() (any, error) {
detached := context.WithoutCancel(ctx)2
shared, cancel := context.WithTimeout(detached, l.timeout3)
defer cancel()
return l.load(shared, key)
})
select {
case r := <-ch:
if r.Err != nil {
return "", r.Err
}
return r.Val.(string), nil
case <-ctx.Done():4
return "", context.Cause(ctx)
}
}- 1DoChan returns a channel, so each caller can also watch its own ctx. Do cannot.
- 2The load keeps the values and survives any one caller. Go 1.21.
- 3WithoutCancel also drops the deadline, so the load needs its own.
- 4This caller leaves. The load goes on for the others.
// leaderContextLoader runs the load under the first caller's context.
type leaderContextLoader struct {
group singleflight.Group
load func(context.Context, string) (string, error)
}
func (l *leaderContextLoader) Get(
ctx context.Context, key string,
) (string, error) {
v, err, _ := l.group.Do(key, func() (any, error) {
return l.load(ctx, key)1 // cancels every waiter with the first caller
})
if err != nil {
return "", err
}
return v.(string), nil
}- 1Every waiter now depends on one caller's context.
func TestLeaderCancelSparesFollowers(t *testing.T) {
load := func(ctx context.Context, _ string) (string, error) {
select {
case <-time.After(10 * time.Millisecond):
return "value", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
tests := []struct {
name string
loader getter
wantErr bool
}{
{"shared context", NewLoader(time.Second, load), false},
{"the bug", &leaderContextLoader{load: load}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
leader, cancel := context.WithCancel(t.Context())
go func() { _, _ = tt.loader.Get(leader, "k") }()
synctest.Wait()
follower := make(chan error, 1)
go func() {
_, err := tt.loader.Get(t.Context(), "k")
follower <- err
}()
synctest.Wait()
cancel() // the first caller gives up
if err := <-follower; (err != nil) != tt.wantErr {
t.Fatalf("follower err = %v, want error = %v", err, tt.wantErr)
}
})
})
}
}singleflight joins concurrent loads of one key. I detach the load from the first caller's context and give it its own timeout.
- Use Allow to reject requests on a server. Use Wait in a client that must fit a quota.
- rate.Limiter is a token bucket from golang.org/x/time. It is safe for concurrent use.
- One process limits its own traffic only. For a limit across servers, see B3 Rate limiting.
// Limiters keeps one token bucket per client.
type Limiters struct {
mu sync.Mutex
clients map[string]*client
rate rate.Limit
burst int
}
type client struct {
limiter *rate.Limiter
seen time.Time
}
// NewLimiters allows r requests a second, with bursts up to burst.
func NewLimiters(r rate.Limit, burst int) *Limiters {
clients := make(map[string]*client)
return &Limiters{clients: clients, rate: r, burst: burst}
}
// Allow spends one token from key's bucket, or reports false.
func (l *Limiters) Allow(key string) bool {
l.mu.Lock()
defer l.mu.Unlock()
c, ok := l.clients[key]
if !ok {
c = &client{limiter: rate.NewLimiter(l.rate, l.burst)1}
l.clients[key] = c
}
c.seen = time.Now()
return c.limiter.Allow()2
}
// Sweep forgets idle clients. Without it the map only grows.
func (l *Limiters) Sweep3(idle time.Duration) {
l.mu.Lock()
defer l.mu.Unlock()
for key, c := range l.clients {
if time.Since(c.seen) > idle {
delete(l.clients, key)
}
}
}
// Pace calls fn once per item at the limiter's rate. Use it for a caller
// that must fit a quota. Use Allow for a server that rejects extra requests.
func Pace[T any](
ctx context.Context, lim *rate.Limiter, items []T, fn func(T),
) error {
for _, item := range items {
if err := lim.Wait(ctx)4; err != nil {
return fmt.Errorf("pace: %w", err)
}
fn(item)
}
return nil
}- 1r tokens a second, up to burst. A new bucket starts full.
- 2Takes a token, or reports false at once.
- 3Run it from a ticker. Each client ID is a map entry, and clients are unbounded.
- 4Blocks for the next token. It fails at once if the token comes after the deadline.
// allowFresh builds a new, full bucket per call, so every request passes.
func allowFresh(r rate.Limit, burst int) bool {
return rate.NewLimiter(r, burst).Allow()1
}- 1A limiter holds state. A new one has a full bucket, so it allows every call.
func TestBurstIsLimited(t *testing.T) {
limiters := NewLimiters(10, 5)
tests := []struct {
name string
allow func() bool
want int
}{
{"per client", func() bool { return limiters.Allow("c") }, 5},
{"the bug", func() bool { return allowFresh(10, 5) }, 100},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
passed := 0
for range 100 {
if tt.allow() {
passed++
}
}
if passed != tt.want {
t.Fatalf("passed %d of 100, want %d", passed, tt.want)
}
})
}
}I keep one token bucket per client in a map, and I sweep idle clients. The rate sets the long-run limit, and the burst sets the peak.
- Use it to fan one event out to many readers in a process: live updates, cache invalidation.
- Decide what a slow subscriber costs. This bus drops values for it. For no loss, use a real queue.
// Bus sends each value to every subscriber.
type Bus[T any] struct {
mu sync.RWMutex
subs map[chan T]struct{}
}
// NewBus returns an empty bus.
func NewBus[T any]() *Bus[T] {
return &Bus[T]{subs: make(map[chan T]struct{})}
}
// Subscribe returns a channel and a function that cancels and closes it.
func (b *Bus[T]) Subscribe(buffer int) (<-chan T, func()) {
ch := make(chan T, buffer)
b.mu.Lock()
b.subs[ch] = struct{}{}
b.mu.Unlock()
cancel := sync.OnceFunc2(func() {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.subs, ch)
close(ch)1
})
return ch, cancel
}
// Publish never waits. A subscriber with a full buffer misses the value.
func (b *Bus[T]) Publish(v T) (dropped int) {
b.mu.RLock()
defer b.mu.RUnlock()
for ch := range b.subs {
select {
case ch <- v:
default:3
dropped++4
}
}
return dropped
}- 1Under the write lock, so no Publish is mid-send. This cannot panic.
- 2A second cancel must not close the channel twice. Go 1.21.
- 3A full buffer drops the value. The publisher does not wait.
- 4Export this as a metric. Silent drops hide a slow reader.
// blockingBus has no way out: one slow subscriber stops every publish.
type blockingBus[T any] struct{ Bus[T] }
func (b *blockingBus[T]) Publish(v T) int {
b.mu.RLock()
defer b.mu.RUnlock()
for ch := range b.subs {
ch <- v1
}
return 0
}- 1One full buffer blocks here, under the read lock. Subscribe and cancel then wait too.
func TestSlowSubscriberDoesNotStopPublish(t *testing.T) {
tests := []struct {
name string
bus func() publisher
stuck bool
}{
{"drop on full", func() publisher { return NewBus[int]() }, false},
{"the bug", func() publisher {
subs := make(map[chan int]struct{})
return &blockingBus[int]{Bus[int]{subs: subs}}
}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
bus := tt.bus()
slow, cancel := bus.Subscribe(1)
published := make(chan struct{})
go func() {
for v := range 3 {
bus.Publish(v)
}
close(published)
}()
select {
case <-published:
if tt.stuck {
t.Fatal("the check missed the bug")
}
case <-time.After(time.Second):
if !tt.stuck {
t.Fatal("Publish waited for a slow subscriber")
}
for range 3 { // let the stuck publisher finish
<-slow
}
<-published
}
cancel()
})
})
}
}Publish never blocks. Each subscriber has a buffer, and a full buffer drops the value and counts it.
- Use one when each key needs its own writer and keys are not known in advance.
- If the entry already exists, put a mutex in the entry. It is simpler.
- A striped lock has fixed memory, and two keys can share a stripe.
// KeyedMutex gives each key a lock and keeps entries only while in use.
type KeyedMutex struct {
mu sync.Mutex
locks map[string]*keyLock
}
type keyLock struct {
mu sync.Mutex
refs int // holders and waiters; guarded by KeyedMutex.mu
}
// NewKeyedMutex returns an empty KeyedMutex.
func NewKeyedMutex() *KeyedMutex {
return &KeyedMutex{locks: make(map[string]*keyLock)}
}
// Lock waits for key and returns the function that unlocks it.
func (k *KeyedMutex) Lock(key string) (unlock func()) {
k.mu.Lock()
l, ok := k.locks[key]
if !ok {
l = &keyLock{}
k.locks[key] = l
}
l.refs++1
k.mu.Unlock()
l.mu.Lock()2
return func() {
l.mu.Unlock()
k.mu.Lock()
defer k.mu.Unlock()
l.refs--
if l.refs == 03 {
delete(k.locks, key)
}
}
}
// Len returns how many keys are in use.
func (k *KeyedMutex) Len() int {
k.mu.Lock()
defer k.mu.Unlock()
return len(k.locks)
}
// Striped maps every key to one of a fixed set of locks.
// Two keys can share a stripe.
type Striped struct {
seed maphash.Seed
locks [64]sync.Mutex
}
// NewStriped returns a Striped with a random seed.
func NewStriped() *Striped { return &Striped{seed: maphash.MakeSeed()} }
// For returns the lock for key.
func (s *Striped) For(key string) *sync.Mutex {
return &s.locks[maphash.String(s.seed, key)4%uint64(len(s.locks))]
}- 1Count before waiting. The count includes waiters, so the entry cannot vanish under them.
- 2Release the map lock first. Waiting on a key while holding it would block every other key.
- 3Delete the entry with the last user. The map holds only keys in use.
- 4Two keys can land on one stripe. To lock both, order by stripe, not by key.
// unsafeKeyed deletes the entry on unlock, even with a waiter on that mutex.
// The next caller makes a new mutex, and two goroutines hold one key.
type unsafeKeyed struct {
mu sync.Mutex
locks map[string]*sync.Mutex
}
func (k *unsafeKeyed) Lock(key string) func() {
k.mu.Lock()
l, ok := k.locks[key]
if !ok {
l = &sync.Mutex{}
k.locks[key] = l
}
k.mu.Unlock()
l.Lock()
return func() {
k.mu.Lock()
delete(k.locks, key)1
k.mu.Unlock()
l.Unlock()
}
}- 1A waiter still holds this mutex. The next caller makes a new one and enters too.
func TestOneHolderPerKey(t *testing.T) {
tests := []struct {
name string
k locker
bug bool
}{
{"reference count", NewKeyedMutex(), false},
{"the bug", &unsafeKeyed{locks: make(map[string]*sync.Mutex)}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var p peak
var wg sync.WaitGroup
for range 32 {
wg.Go(func() {
for range 2000 {
unlock := tt.k.Lock("key")
p.enter()
runtime.Gosched()
p.leave()
unlock()
}
})
}
wg.Wait()
if got := p.top.Load() > 1; got != tt.bug {
t.Fatalf("peak holders = %d, want bug = %v", p.top.Load(), tt.bug)
}
})
}
}Each key gets a mutex with a reference count, so an entry stays until no one holds or waits for it. A striped lock is the fixed-memory option.
- Retry only what can succeed later, with a deadline per try and a deadline overall.
- Add jitter, so that clients that failed together do not retry together.
- Retry a write only when it is idempotent.
// ErrTemporary marks a failure that a retry can fix.
var ErrTemporary = errors.New("temporary failure")
// Retry says how often to try and how long each try may take.
type Retry struct {
Attempts int
Base time.Duration // the backoff before the second try
PerTry time.Duration // the deadline of one try
}
// Do calls fn until it succeeds, fails for good, or ctx ends.
func (r Retry) Do(ctx context.Context, fn func(context.Context) error) error {
var err error
for attempt := range r.Attempts {
tryCtx, cancel := context.WithTimeout(ctx, r.PerTry)1
err = fn(tryCtx)
cancel()2
if err == nil || !retryable(ctx, err) {
return err
}
if attempt == r.Attempts-1 {
break
}
backoff := time.NewTimer(rand.N(r.Base<<attempt)3 + 1) // full jitter
select {
case <-backoff.C:
case <-ctx.Done():4
backoff.Stop()
return fmt.Errorf("retry: %w", context.Cause(ctx))
}
}
return fmt.Errorf("gave up after %d tries: %w", r.Attempts, err)
}
// retryable is true for a temporary failure or a try that ran out of time.
// When ctx itself has ended, no retry can help.
func retryable(ctx context.Context, err error) bool {
if ctx.Err() != nil {
return false
}
return errors.Is(err, ErrTemporary) ||
errors.Is(err, context.DeadlineExceeded)
}- 1One hung try cannot use the whole budget.
- 2Not defer: a defer in a loop runs at function end and keeps every timer until then.
- 3Full jitter: a random wait up to the doubling ceiling. The generic rand.N takes a Duration.
- 4The caller left, so stop now.
// retrySleep waits with time.Sleep, which a cancel cannot interrupt.
func retrySleep(
ctx context.Context, r Retry, fn func(context.Context) error,
) error {
var err error
for attempt := range r.Attempts {
if err = fn(ctx); err == nil {
return nil
}
time.Sleep(rand.N(r.Base<<attempt) + 1)1
}
return fmt.Errorf("gave up: %w", err)
}- 1A cancel cannot interrupt a sleep. A shutdown now waits for the longest backoff.
func TestCancelStopsBackoff(t *testing.T) {
r := Retry{Attempts: 5, Base: time.Minute, PerTry: time.Second}
fail := func(context.Context) error { return ErrTemporary }
selects := func(ctx context.Context) error { return r.Do(ctx, fail) }
sleeps := func(ctx context.Context) error { return retrySleep(ctx, r, fail) }
tests := []struct {
name string
do func(context.Context) error
fast bool
}{
{"timer and select", selects, true},
{"the bug", sleeps, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond)
defer cancel()
start := time.Now()
_ = tt.do(ctx)
if got := time.Since(start) <= time.Millisecond; got != tt.fast {
t.Fatalf("took %v after a 1ms deadline", time.Since(start))
}
})
})
}
}Each try has its own deadline inside the caller's. I back off with full jitter in a select, so a cancel stops the wait at once.
- Stop in dependency order: first the listener, then the handlers, then the pool, then the store.
- Use the grace period of your platform. The process must exit before the orchestrator kills it.
// Serve runs srv until ctx ends. Then it stops in dependency order:
// first the server that feeds the pool, then the pool.
func Serve(
ctx context.Context, srv *http.Server, ln net.Listener,
pool *Pool, grace time.Duration,
) error {
serveErr := make(chan error, 1)
go func() { serveErr <- srv.Serve(ln) }()
select {
case err := <-serveErr:
pool.Close()
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
stop, cancel := context.WithTimeout(context.WithoutCancel(ctx)1, grace)
defer cancel()
err := srv.Shutdown(stop)2 // stop accepting; wait for in-flight requests
pool.Close() // no handler can submit now; run the queue
if serr := <-serveErr; !errors.Is(serr, http.ErrServerClosed)4 {
err = errors.Join(err, serr)
}
return err
}
// ServeUntilSignal is the body of main: SIGINT or SIGTERM starts the stop.
func ServeUntilSignal(
srv *http.Server, ln net.Listener, pool *Pool, grace time.Duration,
) error {
ctx, stop := signal.NotifyContext5(
context.Background(), syscall.SIGINT, syscall.SIGTERM,
)
defer stop()
return Serve(ctx, srv, ln, pool, grace)
}- 1ctx has already ended. Shutdown needs a live context with its own deadline.
- 2Closes the listeners, then waits for active requests. It does not cancel them.
- 3Only now can no handler submit. The queued jobs still run.
- 4Serve always returns this error after Shutdown. It is the normal result.
- 5Since Go 1.26, context.Cause says which signal arrived.
// serveWrongOrder closes the pool under the handlers still in flight.
func serveWrongOrder(
ctx context.Context, srv *http.Server, ln net.Listener,
pool *Pool, grace time.Duration,
) error {
serveErr := make(chan error, 1)
go func() { serveErr <- srv.Serve(ln) }()
<-ctx.Done()
pool.Close() // in-flight handlers now get ErrClosed
stop, cancel := context.WithTimeout(context.WithoutCancel(ctx), grace)
defer cancel()
err := srv.Shutdown(stop)
if serr := <-serveErr; !errors.Is(serr, http.ErrServerClosed) {
err = errors.Join(err, serr)
}
return err
}- 1The request is accepted and in flight, and it then loses its pool.
func TestInFlightRequestFinishes(t *testing.T) {
tests := []struct {
name string
serve serveFunc
want int
}{
{"server first, then pool", Serve, http.StatusOK},
{"the bug", serveWrongOrder, http.StatusServiceUnavailable},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pool := NewPool(1, 1)
arrived, release := make(chan struct{}), make(chan struct{})
handler := func(w http.ResponseWriter, r *http.Request) {
close(arrived)
<-release // the request is in flight during the shutdown
if err := pool.Submit(r.Context(), func() {}); err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
}
}
srv := &http.Server{Handler: http.HandlerFunc(handler)}
ln := listen(t)
ctx, cancel := context.WithCancel(t.Context())
served := make(chan error, 1)
go func() { served <- tt.serve(ctx, srv, ln, pool, 5*time.Second) }()
status := make(chan int, 1)
go func() { status <- get(t, ln.Addr().String()) }()
<-arrived
cancel()
time.Sleep(20 * time.Millisecond) // Serve is now stopping
close(release)
if got := <-status; got != tt.want {
t.Fatalf("status = %d, want %d", got, tt.want)
}
if err := <-served; err != nil {
t.Fatalf("serve: %v", err)
}
})
}
}On SIGTERM I stop accepting, wait for in-flight requests, close the pool and let it drain, all within a grace period.
- This is the shape of the 45-minute build: a map, safe under concurrent requests, with slow side work on a pool.
- Write the Store first, with one mutex, if the time is short. Replace it with per-key locks if a slow update is in the prompt.
// Store is the shape of the 45-minute build: an in-memory map, safe under
// concurrent requests.
type Store struct {
keys *KeyedMutex1 // one writer per key; a slow update blocks only its key
mu sync.RWMutex2 // guards the map itself, for one read or one write
data map[string]int64
}
// NewStore returns an empty store.
func NewStore() *Store {
return &Store{keys: NewKeyedMutex(), data: make(map[string]int64)}
}
// Get returns the value for key.
func (s *Store) Get(key string) int64 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.data[key]
}
func (s *Store) set(key string, v int64) {
s.mu.Lock()
defer s.mu.Unlock()
s.data[key] = v
}
// Update reads, changes and writes one key. Only this key waits for fn.
func (s *Store) Update(key string, fn func(int64) (int64, error)) error {
defer s.keys.Lock(key)()3
next, err := fn(s.Get(key))
if err != nil {
return err
}
s.set(key, next)
return nil
}
// Transfer moves amount between two keys. It locks them in sorted order.
func (s *Store) Transfer(from, to string, amount int64) error {
if from == to {
return nil
}
first, second := from, to
if second < first4 {
first, second = second, first
}
defer s.keys.Lock(first)()
defer s.keys.Lock(second)()
balance := s.Get(from)
if balance < amount {
return ErrInsufficient
}
s.set(from, balance-amount)
s.set(to, s.Get(to)+amount)
return nil
}
// Event says that a key changed.
type Event struct {
Key string
Value int64
}
// Service puts a store and a worker pool behind one request method.
type Service struct {
store *Store
pool *Pool
notify func(Event)
}
// NewService returns a Service. notify runs on the pool.
func NewService(store *Store, pool *Pool, notify func(Event)) *Service {
return &Service{store: store, pool: pool, notify: notify}
}
// Deposit adds amount to key. It queues a notification after the key lock
// is released.
func (s *Service) Deposit(
ctx context.Context, key string, amount int64,
) error {
var value int64
err := s.store.Update(key, func(old int64) (int64, error) {
value = old + amount
return value, nil
})
if err != nil {
return fmt.Errorf("deposit: %w", err)
}
err = s.pool.Submit(ctx,5 func() { s.notify(Event{key, value}) })
if errors.Is(err, ErrClosed) {
return nil // the deposit stands; the notification is best effort
}
return err
}- 1Serializes writers of one key across their whole update.
- 2Protects the map for one operation. Never hold it across fn.
- 3The call takes the lock now. The deferred function unlocks at return.
- 4A global order on keys prevents the deadlock between opposite transfers.
- 5After Update returns, so the key lock is free while the job waits.
// globalLockUpdate holds one lock across fn: a slow update stalls every key.
func (s *Store) globalLockUpdate(
key string, fn func(int64) (int64, error),
) error {
s.mu.Lock()
defer s.mu.Unlock()
next, err := fn(s.data[key])1
if err != nil {
return err
}
s.data[key] = next
return nil
}
// transferUnsorted locks in argument order: opposite transfers deadlock.
func (s *Store) transferUnsorted(from, to string, amount int64) error {
defer s.keys.Lock(from)()2
defer s.keys.Lock(to)()
balance := s.Get(from)
if balance < amount {
return ErrInsufficient
}
s.set(from, balance-amount)
s.set(to, s.Get(to)+amount)
return nil
}- 1fn may be slow. It runs under the one lock of the whole store.
- 2A to B and B to A each take their first lock, then wait forever for the second.
func TestSlowUpdateBlocksOnlyItsKey(t *testing.T) {
tests := []struct {
name string
update func(*Store, string, func(int64) (int64, error)) error
wantOK bool
}{
{"per-key lock", (*Store).Update, true},
{"the bug", (*Store).globalLockUpdate, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := NewStore()
inside, release := make(chan struct{}), make(chan struct{})
slow := make(chan error, 1)
go func() {
slow <- tt.update(s, "slow", func(v int64) (int64, error) {
close(inside)
<-release
return v, nil
})
}()
<-inside
inc := func(v int64) (int64, error) { return v + 1, nil }
other := make(chan error, 1)
go func() { other <- tt.update(s, "other", inc) }()
select {
case <-other:
if !tt.wantOK {
t.Fatal("the check missed the bug")
}
close(release)
case <-time.After(100 * time.Millisecond):
if tt.wantOK {
t.Fatal("key other waited for key slow")
}
close(release)
<-other
}
<-slow
})
}
}
func TestOppositeTransfers(t *testing.T) {
tests := []struct {
name string
transfer func(s *Store, from, to string, n int64) error
deadlock bool
}{
{"sorted order", (*Store).Transfer, false},
{"the bug", (*Store).transferUnsorted, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := NewStore()
s.set("a", 1<<40)
s.set("b", 1<<40)
stop := time.Now().Add(200 * time.Millisecond)
var wg sync.WaitGroup
for _, pair := range [][2]string{{"a", "b"}, {"b", "a"}} {
wg.Go(func() {
for time.Now().Before(stop) {
_ = tt.transfer(s, pair[0], pair[1], 1)
}
})
}
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
select {
case <-done:
if tt.deadlock {
t.Fatal("the check missed the deadlock")
}
case <-time.After(2 * time.Second):
if !tt.deadlock {
t.Fatal("deadlock")
}
}
})
}
}One short lock guards the map. One lock per key guards each read-modify-write. Slow side work leaves the request path through a pool.
| workers | offered / s | finished / s | shed | p50 | p99 |
|---|---|---|---|---|---|
| 8 | 30,000 | 12,631 | 57.4% | 10.5 ms | 12.7 ms |
CPU work stops scaling near the 8 physical cores. Workers past that add almost no throughput. They share the cores, so the slowest jobs take longer.
Queue of 128 jobs. Jobs that find it full are shed. GOMAXPROCS 16 on an 8-core laptop, on a busy machine. Latency runs from arrival to the end of the job.
I size a pool from the work: cores for CPU, rate times latency for waiting. Past the limit of the backend, more workers only add latency.
| since | what changed | where it appears here |
|---|---|---|
| 1.21 | context.WithoutCancel, sync.OnceFunc. | The shared load in panel J, the shutdown in panel O, the bus in panel L. |
| 1.22 | Each loop iteration creates new variables. math/rand/v2 with the generic rand.N. | Closures in g.Go capture item with no copy. The backoff in panel N. |
| 1.23 | Timer channels are unbuffered. Unreferenced timers are collected without Stop. | Stop and Reset leave no stale tick behind. |
| 1.25 | sync.WaitGroup.Go. testing/synctest. | Every wg in this sheet. Every time-based test in this sheet. |
| 1.26 | signal.NotifyContext cancels with a cause that names the signal. | The shutdown in panel O. |
| 1.27 | goroutineleak profile is generally available. synctest.Sleep. httptest.NewTestServer gives a fake network for a bubble. | The leak check in panel D. |
errgroup, singleflight and semaphore come from golang.org/x/sync, and rate comes from golang.org/x/time. Tested with x/sync v0.24.0 and x/time v0.16.0.
| pattern | in the 45-minute build | in the talk |
|---|---|---|
| Per-key locks | "Two requests update one record." Add one lock per key around read, change, write. | How does the lock map shrink? What about two keys at once? What changes with two instances? |
| Worker pool | "Send a webhook after the write." Use a small pool with a bounded queue. Do not call out from the request. | What happens when the queue fills? What if the process dies with jobs in the queue? Move to a durable queue. |
| Graceful shutdown | Add it last, if time remains: 15 lines from panel O. | Give the stop order, the grace period, and what happens to queued jobs. |
| Timeouts and retries | Pass r.Context() down. Add one deadline around each outbound call. | Which errors can you retry? Is the call idempotent? Add jitter and a retry budget. |
| Rate limiting | Only if asked. A map of rate.Limiter per client, behind a mutex. | One instance or many? See B3 Rate limiting for a shared limit. |
| singleflight | Add it when the prompt has a cache and a slow load. | Explain the stampede. Add a stale value and a per-key timeout. |
| errgroup | A request calls several backends: use errgroup with a limit. | Partial failure: fail the request, or return what you have? |
| Semaphore | One outbound dependency with a known connection limit. | A semaphore in each instance adds up: divide the limit by the instance count. |
| Pipeline, fan-out | Rarely in this round. A loop or a pool is shorter. | A stream import: stages, backpressure, cancellation. |
| Pub/sub | A live feed endpoint: one buffered channel per connection. | A slow client: drop, or disconnect? Move to a broker for many instances. |
In the build I write the smallest safe version. In the talk I name the next bound and the test that would prove it.
0 of 11 known
Predict the output. No function failed.
package main import ( "context" "fmt" "golang.org/x/sync/errgroup" ) func main() { g, ctx := errgroup.WithContext(context.Background()) g.Go(func() error { return nil }) fmt.Println(g.Wait()) fmt.Println(ctx.Err()) }Predict the output.
package main import ( "context" "errors" "fmt" "golang.org/x/sync/errgroup" ) func main() { g, ctx := errgroup.WithContext(context.Background()) g.Go(func() error { <-ctx.Done() return errors.New("second") }) g.Go(func() error { return errors.New("first") }) fmt.Println(g.Wait()) }Predict the output.
package main import ( "fmt" "golang.org/x/sync/errgroup" ) func main() { var g errgroup.Group g.SetLimit(1) release := make(chan struct{}) block := func() error { <-release return nil } fmt.Println(g.TryGo(block)) fmt.Println(g.TryGo(block)) close(release) fmt.Println(g.Wait()) fmt.Println(g.TryGo(block)) }Predict the output.
package main import ( "fmt" "golang.org/x/sync/singleflight" ) func main() { var g singleflight.Group calls := 0 load := func() (any, error) { calls++ return "value", nil } _, _, shared1 := g.Do("k", load) _, _, shared2 := g.Do("k", load) fmt.Println(calls, shared1, shared2) }Predict the output. All 10 goroutines arrive inside the 50 ms load.
package main import ( "fmt" "sync" "sync/atomic" "time" "golang.org/x/sync/singleflight" ) func main() { var g singleflight.Group var calls atomic.Int64 load := func() (any, error) { calls.Add(1) time.Sleep(50 * time.Millisecond) return "value", nil } var wg sync.WaitGroup var shared atomic.Int64 for range 10 { wg.Go(func() { if _, _, s := g.Do("k", load); s { shared.Add(1) } }) } wg.Wait() fmt.Println(calls.Load(), shared.Load()) }Predict the output. The first limiter allows 1 a second with a burst of 3.
package main import ( "fmt" "golang.org/x/time/rate" ) func main() { lim := rate.NewLimiter(1, 3) for range 5 { fmt.Print(lim.Allow(), " ") } fmt.Println() none := rate.NewLimiter(1000, 0) fmt.Println(none.Allow()) }Predict the output.
package main import ( "context" "fmt" "time" "golang.org/x/time/rate" ) func main() { lim := rate.NewLimiter(1, 3) ctx := context.Background() fmt.Println(lim.WaitN(ctx, 5)) lim = rate.NewLimiter(1, 1) fmt.Println(lim.Wait(ctx)) short, cancel := context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() fmt.Println(lim.Wait(short)) }Predict the output. The first Acquire asks for more than the size.
package main import ( "context" "fmt" "time" "golang.org/x/sync/semaphore" ) func main() { sem := semaphore.NewWeighted(10) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() fmt.Println(sem.Acquire(ctx, 11)) fmt.Println(sem.TryAcquire(10)) }Predict the output.
package main import "fmt" func main() { sem := make(chan struct{}) sem <- struct{}{} fmt.Println("acquired") <-sem }Predict the output. Shutdown runs before Serve.
package main import ( "context" "errors" "fmt" "net" "net/http" ) func main() { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } srv := &http.Server{} fmt.Println(srv.Shutdown(context.Background())) err = srv.Serve(ln) fmt.Println(err, errors.Is(err, http.ErrServerClosed)) }Predict the output. Each worker closes the channel when it ends.
package main import ( "fmt" "sync" ) func main() { out := make(chan int) var wg sync.WaitGroup for range 2 { wg.Go(func() { defer close(out) }) } wg.Wait() fmt.Println("done") }
- CPU work
- 1,957 jobs a second on 1 worker, 12,631 on 8, 11,336 on 256.
- CPU p99
- 12.7 ms on 8 workers, 372.3 ms on 256.
- waiting work
- 2,000 a second × 10 ms = 20 workers. 16 workers finish 1,577 a second; 32 finish 1,979.
- a limit
- 16 connections ÷ 10 ms = 1,600 a second. 256 workers finish 1,548.
- past the limit
- p99 94.2 ms on 16 workers, 266.7 ms on 256.
Little's law: busy workers = arrival rate × time per job. Use these as orders of magnitude.