Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Cloud Native 32 min read

From 1,200 to 90,000 Goroutines: Postmortem of a Go Cloud-Native Service Runaway

This article dissects a Go cloud-native service incident where goroutines surged from 1,200 to 90,000 due to downstream 429 errors, unbounded concurrency, and missing backpressure, causing OOM kills and latency spikes. It presents evidence-based debugging, bounded worker pools, retry budgets, graceful shutdown patterns, and verification drills to prevent recurrence.

Evidence Boundary: Separating Facts, Hypotheses, and Fixes

The article is based on a production incident record from September 2024. A Go data-sync service running on Kubernetes with 8 instances saw goroutines climb from ~1,200 to 90,000, memory rise from ~1.1 GB to 3.8 GB, three instances OOMKilled, business P99 latency jump from 80 ms to 25 s, some new connections receive 502, and a third-party HTTP API returning 429 for ~40 minutes. The raw record lacks pprof profiles, monitoring screenshots, or raw logs. The author explicitly separates known facts, hypotheses to verify, and recommended implementations, avoiding writing correlation as confirmed root cause.

Summary: CPU Isn't Necessarily High During a Runaway

The most dangerous class of Go service failures isn't necessarily CPU saturation or process exit. More commonly, downstream slowdown or rate-limiting lengthens task execution time; ingress traffic keeps arriving; retries, message prefetch, or unbounded go func() have no ceiling. Tasks move from queue to goroutine, to memory, connections, and tail latency, finally manifesting as 502 or OOM.

A reliable fix isn't "restart and recover" but a verifiable control loop:

Preserve scene → Build evidence chain → Find growth loop → Set task budgets and backpressure → Correctly drain and take offline → Controlled drills verify recovery

The article targets engineers running Go HTTP/gRPC services that consume messages, call third-party APIs, and deploy on Kubernetes. The goal isn't a fixed parameter but a system design method that maintains boundaries when downstream fails.

1. Incident Scene: Distinguishing Facts, Inferences, and Root Causes

The author presents a three-column table mapping recorded phenomena, supported judgments, and missing evidence:

Goroutine rapid rise → Many execution units waiting, blocked, or not exiting → Missing: creation paths, blocking stacks, before/after profile diff.

Downstream continuous 429 → Downstream rate-limiting, retry and queue risk rising → Missing: QPS, 429 ratio, Retry-After, retry counts.

P99 degradation and 502 → Request handling capacity dropping, some proxy layer returning errors → Missing: gateway/Ingress/app/upstream timeout and connection-refusal logs.

Pod OOMKilled → Some container termination involved memory exhaustion → Missing: actual limit, working set, RSS, node events, OOM logs.

A plausible but unproven conclusion: "8 workers stuck on 429 produced 90,000 goroutines." If the system truly had only 8 fixed workers with no other goroutine creation points, a 30-second wait alone cannot create that scale. At least one amplifier must exist: per-message goroutine spawn, failure requeue, consumer continuous prefetch, recursive retry, unbounded fan-out, or background task leak.

Memory conclusions also need caution. "Instance 8G" may refer to node spec, request, limit, or deployment impression. A single 3.8 GB snapshot doesn't explain OOM; Go heap, goroutine stacks, network buffers, mmap, page cache, and other container processes all affect the container memory view.

Failure growth loop and control points
Failure growth loop and control points

Failure Growth Loop and Control Points

Root Cause Confirmation Matrix: Making Troubleshooting Falsifiable

Postmortem shouldn't stop at "maybe." Put each hypothesis, evidence, and corresponding fix in one table to make investigation convergent.

Hypothesis: Unbounded goroutine per message → Priority evidence: goroutine profile creation stacks; inflight vs message rate → Fix direction: fixed worker pool, bounded queue, ingress rejection.

Hypothesis: 429 retry without cancellation propagation → Priority evidence: traces, retry metrics, HTTP request stacks → Fix direction: context, total deadline, limited attempts.

Hypothesis: Consumer continuous prefetch → Priority evidence: lag, unacked message count, consumer client metrics → Fix direction: pause/resume, lower prefetch, delay queue.

Hypothesis: Task backlog drives OOM → Priority evidence: coaxial timeline of working set/RSS/heap/queue → Fix direction: concurrency boundaries, memory budget, stress testing.

Hypothesis: 502 from drain or proxy timeout → Priority evidence: Ingress/gateway logs, connection errors, deploy events → Fix direction: reasonable timeouts, drain before closing listener.

Minimal Evidence Chain: What to Preserve On-Site

Preserve scene first, then consider restart and scale. For Go services, collect at least three goroutine profiles: pre-incident baseline, peak during incident, post-recovery. Stack categories and growth paths are more valuable than a single runtime.NumGoroutine().

# Expose pprof only in safe, authenticated, or temporary debug channels.
curl -sS 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=2' > goroutine.txt

kubectl describe pod <pod> -n <namespace>
kubectl get events -n <namespace> \
  --field-selector involvedObject.name=<pod> --sort-by=.lastTimestamp

Align on a single timeline: ingress rate, completion rate, queue depth, in-flight tasks, 429s, retry counts, connection counts, working set, RSS, Go heap, and log throughput. Little's Law helps understand capacity: if 100 tasks/sec arrive and average latency is 30 seconds, ~3,000 tasks are in-flight or queued. It's not a goroutine formula, but shows "service time grows, ingress doesn't drop" inevitably causes backlog.

2. First Line of Defense: Tasks Must Have Budgets, Not Just Retries

External calls must exit within budget when downstream is unavailable. A task needs at least four layers of constraints:

Call-chain context → Prevents tasks continuing after client disconnect or service termination.

Total deadline → Prevents multiple attempts turning one task into infinite wait.

Per-call timeout → Prevents DNS, connect, read-response phases blocking indefinitely.

Limited attempts with jitter → Prevents multiple instances retrying simultaneously, creating a recovery traffic spike. http.Client.Timeout is a fallback for HTTP calls, not a cancellation mechanism. The caller's context must interrupt in-flight requests and backoff waits; http.Client and Transport should be built once at startup and reused.

Correct Semantics of 429: Never Retry Before the Server Allows

When downstream returns 429, it signals "continuing requests will make me worse." Retry strategy must follow this order:

Honor valid Retry-After header first, never retry earlier.

If no valid header, use capped exponential backoff with full jitter.

When wait exceeds synchronous worker budget, return a classifiable deferred result to be scheduled by a delay queue or message system.

All waits obey total deadline and service-level cancellation.

The example below targets safely retryable GET only. For POST or external side effects, idempotency keys or server-side idempotency guarantees are required; client network errors don't mean the server didn't execute.

package upstream

import (
    "context"
    "errors"
    "fmt"
    "math/rand/v2"
    "net/http"
    "strconv"
    "strings"
    "time"
)

const (
    maxAttempts   = 3
    baseDelay     = 200 * time.Millisecond
    maxWorkerWait = 5 * time.Second
)

// RetryDeferred tells the scheduler to retry no earlier than After.
// It must not be fed back into the same immediate retry loop.
type RetryDeferred struct {
    After time.Duration
}

func (e *RetryDeferred) Error() string {
    return "upstream retry deferred: " + e.After.String()
}

func Fetch(ctx context.Context, client *http.Client, url string) (*http.Response, error) {
    for attempt := 0; attempt < maxAttempts; attempt++ {
        if err := ctx.Err(); err != nil {
            return nil, err
        }
        req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
        if err != nil {
            return nil, err
        }
        resp, err := client.Do(req)
        if err == nil && !retryableStatus(resp.StatusCode) {
            return resp, nil // caller owns and closes resp.Body
        }
        if resp != nil && resp.Body != nil {
            _ = resp.Body.Close() // release the retry-path response body
        }
        if attempt == maxAttempts-1 {
            if err != nil {
                return nil, fmt.Errorf("upstream request: %w", err)
            }
            return nil, fmt.Errorf("upstream returned %d after %d attempts", resp.StatusCode, maxAttempts)
        }
        delay := fullJitter(attempt)
        if resp != nil && resp.StatusCode == http.StatusTooManyRequests {
            if d, ok := parseRetryAfter(resp.Header.Get("Retry-After"), time.Now()); ok {
                if d > maxWorkerWait {
                    return nil, &RetryDeferred{After: d}
                }
                delay = d
            }
        }
        if err := wait(ctx, delay); err != nil {
            return nil, err
        }
    }
    return nil, errors.New("unreachable")
}

