Concurrency Patterns
- Implement worker pools, pipelines and fan-out/fan-in that terminate cleanly on completion, error and cancellation.
- Bound concurrency and request rates to protect downstream systems (PSPs, core banking, databases).
- Collapse duplicate concurrent work with
singleflightand handle its context pitfalls. - Build an in-process pub/sub with an explicit slow-consumer policy.
- Shut down a service gracefully in Kubernetes without dropping in-flight payments.
TL;DR
- Every pattern needs three exits: input exhausted, error, cancellation. If you can't point to all three, it leaks.
- Worker pool = N goroutines ranging over a jobs channel; one closer goroutine closes results after
wg.Wait(). - Pipelines chain stages with channels; build them on
errgroup.WithContextso the first error cancels every stage. - Bounded parallelism:
errgroup.SetLimit(n)is the simplest correct tool. Sizenfrom the downstream's limits, not from your CPU count. - Rate limiting:
rate.NewLimiter(r, burst);Wait(ctx)for outbound smoothing,Allow()for inbound rejection (429). - singleflight collapses concurrent identical requests (cache stampede). Detach the shared work from any single caller's context.
- Graceful shutdown: fail readiness → stop accepting → drain HTTP → stop consumers and commit → flush → close pools — all within the pod's termination grace period.
Why it matters
Concurrency patterns are where Go services either shine or fall over at peak:
- End-of-day settlement: 3,000 merchants must be settled in a 30-minute window, but the bank's API allows 16 parallel sessions and 100 requests/s.
- Flash sale: 50k users hit the same product page; without stampede protection, the cache expiry sends 50k identical queries to PostgreSQL.
- Reconciliation import: a 2 GB file must be parsed, validated and inserted with bounded memory, and a bad row must stop the whole import cleanly.
- Deploys: rolling deploys during business hours must not cut off a card authorization mid-flight.
Core concepts
Worker pool
A fixed number of workers consume jobs; results are funnelled into one channel.
package pool
import (
"context"
"sync"
)
type Job struct{ PaymentID string }
type Result struct {
PaymentID string
Err error
}
// Run starts n workers. It returns a results channel that is closed when
// jobs is drained (and closed by the producer) or ctx is canceled.
func Run(ctx context.Context, n int, jobs <-chan Job,
handle func(context.Context, Job) error) <-chan Result {
results := make(chan Result)
var wg sync.WaitGroup
for range n {
wg.Go(func() {
for {
select {
case <-ctx.Done():
return
case j, ok := <-jobs:
if !ok {
return // input exhausted
}
r := Result{PaymentID: j.PaymentID, Err: handle(ctx, j)}
select {
case results <- r:
case <-ctx.Done():
return
}
}
}
})
}
go func() {
wg.Wait()
close(results) // single closer, after all senders exit
}()
return results
}
Design notes:
- Results arrive out of order. If order matters (statement lines), carry an index and reorder, or don't parallelise.
- Pool size comes from the bottleneck: DB pool size, downstream concurrency limit, or CPU count for CPU-bound work.
- For "run these N things with at most K at a time",
errgroup.SetLimit(below) is less code than a hand-rolled pool. Pools shine for long-lived consumers of a stream.
Pipelines and fan-out/fan-in
A pipeline is a series of stages connected by channels; each stage owns (and closes) its output channel. Fan-out runs several goroutines reading the same input channel; fan-in merges several channels into one.
Using errgroup makes error handling and cancellation uniform:
func ImportSettlement(ctx context.Context, r io.Reader, repo EntryRepo) error {
g, ctx := errgroup.WithContext(ctx)
rows := make(chan Row, 256)
entries := make(chan Entry, 256)
// Stage 1: parse. Reading a stream is sequential, so one goroutine.
g.Go(func() error {
defer close(rows)
return parseCSV(ctx, r, rows) // must select on ctx.Done() when sending
})
// Stage 2: validate and map, fanned out to 4 workers.
var mappers sync.WaitGroup
for range 4 {
mappers.Add(1)
g.Go(func() error {
defer mappers.Done()
for row := range rows {
e, err := toEntry(row)
if err != nil {
return fmt.Errorf("line %d: %w", row.Line, err) // cancels everyone
}
select {
case entries <- e:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
})
}
g.Go(func() error { // closer for the fan-in channel
mappers.Wait()
close(entries)
return nil
})
// Stage 3: fan-in and batch. InsertBatch must not retain the slice.
g.Go(func() error {
batch := make([]Entry, 0, 1000)
for e := range entries {
batch = append(batch, e)
if len(batch) == cap(batch) {
if err := repo.InsertBatch(ctx, batch); err != nil {
return err
}
batch = batch[:0]
}
}
if len(batch) > 0 {
return repo.InsertBatch(ctx, batch)
}
return nil
})
return g.Wait()
}
Why this terminates in all cases:
- Success: parse closes
rows→ mappers drain and exit → closer closesentries→ batcher flushes and exits. - Error in any stage: errgroup cancels
ctx; parse stops sending and closesrows; blocked sends select onctx.Done();Waitreturns the first error. - Caller cancels: same path as error.
Memory is bounded by the channel buffers and the batch size, not the file size. For exactly-once semantics on re-import, make InsertBatch idempotent (unique key on file ID + line number) — see Idempotency & Exactly-Once.
A reusable, generic fan-in:
func Merge[T any](ctx context.Context, ins ...<-chan T) <-chan T {
out := make(chan T)
var wg sync.WaitGroup
for _, in := range ins {
wg.Go(func() {
for v := range in {
select {
case out <- v:
case <-ctx.Done():
return
}
}
})
}
go func() {
wg.Wait()
close(out)
}()
return out
}
Bounded parallelism
// SettleAll settles every merchant with at most 16 concurrent bank sessions.
func SettleAll(ctx context.Context, merchants []string,
settle func(context.Context, string) error) error {
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(16) // from the bank's session limit, minus headroom
for _, m := range merchants {
g.Go(func() error { // blocks here while 16 are running
if err := settle(ctx, m); err != nil {
return fmt.Errorf("settle %s: %w", m, err)
}
return nil
})
}
return g.Wait()
}
Fail-fast is wrong for batch jobs where one bad merchant shouldn't stop the other 2,999. Use a plain errgroup.Group (no context cancellation), collect per-item errors, and report them:
func SettleAllCollect(ctx context.Context, merchants []string,
settle func(context.Context, string) error) error {
var (
g errgroup.Group
mu sync.Mutex
errs []error
)
g.SetLimit(16)
for _, m := range merchants {
g.Go(func() error {
if err := settle(ctx, m); err != nil {
mu.Lock()
errs = append(errs, fmt.Errorf("settle %s: %w", m, err))
mu.Unlock()
}
return nil
})
}
_ = g.Wait()
return errors.Join(errs...) // nil if every merchant succeeded
}
Rate limiting with x/time/rate
golang.org/x/time/rate implements a token bucket: rate r tokens per second, bucket size b (burst).
// Outbound: the PSP contract allows 100 requests/s; smooth our traffic.
type PSPClient struct {
lim *rate.Limiter
http *http.Client
}
func NewPSPClient(hc *http.Client) *PSPClient {
return &PSPClient{lim: rate.NewLimiter(rate.Limit(100), 20), http: hc}
}
func (c *PSPClient) Capture(ctx context.Context, id string) error {
if err := c.lim.Wait(ctx); err != nil { // waits for a token or ctx
return fmt.Errorf("psp rate limit wait: %w", err)
}
return c.doCapture(ctx, id)
}
Wait(ctx)blocks until a token is available (returns an error immediately if the deadline can't be met).Allow()returns false instead of waiting — use it inbound to respond 429 withRetry-After.Reserve()gives you the delay to schedule work yourself.
Per-client inbound limiting keeps one limiter per API key in a map guarded by a mutex — with eviction of idle keys, or the map grows with every key ever seen. For limits shared by many pods, use a distributed limiter (Redis, the API gateway); see Rate Limiting.
singleflight: collapse duplicate work
golang.org/x/sync/singleflight ensures that, for a given key, only one call is in flight; concurrent callers wait and share the result. It is the in-process fix for cache stampedes.
The subtle part is context: Do runs the function with the first caller's context. If that caller disconnects, every waiter gets context.Canceled. Detach the shared work and let each caller wait on its own context:
type RateService struct {
group singleflight.Group
cache RateCache
src RateSource
}
func (s *RateService) Get(ctx context.Context, pair string) (Rate, error) {
if r, ok := s.cache.Get(pair); ok {
return r, nil
}
ch := s.group.DoChan(pair, func() (any, error) {
// Shared work: not tied to any one caller, but still bounded.
fctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer cancel()
r, err := s.src.Fetch(fctx, pair)
if err == nil {
s.cache.Set(pair, r)
}
return r, err
})
select {
case res := <-ch:
if res.Err != nil {
return Rate{}, res.Err
}
return res.Val.(Rate), nil
case <-ctx.Done():
return Rate{}, ctx.Err() // this caller gives up; the fetch continues for others
}
}
Notes: errors are shared too (one failure fails all waiters); Forget(key) lets the next caller start a fresh call; singleflight dedups per process — 40 pods still send 40 requests, which is usually fine. For fleet-wide protection, add jittered TTLs or early refresh in Caching.
In-process pub/sub
Useful for fanning order-status updates out to WebSocket connections or broadcasting cache invalidations within a pod. Not a replacement for Kafka — nothing is durable.
type Broker[T any] struct {
mu sync.RWMutex
subs map[uint64]chan T
next uint64
}
func NewBroker[T any]() *Broker[T] {
return &Broker[T]{subs: make(map[uint64]chan T)}
}
// Subscribe returns a channel and an idempotent unsubscribe function.
func (b *Broker[T]) Subscribe(buf int) (<-chan T, func()) {
ch := make(chan T, buf)
b.mu.Lock()
id := b.next
b.next++
b.subs[id] = ch
b.mu.Unlock()
return ch, func() {
b.mu.Lock()
defer b.mu.Unlock()
if _, ok := b.subs[id]; ok {
delete(b.subs, id)
close(ch) // safe: Publish holds RLock while sending
}
}
}
// Publish never blocks; slow subscribers miss messages.
func (b *Broker[T]) Publish(v T) (dropped int) {
b.mu.RLock()
defer b.mu.RUnlock()
for _, ch := range b.subs {
select {
case ch <- v:
default:
dropped++
}
}
return dropped
}
The key design decision is the slow-consumer policy: drop (above, fine for live dashboards), block (one slow client stalls everyone — almost never right), or disconnect the subscriber after N drops (good for WebSockets: client reconnects and re-syncs state). Make the policy explicit and count drops in a metric. Durable fan-out belongs in Message Queues & Event Streaming.
Graceful shutdown
Kubernetes sends SIGTERM, waits terminationGracePeriodSeconds (default 30 s), then SIGKILL. Endpoints are removed from load balancers asynchronously, so for a few seconds new requests can still arrive after SIGTERM.
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx); err != nil {
slog.Error("service exited", "err", err)
os.Exit(1)
}
}
func run(ctx context.Context) error {
db, err := openDB(ctx)
if err != nil {
return err
}
defer db.Close() // closed last, after everything using it stopped
var ready atomic.Bool
ready.Store(true)
srv := &http.Server{
Addr: ":8080",
Handler: routes(db, &ready),
ReadHeaderTimeout: 5 * time.Second,
}
g, gctx := errgroup.WithContext(ctx)
g.Go(func() error {
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
})
g.Go(func() error {
return runConsumer(gctx, db) // returns after committing offsets when gctx ends
})
g.Go(func() error {
<-gctx.Done() // SIGTERM, or another component failed
ready.Store(false) // /readyz now returns 503
time.Sleep(5 * time.Second) // let endpoints converge; tune to your LB
sctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
return srv.Shutdown(sctx) // stops accepting, waits for in-flight requests
})
return g.Wait()
}
Rules: shut down in reverse dependency order; Shutdown doesn't wait for hijacked connections (WebSockets) — track and close those yourself (RegisterOnShutdown); background goroutines started by handlers need their own tracking; and keep the total under the grace period (5 s + 20 s + consumer drain ≤ 30 s here, or raise the period).
Trade-offs
| Pattern | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Goroutine per item | Simplest code | Unbounded under spikes | Small, bounded inputs |
errgroup.SetLimit | Bounded, error-aware, little code | Fail-fast by default; one error kept | Batch of independent tasks |
| Worker pool + channels | Long-lived, streaming, controllable | More code; ordering lost | Continuous job streams, consumers |
| Pipeline | Bounded memory, stage-level parallelism | Complex error/close choreography | Large file or stream processing |
rate.Limiter.Wait | Smooth outbound traffic | Process-local; adds latency | Respecting partner rate limits |
rate.Limiter.Allow | Fast rejection | Process-local; per-key map needs eviction | Inbound API limits per client |
| singleflight | Removes duplicate in-flight work | Shared errors; context pitfalls; per process | Cache-miss stampedes, hot keys |
| In-process pub/sub | Very fast fan-out | Not durable; slow-consumer policy needed | Live updates, local invalidations |
| Broker (Kafka, RabbitMQ) | Durable, cross-service | Ops cost, latency | Payment events, anything that must not be lost |
In practice
- Size limits from downstream contracts. If the bank allows 16 sessions shared by 4 pods, each pod gets 4 — or you centralise the job in one leader.
- Measure queue depth and wait time. Export
len(jobs)(sampled), in-flight count, and limiter wait duration; these tell you whether to scale workers or the dependency. - Retry inside the worker with backoff and jitter only for retryable errors, and only within the context's budget. See Resilience Patterns.
- Idempotency everywhere pipelines write: a crash mid-import plus a rerun must not double-post.
- Prefer errgroup-based structures — they make "who waits for whom" explicit, which reviewers can verify.
- Use
testing/synctest(Go 1.25) to test timeouts, tickers and rate limiting deterministically without real sleeps (see Testing & Benchmarking).
Common pitfalls
- Closing the results channel from a worker — panics when another worker sends. One closer, after
wg.Wait(). - Producer blocked forever after the consumer returned on error — every send must also select on
ctx.Done(). - Reusing a batch slice that
InsertBatchretained or sent to another goroutine — corrupted batches. - Pool sized by
runtime.NumCPU()for I/O-bound work — far too small, or too large for the dependency. - singleflight with the caller's context — one canceled request fails all waiters.
- Per-key limiter maps without eviction — memory leak proportional to unique API keys / IPs.
- Shutdown that only calls
srv.Shutdown— consumers keep processing, offsets aren't committed, outbox rows are half-sent; or the readiness probe still says ready. - Shutdown longer than the grace period — SIGKILL mid-transaction.
- Pub/sub that blocks on slow subscribers — one stuck WebSocket freezes all updates.
Interview angle
Prompts: "Design a worker pool that processes payments from a queue", "How would you process a 5 GB file concurrently with bounded memory?", "Our cache expiry causes DB spikes — fix it in Go", "Call a partner API limited to 100 TPS", "How do you deploy without dropping requests?"
A strong answer writes the code shape with all three exits, uses errgroup and SetLimit, explains channel ownership and the single-closer rule, sizes concurrency from downstream limits, picks Wait vs Allow correctly, handles singleflight's context issue, and lays out the shutdown order with Kubernetes timing (readiness → drain → consumers → flush → close).
Follow-ups: "What if order matters?", "How do you handle a poison message in the pool?" (dead-letter after N attempts), "What if the limit is global across pods?", "How do you test this deterministically?"
Red flags: unbounded goroutines per message, time.Sleep as rate limiting, no story for partial failures, shutdown via os.Exit in a signal handler.
Self-check
1. In the worker pool, why is there a separate goroutine that calls wg.Wait() and then close(results)?
Results has many senders (the workers), so no worker can know it's last. The closer waits for all workers to exit and then closes once, letting the consumer's range results terminate. Closing from a worker would panic other workers' sends.
2. Walk through what happens in ImportSettlement when line 40,000 fails validation.
The mapper returns an error; errgroup cancels ctx. The parser's next send selects ctx.Done(), returns and closes rows; other mappers drain or abort and exit; the closer closes entries; the batcher finishes its range (inserts fail fast with the canceled ctx) and exits. Wait returns the line-40,000 error. Rows already inserted must be idempotent or wrapped in a staging table for a clean rerun.
3. When do you use rate.Limiter.Wait and when Allow?
Wait(ctx) for outbound calls you must make but must pace (a partner's TPS limit) — it delays within the context's deadline. Allow() for inbound traffic you may reject — return 429 immediately instead of queuing work you can't afford.
4. What's the context pitfall with singleflight.Do, and how does the page's Get avoid it?
Do runs the function once using whatever context the first caller captured; if that caller cancels, the shared call fails for every waiter. Get uses DoChan, runs the fetch with WithoutCancel plus its own timeout, and each caller selects on its own ctx.Done(), so a departing caller doesn't affect others.
5. Scenario: a rolling deploy causes a burst of 502s at the load balancer. What's missing from the shutdown sequence?
Likely the pod stops accepting connections immediately on SIGTERM while the load balancer still routes to it. Fail readiness first, wait for endpoint removal to propagate (a few seconds, or a preStop hook), then Shutdown to drain in-flight requests — all within terminationGracePeriodSeconds. Also ensure keep-alive connections are closed by Shutdown so clients reconnect elsewhere.
6. Your pub/sub feeds order-status updates to 20k WebSocket clients and one client on a bad network stalls everyone. Fix it.
Make Publish non-blocking per subscriber with a bounded buffer, and choose a policy: drop and count, or disconnect after N drops so the client reconnects and fetches current state. Each WebSocket gets its own writer goroutine with a write deadline, so a slow socket blocks only itself.
Exercise
Build settlement-runner:
- A pipeline that reads a gzip CSV of 1M synthetic transactions, validates with 4 mappers, and batch-inserts 1,000 rows per transaction into PostgreSQL (or a fake), using
errgroup. - Rate-limit inserts to 50 batches/s with
rate.Limiter.Wait. - Add an FX-rate lookup per row through a
RateServiceusingsingleflight+ TTL cache; count actual source calls and show they stay at one per currency pair per TTL. - Implement graceful shutdown: on SIGTERM mid-import, stop reading, finish the current batch, record the last committed line, and exit 0; a rerun resumes from that line without duplicates.
- Measure: peak RSS (should be flat regardless of file size), throughput, and goroutine count after completion (back to baseline).
Done when: a forced SIGTERM at a random moment followed by a rerun yields exactly 1M rows, and goleak passes in tests.
Further reading
- Go blog: "Go Concurrency Patterns: Pipelines and cancellation" (Sameer Ajmani).
- Go talks: "Go Concurrency Patterns" and "Advanced Go Concurrency Patterns" (Rob Pike, Sameer Ajmani).
- Katherine Cox-Buday, Concurrency in Go — pipelines, fan-out/fan-in, or-done, bridge, heartbeats.
golang.org/x/sync/errgroup,golang.org/x/sync/singleflight,golang.org/x/time/ratepackage docs.- Kubernetes documentation: "Pod Lifecycle" — termination and grace periods.
- Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — concurrency practice chapter.
Related
- Goroutines & Channels — the primitives these patterns compose.
- sync, atomic & context — errgroup, semaphores and context in detail.
- Rate Limiting — algorithms and distributed limiters.
- Caching — stampede protection beyond singleflight.
- Building Production Services — where graceful shutdown fits in a full service.
- Cloud-Native, Kubernetes & Deployment Strategies — probes, rolling updates and termination.
- Reconciliation & Settlement — the batch jobs these patterns run.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).