Go Concurrency Patterns#

“If a goroutine is responsible for creating a goroutine, it is also responsible for ensuring it can stop the goroutine.”
— Katherine Cox-Buday, Concurrency in Go

Safely combining Go’s low-level concurrency primitives (goroutines, channels, select) in production systems requires proven architectural patterns.

Most concurrency bugs do not stem from a lack of synchronization primitives, but rather from goroutine leaks caused by inadequate lifecycle management.


1. Confinement#

The most efficient way to achieve concurrent safety is not to add synchronization primitives, but to confine access to mutable data to a single concurrent process.

When exclusive ownership is guaranteed, critical sections disappear, making synchronization overhead zero-cost. Developers can write plain sequential code within the confined scope, significantly reducing cognitive load.

DimensionAd-hoc ConfinementLexical Confinement
Enforced ByConventions, comments, and team disciplineCompiler (lexical scope rules)
SafetyVulnerable to code degradation over timeStructurally eliminates illegal access
RecommendationDiscouragedStrongly Recommended

(1) Channel Direction Confinement#

Confining channel instantiation and write privileges within a function scope, while exposing only a receive-only (<-chan T) view to consumers, enforces read-only access at the compiler level.

chanOwner := func() <-chan int {
	// Channel instantiation and write capabilities are confined to this closure scope.
	results := make(chan int, 5)
	go func() {
		defer close(results)
		for i := 0; i <= 5; i++ {
			results <- i
		}
	}()
	// Expose only a receive-only channel externally.
	return results
}

consumer := func(results <-chan int) {
	// Attempting to write to results or call close() results in a compile-time error.
	for result := range results {
		fmt.Println("Received:", result)
	}
}

results := chanOwner()
consumer(results)

(2) Data Slicing Confinement#

Non-concurrent-safe data structures like bytes.Buffer or slices can be processed safely without locks by confining them to local goroutine stacks or partitioning them into disjoint sub-slices.

printData := func(wg *sync.WaitGroup, data []byte) {
	defer wg.Done()
	var buff bytes.Buffer // Confined to the goroutine's local stack; completely race-free.
	for _, b := range data {
		fmt.Fprintf(&buff, "%c", b)
	}
	fmt.Println(buff.String())
}

var wg sync.WaitGroup
wg.Add(2)
data := []byte("golang")

// Partition disjoint sub-slices to confine access exclusively per goroutine.
go printData(&wg, data[:3]) // Owns "gol"
go printData(&wg, data[3:]) // Owns "ang"

wg.Wait()

2. The for-select Loop#

The standard idiom in Go concurrent programming, used for multiplexing channel data operations alongside cancellation signals.

(1) Iterating Over a Collection with Cancellation#

for _, s := range []string{"a", "b", "c"} {
	select {
	case <-done: // Early exit upon receiving cancellation signal
		return
	case stringStream <- s:
	}
}

(2) Infinite Loop with Non-preemptable Work#

for {
	select {
	case <-done:
		return
	default:
		// Regular work executed when no cancellation signal is present
	}
}

3. Preventing Goroutine Leaks#

While goroutines are lightweight, they are never garbage collected by the Go runtime. A goroutine that remains blocked in memory leaks its stack and all referenced heap objects for the lifetime of the process.

A goroutine must always terminate through one of three paths:

  1. Work completion
  2. An unrecoverable error
  3. Explicit cancellation signal from a parent routine

(1) Consumer Leak & The done Channel#

Goroutines blocked waiting to receive from an unpopulated or nil channel block indefinitely. The parent routine must provide a done <-chan struct{} signal to command termination.

// Use a done channel to explicitly control child goroutine termination.
doWork := func(done <-chan struct{}, strings <-chan string) <-chan struct{} {
	terminated := make(chan struct{})
	go func() {
		defer fmt.Println("doWork exited")
		defer close(terminated)
		for {
			select {
			case s := <-strings:
				fmt.Println(s)
			case <-done: // Exits immediately when parent closes done channel.
				return
			}
		}
	}()
	return terminated
}

done := make(chan struct{})
terminated := doWork(done, nil) // Never leaks even with a nil channel.

go func() {
	time.Sleep(1 * time.Second)
	close(done) // Broadcast cancellation
}()

// <-terminated acts as a Join Point waiting for the single child goroutine to terminate via channel closure.
// For a single goroutine, it performs the exact same synchronization role as sync.WaitGroup's wg.Wait().
<-terminated

(2) Producer Leak#

When a consumer stops reading or returns early, a producer attempting to send into an unbuffered channel blocks forever. Producers must monitor the done channel during sends.

// Producers must monitor the cancellation channel to prevent write-blocking leaks.
newRandStream := func(done <-chan struct{}) <-chan int {
	randStream := make(chan int)
	go func() {
		defer fmt.Println("newRandStream exited")
		defer close(randStream)
		for {
			select {
			case <-done: // Exits immediately when consumer stops reading.
				return
			case randStream <- rand.Int():
			}
		}
	}()
	return randStream
}

done := make(chan struct{})
randStream := newRandStream(done)
for i := 1; i <= 3; i++ {
	fmt.Printf("%d: %d\n", i, <-randStream)
}
close(done) // Signal producer to stop once consumption finishes.

4. The or-channel#

Combines multiple cancellation (done) channels into a single unified done channel such that if any upstream channel closes, the composite channel immediately closes as well.

Useful when the exact number of channels to monitor cannot be determined at compile time.

var or func(channels ...<-chan any) <-chan any
or = func(channels ...<-chan any) <-chan any {
	// Base cases
	switch len(channels) {
	case 0:
		return nil
	case 1:
		return channels[0]
	}

	orDone := make(chan any)
	go func() {
		defer close(orDone)

		switch len(channels) {
		case 2:
			select {
			case <-channels[0]:
			case <-channels[1]:
			}
		default:
			// Recursive tree split: multiplex first channels with remaining subtrees.
			select {
			case <-channels[0]:
			case <-channels[1]:
			case <-channels[2]:
			case <-or(append(channels[3:], orDone)...):
			}
		}
	}()
	return orDone
}
  • Each recursive step consumes 2 channels and forwards the remaining slice, creating $f(N) = \lfloor N/2 \rfloor$ goroutines with $O(N)$ depth (a binary divide-and-conquer implementation can reduce the tree depth to $O(\log N)$).
  • When the composite parent channel closes, all recursive child goroutines terminate in cascade.

5. Error Handling#

When an error occurs inside a concurrent goroutine, the goroutine must not unilaterally exit the process (log.Fatal) or silently drop the error. Goroutines should package errors alongside results and delegate error handling policies (retry, log, terminate) to the caller.

The standard pattern is to define a container Result struct sent over a single channel.

type Result struct {
	Data string
	Err  error
}

checkStatus := func(done <-chan struct{}, urls ...string) <-chan Result {
	results := make(chan Result)
	go func() {
		defer close(results)
		for _, url := range urls {
			resp, err := http.Get(url)
			result := Result{Err: err}
			if err == nil {
				result.Data = resp.Status
				resp.Body.Close()
			}

			select {
			case <-done:
				return
			case results <- result:
			}
		}
	}()
	return results
}

done := make(chan struct{})
defer close(done)

urls := []string{"https://google.com", "badhost"}
for result := range checkStatus(done, urls...) {
	if result.Err != nil {
		fmt.Printf("error encountered: %v (caller decides whether to abort)\n", result.Err)
		continue
	}
	fmt.Printf("success: %s\n", result.Data)
}

6. Pipelines#

A pipeline is a chain of processing stages connected by channels where data flows sequentially from stage to stage.

Properties of a well-formed stage:

  • Consumes and returns channels of compatible types.
  • Maintains exclusive lexical ownership of data without sharing mutable state.
  • Accepts an incoming done channel to prevent goroutine leaks upon early termination.

(1) Batch Processing vs Stream Processing#

DimensionBatch ProcessingStream Processing
Data TransferAccumulates full slice/chunk before returningEmits elements one-by-one over channels
Memory FootprintProportional to total dataset size ($O(N)$)Bounded by pipeline channel buffers ($O(1)$)
Time to First ValueBlocked until all inputs are processedImmediate as soon as the first element is ready
Cancellation EfficiencyWastes memory and computation on aborted batchesUpstream stages cancel immediately on done

(2) Generators and Take#

Pipelines originate from a generator (repeat) that emits items continuously and terminate with a take stage that limits consumption.

repeat := func(done <-chan struct{}, values ...int) <-chan int {
	valueStream := make(chan int)
	go func() {
		defer close(valueStream)
		for {
			for _, v := range values {
				select {
				case <-done:
					return
				case valueStream <- v:
				}
			}
		}
	}()
	return valueStream
}

take := func(done <-chan struct{}, valueStream <-chan int, num int) <-chan int {
	takeStream := make(chan int)
	go func() {
		defer close(takeStream)
		for i := 0; i < num; i++ {
			select {
			case <-done:
				return
			case takeStream <- (<-valueStream):
			}
		}
	}()
	return takeStream
}

done := make(chan struct{})
defer close(done)

// Safely consume 3 elements from an infinite generator
for num := range take(done, repeat(done, 1, 2), 3) {
	fmt.Println(num) // 1, 2, 1
}

7. Fan-Out / Fan-In#

When a specific pipeline stage is computationally expensive or I/O bound, spawn multiple concurrent goroutines to execute that stage in parallel (Fan-Out), and aggregate their outputs back into a single channel (Fan-In).

(1) Preconditions#

  • Stateless Operations: Each stage input must be independent of other inputs.
  • Sufficient Work Duration: Individual task execution must exceed goroutine instantiation and channel synchronization overhead.
  • Order Insensitivity: Order of items in the output channel is non-deterministic.

(2) Fan-In Implementation#

Use sync.WaitGroup to wait for all parallel worker goroutines before safely closing the multiplexed output channel.

fanIn := func(done <-chan struct{}, channels ...<-chan any) <-chan any {
	var wg sync.WaitGroup
	multiplexedStream := make(chan any)

	multiplex := func(c <-chan any) {
		defer wg.Done()
		for i := range c {
			select {
			case <-done:
				return
			case multiplexedStream <- i:
			}
		}
	}

	wg.Add(len(channels))
	for _, c := range channels {
		go multiplex(c)
	}

	// Close multiplexed stream once all upstream workers finish
	go func() {
		wg.Wait()
		close(multiplexedStream)
	}()

	return multiplexedStream
}

8. The or-done-channel#

Encapsulates the repetitive select boilerplate needed across pipeline stages to monitor incoming channel values alongside cancellation signals.

orDone := func(done <-chan struct{}, c <-chan any) <-chan any {
	valStream := make(chan any)
	go func() {
		defer close(valStream)
		for {
			select {
			case <-done:
				return
			case v, ok := <-c:
				if !ok {
					return
				}
				select {
				case valStream <- v:
				case <-done:
				}
			}
		}
	}()
	return valStream
}

// Consumer code simplifies to a clean for-range loop.
for val := range orDone(done, myChan) {
	// Process val
}

9. The tee-channel#

Splits incoming data from a single input channel into two separate output channels, mirroring the Unix tee utility.

Non-blocking Delivery via nil Channels#

Uses a 2-iteration loop and select. Once an output channel receives a value, set its local copy to nil to disable that case in the next select iteration.

tee := func(done <-chan struct{}, in <-chan any) (<-chan any, <-chan any) {
	out1 := make(chan any)
	out2 := make(chan any)
	go func() {
		defer close(out1)
		defer close(out2)
		for val := range orDone(done, in) {
			var out1Copy, out2Copy = out1, out2
			for i := 0; i < 2; i++ {
				select {
				case <-done:
					return
				case out1Copy <- val:
					out1Copy = nil // Disable case for subsequent iteration once sent
				case out2Copy <- val:
					out2Copy = nil // Disable case for subsequent iteration once sent
				}
			}
		}
	}()
	return out1, out2
}

10. The bridge-channel#

Flattens a sequence of channels emitted over a channel (<-chan <-chan any) into a single continuous stream (<-chan any).

bridge := func(done <-chan struct{}, chanStream <-chan <-chan any) <-chan any {
	valStream := make(chan any)
	go func() {
		defer close(valStream)
		for {
			var stream <-chan any
			select {
			case maybeStream, ok := <-chanStream:
				if !ok {
					return
				}
				stream = maybeStream
			case <-done:
				return
			}
			for val := range orDone(done, stream) {
				select {
				case valStream <- val:
				case <-done:
				}
			}
		}
	}()
	return valStream
}

11. Queuing and Little’s Law#

Adding buffers to channels is frequently misunderstood as a mechanism to “speed up the system.”

(1) Fundamental Limits of Queues#

  • Queuing never reduces the overall runtime (end-to-end latency) of a pipeline.
  • System throughput is strictly capped by its slowest stage (the bottleneck).
  • Queues smooth out temporary bursts between stages. If arrival rate continuously exceeds processing capacity, the buffer will fill and block.

(2) Legitimate Uses of Queuing#

  1. Ingress Shock Absorber:
    • Shields internal services from traffic surges, preventing death-spiral cascades (upstream timeouts triggering retry storms).
    • Holds requests at the boundary and feeds them downstream at a sustainable processing rate.
  2. Batching:
    • Bundles individual operations into chunks where bulk I/O yields higher efficiency (e.g., batched database writes or network socket flushes).

(3) Little’s Law and the Cost of Bufferbloat#

In steady-state queuing systems, Little’s Law establishes:

\( L = \lambda W \)
  • $L$: Average number of items in the queue (Queue Depth)
  • $\lambda$: Average arrival and departure rate (Throughput)
  • $W$: Average time an item spends in the system (Latency)