func retryableStatus(code int) bool {
    // 501/505 generally indicate a permanent protocol/capability mismatch.
    return code == http.StatusTooManyRequests || code == http.StatusInternalServerError ||
        code == http.StatusBadGateway || code == http.StatusServiceUnavailable ||
        code == http.StatusGatewayTimeout
}

func fullJitter(attempt int) time.Duration {
    cap := min(baseDelay<<attempt, maxWorkerWait)
    return time.Duration(rand.Int64N(int64(cap) + 1))
}

func wait(ctx context.Context, d time.Duration) error {
    t := time.NewTimer(d)
    defer t.Stop()
    select {
    case <-ctx.Done():
        return ctx.Err()
    case <-t.C:
        return nil
    }
}

func parseRetryAfter(v string, now time.Time) (time.Duration, bool) {
    v = strings.TrimSpace(v)
    if seconds, err := strconv.Atoi(v); err == nil && seconds >= 0 {
        return time.Duration(seconds) * time.Second, true
    }
    if when, err := http.ParseTime(v); err == nil && when.After(now) {
        return when.Sub(now), true
    }
    return 0, false
}

Callers must use errors.As(err, &deferred) to identify RetryDeferred and persist it as a "retry after now + deferred.After " task; feeding it back into immediate Submit recreates a retry storm. In high-concurrency HTTP/1.1 scenarios sensitive to connection reuse, read and discard response body within a clear size limit before closing; don't read untrusted response bodies unboundedly.

3. Second Line of Defense: Bounded Workers and Service-Level Cancellation

Unbounded queues turn latency problems into memory problems; unbounded go func() turns them into goroutine, scheduling, and memory problems. The service must explicitly answer: when capacity is insufficient, where does new work stop?

The pool below has three boundaries: fixed worker count, bounded task queue, service root context. Tasks are constrained by per-task deadline and receive cancellation when service begins termination.

type Pool struct {
    root context.Context
    jobs chan Task
    wg   sync.WaitGroup
    done chan struct{}
}

func NewPool(root context.Context, workers, capacity int, handle func(context.Context, Task)) *Pool {
    p := &Pool{root: root, jobs: make(chan Task, capacity), done: make(chan struct{})}
    p.wg.Add(workers)
    for i := 0; i < workers; i++ {
        go func() {
            defer p.wg.Done()
            for task := range p.jobs {
                taskCtx, cancel := context.WithTimeout(p.root, 12*time.Second)
                handle(taskCtx, task)
                cancel()
            }
        }()
    }
    go func() { p.wg.Wait(); close(p.done) }()
    return p
}

func (p *Pool) Submit(task Task) error {
    select {
    case <-p.root.Done():
        return context.Cause(p.root)
    case p.jobs <- task:
        return nil
    default:
        return ErrOverloaded
    }
}

// The owner must first stop all Submit callers, then close the pool once.
func (p *Pool) CloseAndWait(ctx context.Context) error {
    close(p.jobs)
    select {
    case <-p.done:
        return nil
    case <-ctx.Done():
        return ctx.Err()
    }
}

The example omits Task, ErrOverloaded, and mutex state definitions; the focus is lifecycle: the service's root context cancels during draining, allowing in-flight HTTP calls to exit; stop all producers before closing jobs to avoid send-on-closed-channel. Real projects usually encapsulate this protocol in a component rather than letting multiple handlers manipulate channels directly.

Queue-full business semantics must be explicitly defined: HTTP ingress returns 429/503; message consumers pause or reduce pull rate; offset/ack only committed after processing semantics complete; work exceeding synchronous budget goes to delay queue, dead-letter queue, or manual handling path. Concurrency value isn't a "best practice of 8 workers" but derived from downstream quota, instance count, task latency, peak traffic, SLO, and stress tests.

4. Third Line of Defense: Probes Express State, Not Replace Traffic Governance

Three probe endpoints with distinct responsibilities:

