System Design Part 3: Golang Concurrency & Performance
Let me tell you about the incident that made me respect Go's concurrency model—by nearly destroying our production system.
It was Black Friday 2023. Our image processing service was handling 50,000 uploads per minute, and everything was green. Then someone pushed a "minor optimization"—replacing our worker pool with raw goroutine spawning. "It's more efficient," they said. "No overhead from channels."
Within 15 minutes, our servers were consuming 40GB of RAM. Database connections were exhausted. The kernel was killing processes. We lost $2.3 million in revenue during the 47-minute outage.
The "optimization" was this:
go// The code that cost us $2.3 million for _, image := range images { go processImage(image) // Seemed so simple }
This guide will teach you why that code was catastrophically wrong, how to build systems that handle millions of operations, and the production patterns I wish I'd known before that Friday.
The Real Problem: Unbounded Concurrency
Here's what actually happens when you spawn unlimited goroutines:
At 50,000 requests/minute:
- 50,000 goroutines spawned
- Each goroutine needs ~2KB minimum stack
- 50,000 × 2KB = 100MB just for stacks
- Each opens a database connection
- Connection pool (default 100) exhausted in 0.12 seconds
- Remaining 49,900 goroutines block, waiting for connections
- Next minute: 50,000 more goroutines spawn
- Memory grows linearly: 100MB → 200MB → 300MB...
- After 15 minutes: 750,000 blocked goroutines, 1.5GB+ RAM