Rearranging for latency:

\( W = \frac{L}{\lambda} \)
  • Latency Inflation: When throughput ($\lambda$) is constrained by a downstream bottleneck, enlarging the buffer ($L$) causes end-to-end latency ($W$) to grow linearly.
  • Bufferbloat: Instead of failing fast and signaling backpressure, items sit trapped in deep queues for seconds or minutes.
  • Zombie Work: Callers time out and disconnect, leaving servers to expend resources processing stale requests whose responses will never be consumed.

Rule of Thumb: Confine queuing to ingress boundaries. Inside pipeline stages, use unbuffered channels so backpressure propagates upstream immediately.


12. The context Package#

Standardizes cancellation signals, deadlines, and request-scoped metadata across goroutine call trees, addressing the limitations of raw done channels.

For full architectural details, fail-fast patterns, lifecycle pitfalls, and value storage heuristics, see standard library context.


13. Preventing Goroutine Leaks on Channel Send#

In concurrent pipelines, pairing <-ctx.Done() only with channel receives (<-ch) is insufficient. If a downstream consumer is canceled and exits, an upstream producer attempting to write (ch <- val) will block forever, causing a goroutine leak. Every blocking channel send must also be wrapped in a select statement with <-ctx.Done().

select {
case resultChan <- val:
    // Successfully sent downstream
case <-ctx.Done():
    // Downstream canceled or timed out -> exit cleanly without leaking goroutine
    return ctx.Err()
}

14. Heartbeats#

Heartbeats allow long-running goroutines to signal liveness to outside observers, solving the dilemma between setting timeouts too short (killing legitimate long-running work) or too long (delaying deadlock detection).

(1) Time-Interval Heartbeats#

Emits a pulse at fixed intervals using time.Ticker. Ideal for long-running production workers that spend variable time waiting on I/O or computation.

// Callee (Worker): Emits periodic pulses and results
func doWork(ctx context.Context, pulseInterval time.Duration) (<-chan any, <-chan time.Time) {
    heartbeat := make(chan time.Time)
    results := make(chan any)

    go func() {
        defer close(heartbeat)
        defer close(results)

        pulse := time.NewTicker(pulseInterval)
        defer pulse.Stop()

        sendPulse := func() {
            select {
            case heartbeat <- time.Now():
            default: // Non-blocking send: drops pulse if caller is busy to prevent deadlock
            }
        }

        for {
            select {
            case <-ctx.Done():
                return
            case <-pulse.C:
                sendPulse()
            case results <- computeNext():
            }
        }
    }()
    return results, heartbeat
}

// Caller (Observer): Monitors liveness using resettable time.After watchdog
func monitor(ctx context.Context) {
    results, heartbeat := doWork(ctx, 1*time.Second)
    for {
        select {
        case r, ok := <-results:
            if !ok {
                return // Channel closed cleanly -> exit loop
            }
            handleResult(r)
        case <-heartbeat:
            // Worker is alive
        case <-time.After(2 * time.Second):
            // No result or heartbeat for 2 seconds -> worker is unhealthy/deadlocked
            return
        }
    }
}
  • Why default: is mandatory when sending heartbeats: If the caller stops reading <-heartbeat temporarily, an unbuffered heartbeat <- time.Now() would block the worker goroutine indefinitely. Including default: makes the send non-blocking so the worker never stalls on its own heartbeat.
  • Why checking ok (!ok) is mandatory when receiving: A closed channel never blocks in a select block; it immediately returns the zero value and ok == false infinitely. Always check if !ok { return } to avoid an infinite CPU-spinning loop after channel closure.

(2) Work-Unit Heartbeats#

Emits a pulse at the start of each unit of work (loop iteration). Primarily used in unit tests (_test.go) to synchronize goroutine execution deterministically without relying on flaky time.Sleep calls.

func doWorkByUnit(ctx context.Context, nums ...int) (<-chan int, <-chan struct{}) {
    // Buffer size 1 ensures the initial pulse is not dropped if sent before the caller listens
    heartbeat := make(chan struct{}, 1)
    results := make(chan int)

    go func() {
        defer close(heartbeat)
        defer close(results)
        for _, n := range nums {
            select {
            case heartbeat <- struct{}{}:
            default:
            }

            select {
            case <-ctx.Done():
                return
            case results <- n * 2:
            }
        }
    }()
    return results, heartbeat
}

// Deterministic test synchronization without time.Sleep
func TestWorkerCancel(t *testing.T) {
    ctx, cancel := context.WithCancel(t.Context())
    results, heartbeat := doWorkByUnit(ctx, 1, 2, 3)

    <-heartbeat // Guarantees worker goroutine has started and entered the loop
    cancel()    // Deterministically test mid-execution cancellation
    ...
}
  • Why buffer size 1 (make(chan struct{}, 1)) is used: If the worker goroutine starts rapidly before the test caller reaches <-heartbeat, an unbuffered channel with default: would drop the first pulse, causing <-heartbeat to miss the signal. A 1-slot buffer preserves the initial pulse so the test caller receives it immediately upon reading.

15. Replicated Requests (Hedged Requests)#

Dispatches the same request concurrently across multiple backend handlers (goroutines, nodes, or replicas), accepting the first response to arrive and immediately canceling all remaining in-flight requests. Designed to drastically reduce Tail Latency (p99 / p99.9) rather than average latency.

func doReplicatedWork(ctx context.Context, numReplicas int) (Result, error) {
    // Derived context to immediately cancel losing replicas as soon as the first winner arrives
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    // Buffer size 1: ensures the winning replica writes non-blockingly and exits
    resultChan := make(chan Result, 1)

    for i := 0; i < numReplicas; i++ {
        go func(replicaID int) {
            res, err := callBackend(ctx, replicaID)
            if err != nil {
                return
            }
            select {
            case resultChan <- res:
                // Won the race
            case <-ctx.Done():
                // Another replica already won -> discard result and exit
            }
        }(i)
    }

    select {
    case res := <-resultChan:
        return res, nil // defer cancel() reclaims resources of slower replicas
    case <-ctx.Done():
        return Result{}, ctx.Err()
    }
}
  • Trade-off: Reduces tail latency at the expense of multiplying CPU and network resource consumption by $N$. In production, rather than blindly replicating every request immediately, Hedged Requests are preferred: send a single primary request first, and only spawn a secondary hedged request if the primary does not respond within a threshold (e.g., the p95 latency).

16. Rate Limiting#

While Replicated Requests consume more resources to reduce latency, Rate Limiting constrains the rate of incoming or outgoing operations to protect systems from resource exhaustion (CPU, memory, DB connection pools), cascading failures, retry storms, and quota/billing overruns.

(1) Token Bucket Algorithm & golang.org/x/time/rate#

The standard Go rate limiter (golang.org/x/time/rate) implements the Token Bucket algorithm.

import "golang.org/x/time/rate"

// NewLimiter(r Limit, b int) *Limiter
// r (Rate / Limit): tokens refilled per second (steady-state throughput)
// b (Burst / Depth): maximum token capacity of the bucket (spike absorption)
limiter := rate.NewLimiter(rate.Every(100*time.Millisecond), 5) // 10 tokens/sec (r=10), max burst 5 (b=5)
  • Limit() vs Burst() Methods:
    • limiter.Limit() returns the refill rate $r$ (rate.Limit, float64).
    • limiter.Burst() returns the maximum bucket capacity $b$ (int).
  • Why Burst(b) Matters (Execution Latency vs. Inter-arrival Pacing):
    • A rate limiter does not control how long an individual request takes to execute (Execution Latency)—Go servers process requests concurrently across goroutines. Instead, it controls the pacing at which new requests are permitted to enter the gate (Inter-arrival Time).
    • Suppose a limiter refills at 10 tokens/sec (r = 10, or 1 token every 100ms), but its burst size is set to b = 1.
    • Even if the system has been completely idle for 10 minutes, a bucket with capacity 1 can hold at most 1 token (excess tokens overflow and are discarded). If Request A and Request B arrive simultaneously at $t = 0$, Request A consumes the sole token and starts immediately ($0\text{ ms}$ wait), while Request B encounters an empty bucket and is forced to wait $100\text{ ms}$ for the next token refill.
    • Setting b = 5 allows the bucket to accumulate 5 tokens during idle periods, enabling 5 simultaneous requests to enter immediately and concurrently with zero wait time.

(2) Gatekeeper Model: Where Business Logic Executes#

A rate.Limiter does not execute RPCs or database queries itself; it acts strictly as a tollbooth gatekeeper. The actual business logic always executes on the line immediately following Wait(ctx) or Allow().

func (c *Client) CallAPI(ctx context.Context, req Request) (Response, error) {
    // [Step 1: Pass the Tollbooth Gatekeeper]
    // Blocks here until a token is acquired.
    if err := c.limiter.Wait(ctx); err != nil {
        // If context is canceled or deadline would be exceeded, abort without executing business logic!
        return Response{}, err
    }

    // [Step 2: Execute Actual Business Logic]
    // Reaching this line means a token was successfully consumed.
    return c.doActualNetworkRPC(ctx, req)
}

Built-in Optimizations of Wait(ctx): Fast-Fail Deadline & Token Restoration#

The standard rate.Limiter.Wait(ctx) implementation includes two critical context-aware optimizations:

  1. Fast-Fail Deadline Check: Before sleeping, Wait(ctx) checks ctx.Deadline(). If the queue is backed up such that the required wait time for a token (e.g., 5s) exceeds the remaining context deadline (e.g., 2s), Wait(ctx) does not waste 2 seconds waiting—it fails fast immediately without starting a timer (rate: Wait(n=1) would exceed context deadline).
  2. Token Restoration on Cancellation (r.Cancel()): If ctx is canceled (<-ctx.Done()) while a goroutine is waiting for its reserved token timer, Wait(ctx) automatically invokes r.Cancel() to return the reserved token back to the bucket, allowing subsequent goroutines in line to proceed sooner.

(3) Client-Side vs. Server-Side Rate Limiting (Wait vs. Allow)#

Rate limiting should be applied on both clients and servers, but their objectives and method choices are exact opposites.

DimensionClient-Side Rate LimitingServer-Side Rate Limiting
Primary GoalSelf-Throttling & Quota Compliance
Pace outgoing requests so the client avoids 429 bans/cost overruns while processing every single request without dropping (No Drop)
Self-Defense
Protect CPU, memory, and databases from DoS attacks or runaway clients as the last line of defense
Method Usedlimiter.Wait(ctx) (Blocking wait)limiter.Allow() (Non-blocking instant decision)
Behavior on ExcessGoroutine pauses (paces) until a token refills, then sends the requestBlocking on the server would exhaust goroutines and socket memory; excess requests are rejected immediately (HTTP 429 Too Many Requests / gRPC ResourceExhausted)
// [Server-Side Example]: Reject excess traffic immediately using Allow()
func (s *Server) HandleRequest(w http.ResponseWriter, r *http.Request) {
    // Non-blocking check: do not sleep on the server!
    if !s.inboundLimiter.Allow() {
        http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
        return
    }
    // Token consumed -> execute handler business logic
    s.processBusinessLogic(w, r)
}

Practical Tip (Log Throttling): Use if logLimiter.Allow() { log.Printf(...) } inside error loops to prevent disk I/O saturation during outage-induced log storms.

(4) Multi-Tier Rate Limiting (MultiLimiter)#

Real-world APIs rarely enforce a single time-window constraint. Instead, they combine multiple tiers:

  • Short-term limit (Fine-grained spike protection): e.g., at most 2 requests per second to prevent memory spikes.
  • Long-term limit (Aggregate quota protection): e.g., at most 10 requests per minute to enforce billing/quota tiers.

Relying solely on a per-minute limiter (rate.Every(6*time.Second), 10) would allow all 10 requests to slam the server within 0.01s. Relying solely on a per-second limiter (2 req/s) would allow up to 120 requests in a minute, violating the 10 req/min quota by 12x.

The MultiLimiter pattern composes multiple limiters into a single unified RateLimiter interface.

package main

import (
    "context"
    "sort"
    "time"

    "golang.org/x/time/rate"
)

type RateLimiter interface {
    Wait(context.Context) error
    Limit() rate.Limit
}

type multiLimiter struct {
    limiters []RateLimiter
}

func MultiLimiter(limiters ...RateLimiter) *multiLimiter {
    // Key: Sort ascending by Limit() (steady refill rate r).
    // Places the most restrictive limiter (smallest r) at index 0.
    byLimit := func(i, j int) bool {
        return limiters[i].Limit() < limiters[j].Limit()
    }
    sort.Slice(limiters, byLimit)
    return &multiLimiter{limiters: limiters}
}

func (l *multiLimiter) Wait(ctx context.Context) error {
    // Must acquire a token from every limiter in order, starting from the strictest.
    for _, limiter := range l.limiters {
        if err := limiter.Wait(ctx); err != nil {
            return err
        }
    }
    return nil
}

func (l *multiLimiter) Limit() rate.Limit {
    // The overall steady-state rate is bound by the strictest limiter (index 0).
    return l.limiters[0].Limit()
}

MultiLimiter Composition & Execution Mechanics#

type APIConnection struct {
    apiLimiter RateLimiter
}

func Open() *APIConnection {
    // 1. Short-term spike protection: 2 tokens/sec (Limit = 2.0/s), burst 2
    secondLimit := rate.NewLimiter(rate.Every(time.Second/2), 2)
    // 2. Long-term quota protection: 1 token per 6s = 10/min (Limit = 0.166/s), burst 10
    minuteLimit := rate.NewLimiter(rate.Every(time.Minute/10), 10)

    return &APIConnection{
        apiLimiter: MultiLimiter(secondLimit, minuteLimit),
    }
}