/livez → Answers: can the process execute basic logic? → Must NOT probe DB, third-party APIs, queue pressure.

/readyz → Answers: is this instance suitable for new traffic now? → Must NOT replace rate-limiting or cancel in-flight requests.

/startupz → Answers: has local config and initialization completed? → Must NOT judge runtime dependency real-time availability.

Liveness failure triggers restart; readiness failure removes Pod from regular Service ready endpoints; startup probe success suppresses regular liveness/readiness probes. Readiness failure does not auto-cancel in-flight requests, so it's not a backpressure mechanism.

startupProbe:
  httpGet: { path: /startupz, port: 8080 }
  periodSeconds: 5
  failureThreshold: 12
livenessProbe:
  httpGet: { path: /livez, port: 8080 }
  periodSeconds: 10
  timeoutSeconds: 2
  failureThreshold: 3
readinessProbe:
  httpGet: { path: /readyz, port: 8080 }
  periodSeconds: 5
  timeoutSeconds: 2
  failureThreshold: 2
terminationGracePeriodSeconds: 40

Don't synchronously db.Ping or call third-party APIs on every /readyz call. Shared dependency transient fluctuations could cause all Pods to drain simultaneously. Better signals: local init complete, service not draining, key local queues not persistently saturated. If service cannot respond correctly when DB fails, combine local state with timeout, cache, stable window, and business error rate. runtime.NumGoroutine() suits trend diagnosis and alert input, not as sole readiness gate. Focus on relative baseline deviation, growth rate, and actual blocking stacks in profiles.

5. Fourth Line of Defense: Graceful Termination Must "Drain First, Then Close"

Calling Shutdown immediately on SIGTERM is better than hard exit, but brief 502s may still occur: app stops accepting new connections while EndpointSlice, Ingress, or external LB haven't finished drain propagation.

Pod graceful termination sequence
Pod graceful termination sequence

Correct order: mark instance as draining, pause new task acquisition, wait for measured drain propagation window on real link, then close HTTP/gRPC listeners and finish workers. preStop, drain wait, in-flight requests, message processing, offset/ack, and telemetry flush all count toward terminationGracePeriodSeconds; they cannot each consume the full 40 seconds independently.

func shutdown(srv *http.Server, consumer Consumer, pool *Pool, drain func()) {
    sigCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
    defer stop()
    <-sigCtx.Done()

    drain()           // /readyz starts failing, stop new Submit
    consumer.Pause()  // must guarantee unfinished messages can be redelivered per client semantics

    // Config value comes from measured Service → EndpointSlice → Ingress/LB publish drill.
    timer := time.NewTimer(5 * time.Second)
    <-timer.C

    ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        log.Printf("http graceful shutdown: %v", err)
    }
    if err := pool.CloseAndWait(ctx); err != nil {
        log.Printf("worker shutdown: %v", err)
    }
    consumer.Close()
}

WebSocket, hijacked connections, and long-lived streaming RPCs need extra connection registry, termination notice, and deadline; http.Server.Shutdown doesn't handle all upgraded connections. The 5 seconds in the example isn't universal; it emphasizes "drain propagation takes time" and must be configured after measuring the real cluster's publish path.

6. OOM, Connections, and Logs: Explain with Timelines, Not Single Metrics

OOMKilled

is a symptom, not root cause. Recommended investigation order: confirm Pod Last State, exit code, events, node logs; align container working set, RSS, Go heap, goroutine, queue, log throughput; then use heap profile to find allocation sources, goroutine profile to find live tasks, finally correlate connection counts, request bodies, caches, mmap, and file descriptors.

Several common claims need correction:

Since Go 1.23, modules using new timer semantics allow unreferenced tickers to be GC-collected; Stop remains the explicit lifecycle operation to end known periodic tasks, and referenced tickers won't stop themselves.

Default per-host idle connection pool size is 2, not equal to active connection limit, nor does it equal connection leak; whether to tune depends on protocol, concurrency, handshake latency, and downstream capacity.

Uncontrolled error logging under high error rates amplifies I/O, CPU, and storage pressure. Aggregate and rate-limit repeated errors, preserving correlatable error categories and trace context.

7. Two Foundational Capabilities: Reliable Events and Observability