Worker Pool Pattern
The goroutines never die because they're blocked on database connections. They accumulate until the OOM killer intervenes.
Building a Production Worker Pool
Let me show you the worker pool we built after that incident. It's been running for two years without a single memory issue.
The Core Structure
gotype WorkerPool struct { workers int taskQueue chan Task resultChan chan Result wg sync.WaitGroup ctx context.Context cancel context.CancelFunc // Metrics for observability metrics *PoolMetrics } type PoolMetrics struct { tasksProcessed atomic.Int64 tasksFailed atomic.Int64 activeWorkers atomic.Int32 queueDepth atomic.Int32 }
Why these specific fields?
workers: Fixed count prevents unbounded growthtaskQueue: Bounded channel provides backpressurectx/cancel: Enables graceful shutdownmetrics: You can't debug what you can't measure
Starting the Pool
gofunc NewWorkerPool(workers, queueSize int) *WorkerPool { ctx, cancel := context.WithCancel(context.Background()) p := &WorkerPool{ workers: workers, taskQueue: make(chan Task, queueSize), resultChan: make(chan Result, queueSize), ctx: ctx, cancel: cancel, metrics: &PoolMetrics{}, } for i := 0; i < workers; i++ { p.wg.Add(1) go p.worker(i) } return p } func (p *WorkerPool) worker(id int) { defer p.wg.Done() for { select { case task, ok := <-p.taskQueue: if !ok { return // Channel closed, shutdown } p.metrics.activeWorkers.Add(1) p.metrics.queueDepth.Add(-1) result := p.processTask(task) p.metrics.activeWorkers.Add(-1) if result.Err != nil { p.metrics.tasksFailed.Add(1) } else { p.metrics.tasksProcessed.Add(1) } // Non-blocking send to result channel select { case p.resultChan <- result: default: // Result channel full, log and continue } case <-p.ctx.Done(): return } } }

Worker Sequence
Submitting Tasks with Backpressure
Here's the critical part that prevents overload:
gofunc (p *WorkerPool) Submit(ctx context.Context, task Task) error { select { case p.taskQueue <- task: p.metrics.queueDepth.Add(1) return nil case <-ctx.Done(): return ctx.Err() case <-p.ctx.Done(): return ErrPoolShutdown } } // Non-blocking variant for APIs that need immediate response func (p *WorkerPool) TrySubmit(task Task) error { select { case p.taskQueue <- task: p.metrics.queueDepth.Add(1) return nil default: return ErrQueueFull // Caller should return 503 } }
The key insight: When the queue is full,
TrySubmit returns immediately with ErrQueueFull. The HTTP handler converts this to a 503 with Retry-After header. The client backs off. The system stays healthy.Without this, requests pile up in goroutines, memory grows, and you get the Black Friday scenario.

Backpressure
Graceful Shutdown
This is where most implementations fail. Here's how to do it right:
gofunc (p *WorkerPool) Shutdown(timeout time.Duration) error { // Step 1: Stop accepting new tasks close(p.taskQueue) // Step 2: Wait for workers with timeout done := make(chan struct{}) go func() { p.wg.Wait() close(done) }() select { case <-done: close(p.resultChan) return nil // Clean shutdown case <-time.After(timeout): p.cancel() // Force cancel remaining work return ErrShutdownTimeout } }

Graceful Shutdown
Why this matters: During deploys, you need to drain in-flight requests. If you just kill the process, users see errors. With graceful shutdown, existing requests complete while new requests go to fresh instances.
Real Incident: The Goroutine Leak That Ate 64GB
Three months after the Black Friday fix, we hit another problem. Memory usage was climbing slowly—about 100MB per hour. After 24 hours, servers were using 2.4GB more than at startup. After a week, the 64GB servers were hitting swap.
We added runtime monitoring:
gogo func() { ticker := time.NewTicker(time.Minute) for range ticker.C { log.Info("goroutine_count", "count", runtime.NumGoroutine(), "heap_mb", getHeapMB(), ) } }()
The goroutine count was climbing: 500 → 600 → 700 per hour.
The culprit? A background email sender:
gofunc sendOrderConfirmation(order Order) { go func() { resp, err := emailClient.Send(order.Email, template) if err != nil { // Log and retry time.Sleep(5 * time.Second) sendOrderConfirmation(order) // Recursive retry! } }() }
When the email service was slow or down, this code would:
- Spawn a goroutine
- Fail after 30-second timeout
- Sleep 5 seconds
- Spawn another goroutine (recursive call)
- Original goroutine still hasn't returned
Each failure created a new goroutine without cleaning up the old one. During email outages, we were creating 12 goroutines per minute per failed email.

Goroutine Leak
The fix:
gofunc sendOrderConfirmation(ctx context.Context, order Order) error { const maxRetries = 3 for attempt := 0; attempt < maxRetries; attempt++ { err := emailClient.Send(ctx, order.Email, template) if err == nil { return nil } // Check if we should give up select { case <-ctx.Done(): return ctx.Err() case <-time.After(backoff(attempt)): // Continue to next attempt } } // Max retries exceeded, queue for later return deadLetterQueue.Push(order) } func backoff(attempt int) time.Duration { return time.Duration(1<<attempt) * time.Second // 1s, 2s, 4s }
Key changes:
- No goroutine spawning—caller decides concurrency
- Bounded retries with exponential backoff
- Context cancellation for cleanup
- Dead letter queue for persistent failures
Detecting Leaks in Tests
We now run this in every test:
gofunc TestMain(m *testing.M) { goleak.VerifyTestMain(m) } // Or manually: func TestNoLeaks(t *testing.T) { before := runtime.NumGoroutine() // Run your code doSomething() // Give goroutines time to clean up time.Sleep(100 * time.Millisecond) after := runtime.NumGoroutine() if after > before+1 { // Allow small variance buf := make([]byte, 1024*1024) n := runtime.Stack(buf, true) t.Fatalf("Goroutine leak: %d -> %d\n%s", before, after, buf[:n]) } }

Leak Detection
The Deadlock That Only Happened on Tuesdays
This one took three weeks to debug. Our payment service would freeze every Tuesday around 2 PM, requiring a restart. No errors, no panics—just complete silence.
The smoking gun was in the goroutine dump:
bashcurl localhost:6060/debug/pprof/goroutine?debug=2 > dump.txt
goroutine 847 [semacquire, 847 minutes]: sync.runtime_SemacquireMutex(...) sync/mutex.go:72 main.(*TransferService).Transfer(...) /app/transfer.go:45 goroutine 849 [semacquire, 847 minutes]: sync.runtime_SemacquireMutex(...) sync/mutex.go:72 main.(*TransferService).Transfer(...) /app/transfer.go:45
Two goroutines, both waiting on mutex acquisition, for 847 minutes. Classic deadlock.
The code:
gofunc (s *TransferService) Transfer(from, to *Account, amount int64) error { from.mu.Lock() defer from.mu.Unlock() to.mu.Lock() defer to.mu.Unlock() if from.Balance < amount { return ErrInsufficientFunds } from.Balance -= amount to.Balance += amount return nil }
Why Tuesdays? That's when payroll ran. Thousands of transfers happened simultaneously, and eventually two transfers would try:
- Transfer A→B (goroutine 1 locks A, wants B)
- Transfer B→A (goroutine 2 locks B, wants A)
Deadlock.

Classic Deadlock
The fix—consistent lock ordering:
gofunc (s *TransferService) Transfer(from, to *Account, amount int64) error { // Always lock accounts in ID order first, second := from, to if from.ID > to.ID { first, second = to, from } first.mu.Lock() defer first.mu.Unlock() second.mu.Lock() defer second.mu.Unlock() if from.Balance < amount { return ErrInsufficientFunds } from.Balance -= amount to.Balance += amount return nil }
The rule: If you must hold multiple locks, always acquire them in the same global order. We use account ID, but any consistent ordering works.
The Sneakier Deadlock: Mutex + Channel
Another variant that bit us:
gotype Queue struct { mu sync.Mutex items chan int } func (q *Queue) Push(item int) { q.mu.Lock() defer q.mu.Unlock() q.items <- item // Blocks if channel full! } func (q *Queue) Pop() int { q.mu.Lock() defer q.mu.Unlock() return <-q.items // Needs the lock Push is holding! }
If
items channel is full, Push blocks while holding the mutex. Pop can't acquire the mutex to drain the channel. Deadlock.
Channel Mutex Deadlock
The rule: Never hold a lock while performing a blocking channel operation.
gofunc (q *Queue) PushFixed(item int) error { select { case q.items <- item: return nil default: return ErrQueueFull } }
Context Cancellation: The Patterns That Actually Work
Context is Go's mechanism for cancellation, deadlines, and request-scoped values. Here's how to use it correctly.

Context Rules
Pattern 1: Timeout for External Calls
Every external call needs a timeout. Period.
gofunc (c *Client) FetchUser(ctx context.Context, id string) (*User, error) { // Add timeout if caller didn't provide one ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() // Always cancel to release resources req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/users/"+id, nil) if err != nil { return nil, err } resp, err := c.httpClient.Do(req) if err != nil { if ctx.Err() == context.DeadlineExceeded { return nil, ErrTimeout // More specific error } return nil, err } defer resp.Body.Close() var user User if err := json.NewDecoder(resp.Body).Decode(&user); err != nil { return nil, err } return &user, nil }

Timeout Pattern
Pattern 2: First Error Cancels All
When fetching multiple resources, fail fast:
gofunc (s *Service) GetDashboard(ctx context.Context, userID string) (*Dashboard, error) { g, ctx := errgroup.WithContext(ctx) var user *User var orders []*Order var recommendations []*Product g.Go(func() error { var err error user, err = s.users.Get(ctx, userID) return err }) g.Go(func() error { var err error orders, err = s.orders.Recent(ctx, userID, 10) return err }) g.Go(func() error { var err error recommendations, err = s.recommender.ForUser(ctx, userID) return err // If this fails, cancel the others }) if err := g.Wait(); err != nil { return nil, err } return &Dashboard{user, orders, recommendations}, nil }

Errgroup Pattern
Pattern 3: Long Operations with Checkpoints
For operations that process large amounts of data:
gofunc (p *Processor) ProcessFile(ctx context.Context, file *os.File) error { scanner := bufio.NewScanner(file) lineNum := 0 for scanner.Scan() { lineNum++ // Check cancellation every 1000 lines if lineNum%1000 == 0 { select { case <-ctx.Done(): return fmt.Errorf("cancelled at line %d: %w", lineNum, ctx.Err()) default: } } if err := p.processLine(scanner.Text()); err != nil { return fmt.Errorf("line %d: %w", lineNum, err) } } return scanner.Err() }
GC Pressure: Death by a Thousand Allocations
At 100,000 requests per second, small inefficiencies become catastrophic:
- 1KB allocation per request = 100MB/second of garbage
- GC runs every ~2 seconds at this rate
- Each GC pause: 1-10ms
- 1000 requests affected per GC pause
- p99 latency spikes to 50ms+ during GC

GC Pressure
The Biggest Offenders

GC Offenders
1. Slice Growth
go// Bad: Multiple allocations as slice grows func collectIDs(users []*User) []string { var ids []string // Starts at cap 0 for _, u := range users { ids = append(ids, u.ID) // Reallocates at 0, 1, 2, 4, 8, 16... } return ids } // Good: Single allocation func collectIDs(users []*User) []string { ids := make([]string, 0, len(users)) // Pre-allocate for _, u := range users { ids = append(ids, u.ID) // No reallocation } return ids }
2. String Concatenation
go// Bad: O(n²) allocations—new string for each + func buildQuery(conditions []string) string { query := "SELECT * FROM users WHERE " for i, cond := range conditions { if i > 0 { query += " AND " } query += cond } return query } // Good: O(1) allocations func buildQuery(conditions []string) string { var b strings.Builder b.WriteString("SELECT * FROM users WHERE ") for i, cond := range conditions { if i > 0 { b.WriteString(" AND ") } b.WriteString(cond) } return b.String() }
3. Object Pooling for Hot Paths

Object Pool
govar bufferPool = sync.Pool{ New: func() interface{} { return bytes.NewBuffer(make([]byte, 0, 4096)) }, } func ProcessRequest(data []byte) ([]byte, error) { buf := bufferPool.Get().(*bytes.Buffer) defer func() { buf.Reset() bufferPool.Put(buf) }() // Use buf for processing buf.Write(data) // ... transform data ... // Must copy out—buffer returns to pool result := make([]byte, buf.Len()) copy(result, buf.Bytes()) return result, nil }
Critical: Always
Reset() before returning to pool, and copy out any data you need to keep.4. Struct Layout Optimization
go// Bad: 24 bytes due to padding type BadLayout struct { A bool // 1 byte + 7 padding (align to 8) B int64 // 8 bytes C bool // 1 byte + 7 padding } // Good: 16 bytes type GoodLayout struct { B int64 // 8 bytes A bool // 1 byte C bool // 1 byte + 6 padding }
Use
fieldalignment linter to catch these automatically:bashgo install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest fieldalignment -fix ./...
Mutex vs RWMutex: The Counterintuitive Truth
Everyone assumes RWMutex is always better for read-heavy workloads. Our benchmarks showed otherwise:

Mutex Decision Tree
| Scenario | Mutex | RWMutex | Winner |
|---|---|---|---|
| 99% reads, 100μs hold time | 28 ns/op | 8 ns/op | RWMutex |
| 50% reads, 100μs hold time | 30 ns/op | 45 ns/op | Mutex |
| 99% reads, 10ns hold time | 15 ns/op | 22 ns/op | Mutex |
Why? RWMutex has overhead:
- Read lock/unlock requires atomic operations on a counter
- Multiple readers must coordinate
- For fast operations (<100ns), the coordination overhead exceeds the benefit

Mutex vs RWMutex
Rules of thumb:
- RWMutex: Read-heavy (>90% reads) AND holds lock for >1μs
- Mutex: Mixed workloads or fast operations
- Atomic: Single values (counters, flags)
- Channel: Coordination between goroutines
go// Cache with slow operations → RWMutex type Cache struct { mu sync.RWMutex data map[string]*CachedItem } func (c *Cache) Get(key string) *CachedItem { c.mu.RLock() defer c.mu.RUnlock() return c.data[key] } // Counter → Atomic (no lock needed) type Counter struct { value atomic.Int64 } func (c *Counter) Increment() int64 { return c.value.Add(1) } // Rate limiter (read + write every call) → Mutex type RateLimiter struct { mu sync.Mutex tokens int last time.Time }
Security: Protecting Concurrent Systems
Concurrent systems have unique attack vectors. Here's what we've learned defending against them.
Race Condition Exploitation
The vulnerability:
gotype Account struct { mu sync.Mutex balance int64 } // Vulnerable: Check-then-act without holding lock func (a *Account) Withdraw(amount int64) error { if a.balance < amount { // Check return ErrInsufficientFunds } a.mu.Lock() a.balance -= amount // Act a.mu.Unlock() return nil }
An attacker can exploit this by sending concurrent withdrawal requests. Both threads pass the balance check before either acquires the lock, resulting in overdraft.
The fix:
gofunc (a *Account) Withdraw(amount int64) error { a.mu.Lock() defer a.mu.Unlock() if a.balance < amount { return ErrInsufficientFunds } a.balance -= amount return nil }
Goroutine Exhaustion Attack
An attacker can exhaust server resources by triggering unbounded goroutine creation:
go// Vulnerable: Each request creates unbounded goroutines func handleSearch(w http.ResponseWriter, r *http.Request) { terms := r.URL.Query()["q"] // Attacker sends 10,000 terms results := make(chan string, len(terms)) for _, term := range terms { go searchIndex(term, results) // 10,000 goroutines per request } // ... }
Defense in depth:
goconst maxSearchTerms = 10 const maxConcurrentSearches = 100 var searchSem = make(chan struct{}, maxConcurrentSearches) func handleSearch(w http.ResponseWriter, r *http.Request) { terms := r.URL.Query()["q"] // Limit 1: Cap input size if len(terms) > maxSearchTerms { http.Error(w, "Too many search terms", http.StatusBadRequest) return } results := make(chan string, len(terms)) for _, term := range terms { // Limit 2: Global concurrency cap select { case searchSem <- struct{}{}: go func(t string) { defer func() { <-searchSem }() searchIndex(t, results) }(term) case <-r.Context().Done(): return } } // ... }
Channel Flooding
Unbuffered or small-buffered channels can be used for denial of service:
go// Vulnerable: Slow consumer blocks producer func (s *Service) ProcessEvents(events <-chan Event) { for event := range events { s.processEvent(event) // If slow, producers block } }
Defense:
gofunc (s *Service) ProcessEvents(events <-chan Event) { // Timeout prevents indefinite blocking for { select { case event := <-events: ctx, cancel := context.WithTimeout(context.Background(), time.Second) s.processEvent(ctx, event) cancel() case <-s.shutdown: return } } } // Producer side: Non-blocking with metrics func (s *Service) Emit(event Event) error { select { case s.events <- event: return nil default: s.metrics.droppedEvents.Inc() return ErrEventDropped } }
Timing Attacks on Mutexes
Lock acquisition timing can leak information:
go// Vulnerable: Lock time reveals cache hit vs miss func (c *SecretCache) Get(key string) (string, bool) { c.mu.Lock() defer c.mu.Unlock() if val, ok := c.cache[key]; ok { return val, true // Fast path } // Slow path: fetch from database val := c.fetchFromDB(key) c.cache[key] = val return val, true }
An attacker can determine which keys are cached by measuring response times.
Mitigation:
gofunc (c *SecretCache) Get(key string) (string, bool) { c.mu.RLock() val, ok := c.cache[key] c.mu.RUnlock() if ok { // Add jitter to mask timing time.Sleep(time.Duration(rand.Intn(1000)) * time.Microsecond) return val, true } // ... fetch and cache }
Interview Cheat Sheet
When Asked About Goroutines
-
"How many goroutines should I spawn?"
- Never unbounded—use worker pools
- Rule of thumb:
GOMAXPROCS * 10for CPU-bound - For I/O-bound: Limited by external resource (DB connections, etc.)
-
"How do you prevent goroutine leaks?"
- Always pass context for cancellation
- Use
goleakin tests - Track goroutine count in metrics
- Every
gostatement needs a shutdown path
-
"Mutex vs RWMutex?"
- RWMutex: >90% reads AND >1μs hold time
- Otherwise: plain Mutex or atomics
- Never hold lock during I/O
When Asked About Performance
-
"How do you reduce GC pressure?"
sync.Poolfor frequently allocated objects- Pre-allocate slices with known capacity
strings.Builderfor concatenation- Field alignment for struct packing
-
"How do you debug production issues?"
- for deadlocks
/debug/pprof/goroutine?debug=2 /debug/pprof/heapfor memory- for CPU
/debug/pprof/profile?seconds=30 - Runtime metrics: goroutine count, heap size
Red Flags to Avoid
- Spawning goroutines in loops without limits
- Blocking channel operations while holding mutex
- Missing context cancellation in external calls
time.Sleepfor coordination instead of proper sync- Recursive goroutine spawning on failure
Key Takeaways

Go Concurrency Mindmap
-
Bounded concurrency is non-negotiable. Worker pools with backpressure, not unbounded goroutine spawning.
-
Every goroutine needs a death plan. Context cancellation, channel close, or explicit signal.
-
Deadlocks are deterministic. Consistent lock ordering and never hold locks during channel operations.
-
Measure GC impact. Object pools, pre-allocation, and struct layout matter at scale.
-
Defense in depth for security. Input limits, concurrency caps, and timeout on everything.
The patterns in this guide have survived two years of production traffic at 100K+ requests per second. Apply them systematically, and your Go services will handle whatever scale throws at them.
What's Next?
In Part 4: Database & Storage Patterns, we'll explore:
- Connection pooling that actually works
- Read replicas and consistency tradeoffs
- Sharding strategies and their hidden costs
- The real reason your queries are slow
The incident that cost $2.3 million taught me more about concurrency than any textbook. I hope this guide helps you learn those lessons without the outage.