func (a *APIConnection) ReadFile(ctx context.Context) error {
    // Gatekeeper: evaluates minuteLimit.Wait(ctx) -> secondLimit.Wait(ctx) in order
    if err := a.apiLimiter.Wait(ctx); err != nil {
        return err
    }
    // Execute actual file read / network RPC business logic
    return nil
}
  1. Internal Sorting Order (minuteLimit -> secondLimit):
    • minuteLimit.Limit() is $10 / 60\text{s} = \mathbf{0.166/s}$, whereas secondLimit.Limit() is $\mathbf{2.0/s}$.
    • Because MultiLimiter sorts ascending by Limit(), the slice is ordered as [0]: minuteLimit (0.166/s), [1]: secondLimit (2.0/s).
  2. How the Two Tiers Cooperate During Wait(ctx):
    • First 10 Requests (Burst Phase): Because minuteLimit has a burst capacity of 10, the first 10 calls pass minuteLimit.Wait(ctx) instantly ($0\text{ s}$ wait). However, the subsequent gate secondLimit.Wait(ctx) has a burst of only 2, forcing those 10 requests to be paced safely at 2 requests per second rather than slamming the backend all at once.
    • 11th Request Onward (Steady Quota Phase): After 5 seconds, all 10 initial burst tokens in minuteLimit are exhausted. From the 11th request onward, index 0 (minuteLimit.Wait(ctx)) governs the gate, permitting exactly 1 request every 6 seconds so the 10 req/min quota is never breached.
  3. Why Sort Ascending by Limit() (Strictest First) and Execute Sequentially (for Loop)?:
    • Evaluating in reverse order (secondLimit before minuteLimit) or evaluating all limiters concurrently in parallel goroutines introduces two critical bugs:
      1. Token Leakage: Suppose both buckets are empty at $t = 5.0\text{s}$ and a request arrives with a $3.0\text{s}$ context deadline. If secondLimit.Wait(ctx) is called first, it waits $0.5\text{s}$ and permanently consumes 1 token from secondLimit at $t = 5.5\text{s}$ (once Wait returns nil, that token is never refunded). Immediately afterward, minuteLimit.Wait(ctx) sees that $5.5\text{s}$ of wait time remains against a $2.5\text{s}$ deadline and aborts with a deadline error. As a result, a doomed request steals and destroys a token from secondLimit without ever executing.
      2. Timing Distortion: Even with an infinite deadline, evaluating secondLimit first causes the request to consume a secondLimit token at $t = 5.5\text{s}$ and then sit blocked at minuteLimit until $t = 11.0\text{s}$. The actual network call fires at $t = 11.0\text{s}$, but secondLimit recorded the event back at $t = 5.5\text{s}$, corrupting short-term burst accounting.
    • By placing the strictest gate (minuteLimit) at index 0 and evaluating sequentially, requests that will be rejected or delayed by the outer long-term quota gate never touch the inner short-term gate until the exact moment ($t = 11.0\text{s}$) they are cleared to execute.

17. Healing Unhealthy Goroutines (Steward & Ward Pattern)#

In long-running server processes and background daemons, individual worker goroutines can become unhealthy—deadlocking on network sockets or database locks, entering livelocks, or terminating unexpectedly. To prevent a Zombie Server state (where process-level health checks pass while internal subsystems are frozen), the Steward (Supervisor) & Ward (Worker) pattern combines context cancellation (context.WithCancel) with heartbeats (Heartbeats) to automatically detect, terminate, and respawn unhealthy goroutines.

(1) Separation of Concerns & Two-Step Healing Lifecycle#

  • Ward (Worker Goroutine): Executes actual business logic while periodically emitting heartbeats (<-chan struct{}) to prove liveness.
  • Steward (Supervisor Goroutine): Performs no business logic itself; its sole responsibility is monitoring a specific Ward’s heartbeat. If no heartbeat arrives within timeout (or if the channel closes prematurely), the Steward executes a strict two-step healing procedure:
    1. [Step 1: Clean Termination (cancelWard())]: Cancels the unhealthy Ward’s context to guarantee the frozen goroutine releases resources and does not leak.
    2. [Step 2: Respawn (startWardInstance())]: Spawns a fresh Ward goroutine and subscribes to its new heartbeat channel.

(2) Isomorphic Signature (startGoroutineFn) & Supervision Trees#

Crucially, the Steward itself emits heartbeats upstream and shares the exact same function signature (startGoroutineFn) as a Ward.

// Shared function signature implemented by both Wards (workers) and Stewards (supervisors)
type startGoroutineFn func(
    ctx context.Context,
    pulseInterval time.Duration,
) (heartbeat <-chan struct{})
  • Hierarchical Composability: Because newSteward returns a startGoroutineFn, a higher-level Steward can supervise another Steward as its Ward, forming a multi-layered, self-healing Supervision Tree (analogous to Erlang/OTP supervisors or Kubernetes Deployment -> ReplicaSet -> Pod controllers).

(3) Canonical newSteward Implementation#

func newSteward(
    timeout time.Duration,
    startWard startGoroutineFn, // Factory function to launch/relaunch the monitored Ward
) startGoroutineFn {
    return func(ctx context.Context, pulseInterval time.Duration) <-chan struct{} {
        heartbeat := make(chan struct{})

        go func() {
            defer close(heartbeat)

            var wardCtx context.Context
            var cancelWard context.CancelFunc
            var wardHeartbeat <-chan struct{}

            startWardInstance := func() {
                // 1. Create an isolated cancellation context for the new Ward instance
                wardCtx, cancelWard = context.WithCancel(ctx)
                // 2. Instruct Ward to pulse at half the Steward's timeout (timeout/2)
                wardHeartbeat = startWard(wardCtx, timeout/2)
            }

            // Launch initial Ward
            startWardInstance()

            // [CRITICAL DETAIL]: Why wrap in an anonymous closure instead of defer cancelWard()?
            // Every time the Ward restarts, cancelWard is reassigned to a brand-new CancelFunc.
            // A closure captures the variable reference so that when the Steward finally exits,
            // it invokes the latest active CancelFunc rather than the first one.
            // (See the Function documentation's defer evaluation section for details.)
            defer func() {
                if cancelWard != nil {
                    cancelWard()
                }
            }()

            pulse := time.NewTicker(pulseInterval)
            defer pulse.Stop()

            watchdog := time.NewTimer(timeout)
            defer watchdog.Stop()

            for {
                select {
                case <-ctx.Done():
                    // Parent context canceled -> defer cancels the active Ward and exits cleanly
                    return

                case <-pulse.C:
                    // Emit Steward's own heartbeat upstream (non-blocking)
                    select {
                    case heartbeat <- struct{}{}:
                    default:
                    }

                case _, ok := <-wardHeartbeat:
                    if !ok {
                        // Case A: Ward closed its heartbeat channel unexpectedly -> heal immediately
                        cancelWard()        // Ensure old resources are cleaned up
                        startWardInstance() // Respawn fresh Ward
                    }
                    // Ward is healthy -> reset watchdog timer
                    if !watchdog.Stop() {
                        select {
                        case <-watchdog.C:
                        default:
                        }
                    }
                    watchdog.Reset(timeout)

                case <-watchdog.C:
                    // Case B: No heartbeat received within timeout (deadlock detected)
                    cancelWard()        // [Step 1: Euthanize] Terminate stuck Ward
                    startWardInstance() // [Step 2: Respawn] Launch fresh Ward
                    watchdog.Reset(timeout)
                }
            }
        }()

        return heartbeat
    }
}

(4) Three Architectural Principles for Production#

  1. The timeout / 2 Pulse Rule:
    • If a Ward pulses at the exact same interval as the Steward’s timeout, even a 1ms CPU scheduling delay will trigger a false positive restart. Configuring pulseInterval = timeout / 2 gives the Ward safe headroom before the watchdog fires.
  2. Parent-Child Context Propagation vs. Isolation (wardCtx, cancelWard = context.WithCancel(ctx)):
    • Top-Down Propagation: Canceling parent ctx (Steward) automatically cancels child wardCtx (Ward). (Explicitly calling defer func() { cancelWard() }() is still required to detach the child reference from the parent’s internal map for GC and to handle non-context exits.)
    • Bottom-Up Isolation: Calling child cancelWard() terminates only the unhealthy Ward while leaving parent ctx (Steward) completely unharmed so it can spawn the replacement.
  3. Top-Down Bootstrapping from main():
    • Calling newSteward(...) does not launch any goroutines; it merely composes and returns a startGoroutineFn closure.
    • Actual execution is triggered top-down like dominoes when the outermost function is invoked in main():
func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    // 1. Assembly phase (no goroutines running yet)
    ward := doWork
    steward := newSteward(4*time.Second, ward)
    superSteward := newSteward(10*time.Second, steward)

    // 2. Initial trigger: invoking superSteward cascades startup top-down:
    // superSteward starts -> launches steward -> launches ward!
    rootHeartbeat := superSteward(ctx, 5*time.Second)

    for range rootHeartbeat {
        // Entire supervision tree is healthy
    }
}