Transactional Outbox addresses the reliability gap "business transaction committed but event not yet delivered": business data and outbox record commit in same transaction; relay delivers outside transaction; consumer stays idempotent. It doesn't handle 429 or limit goroutines. Multi-instance relay using FOR UPDATE SKIP LOCKED should claim records and set lease in short transaction; update status with claim token after send; lease timeout allows retry. Don't query normally, release lock, then slowly send assuming exclusive ownership.

Observability must let three signals correlate: Metrics detect P99, 429, queue, inflight, goroutine, memory, rejection counts; Traces locate which request, which retry, which downstream stage took time; Structured logs explain error classification and rate-limiting decisions. Don't put high-cardinality fields like order ID, user ID, full URL into Prometheus labels; details belong in logs and traces.

8. Deployment Checklist: Deliver Boundaries with the Artifact

At image and Deployment level, at minimum verify:

Process runs as non-root user; base image matches CGO/runtime library requirements.

Requests/limits come from stress tests and capacity model, not "defaults are enough".

Debug endpoints like pprof have network isolation, auth, or temporary enable mechanism.

Deployment maxUnavailable, maxSurge, and PodDisruptionBudget match fault-tolerance capacity.

Service-level root context, HTTP/gRPC deadlines, connection pools, worker counts, queue capacities are all configurable and observable.

Practice drain and connection termination on real Service, EndpointSlice, Ingress/LB path.

Containerization isn't just putting a binary in an image; it means resource, termination, traffic, and debug boundaries ship with the application.

9. Acceptance: Prove the Fix with Three Drills, Not Wait for Next Incident

Drill 1: Reproduce Growth Conditions

In staging or isolated stress environment, use mock downstream returning continuous 429 with injected latency, ingress sustaining near-incident traffic. Record ingress, completion, queue, inflight, goroutine, retries, connections, memory, error codes. Goal: verify growth loop is observed, not to crush the environment.

Drill 2: Verify Boundaries and Recovery

Cancel caller context, confirm HTTP calls and backoff waits exit promptly; fill queue, confirm ingress fast-rejects or consumer pauses; stop injecting 429, confirm backlog drains within target window, outbound concurrency never exceeds budget.

Drill 3: Verify Pod Lifecycle

Keep one instance continuously overloaded, confirm readiness drains and liveness doesn't mis-restart due to external API fluctuation; rolling delete Pod, confirm no significant connection failures during drain window, unacked tasks re-delivered or persisted per contract; check events and container metrics, confirm no sustained memory growth.

Bounded concurrency → Active outbound calls and workers never exceed configured value; queue full rejects or slows within target time.

Cancellation effective → Requests and backoffs exit within deadline; similar blocking stacks don't keep growing.

Rate-limit friendly → Valid Retry-After not broken early; deferred tasks don't re-enter immediate retry.

Recovery capability → After downstream recovers, backlog returns to baseline within target window, P99 reverts to SLO.

Clean takedown → Drain before closing listener; no erroneous ack; long connections have explicit strategy.

Memory boundary → Stress peak below limit with measured headroom, no sustained growth or OOM.

Conclusion: Reliability Comes from Verifiable Boundaries

Facing goroutine explosion, the most dangerous move is quickly attributing it to a familiar label: connection leak, Ticker, HTTP default config, or "downstream slow." They may be local phenomena but don't necessarily explain the entire growth loop.

A reliable postmortem must answer: where tasks are created, where they wait, why cancellation and backpressure didn't block growth, why container was killed. A reliable retrofit must solidify answers into executable boundaries: tasks cancellable, retries schedulable, concurrency capped, ingress backpressures, Pod drains correctly, faults drillable. Achieve these, and the service moves from "temporarily normal after restart" to "still controllable under same failure."

References

Go: Context

Go 1.23 Release Notes (Timer and Ticker semantics)

Go: net/http standard library docs

Kubernetes: Container Probes

Kubernetes: Pod Termination

Kubernetes: Resource Requests and Limits

PostgreSQL: SELECT with

SKIP LOCKED
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Cloud-NativeObservabilityKubernetesGoConcurrency ControlGoroutineGraceful ShutdownRetry Strategy

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion