Backend Performance··2 min read

Debugging Linux TCP TIME_WAIT Socket Exhaustion Under 12,000 Outbound Webhook Calls Per Minute

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Debugging Linux TCP TIME_WAIT Socket Exhaustion Under 12,000 Outbound Webhook Calls Per Minute

When CPU Is 14% But Every Outbound HTTP Call Fails

During a surge of 12,000 outbound webhook deliveries per minute, our Go worker pods suddenly began failing with:

dial tcp: connect: cannot assign requested address

Node CPU was at 14% and memory was flat. Running ss -s inside the container namespace revealed the root cause immediately: 28,210 TCP sockets were sitting in TIME_WAIT.


1. Why Default Go http.DefaultTransport Leaks Ephemeral Ports

By default, Linux allocates local ephemeral ports from 32768 to 60999 (28,232 ports). When a connection closes actively, the kernel holds that 4-tuple in TIME_WAIT for 60 seconds to catch delayed packets.

In Go, http.DefaultTransport sets MaxIdleConnsPerHost: 2. Worse, if any handler does not fully read resp.Body before calling resp.Body.Close(), Go cannot reuse the keep-alive TCP socket and closes it immediately after every request.


2. Fixing Go HTTP Keep-Alive and Body Draining

We replaced the default transport with a shared, tuned http.Client and enforced bounded body draining on every webhook response:

var WebhookHTTPClient = &http.Client{
    Timeout: 10 * time.Second,
    Transport: &http.Transport{
        MaxIdleConns:          1024,
        MaxIdleConnsPerHost:   128,
        MaxConnsPerHost:       256,
        IdleConnTimeout:       90 * time.Second,
        TLSHandshakeTimeout:   5 * time.Second,
        ExpectContinueTimeout: 1 * time.Second,
    },
}

// Always drain up to 4KB before closing so Go returns the TCP socket to the idle pool
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()

3. Expanding Linux Ephemeral Port Range and tcp_tw_reuse

For destinations that explicitly send Connection: close, we also widened the Linux ephemeral port range and enabled safe timestamp-backed tcp_tw_reuse:

net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.tcp_tw_reuse = 1

Active TIME_WAIT sockets dropped from 28,210 to under 420, and TLS handshake CPU overhead fell by 64%.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles