Lesson 6 of 9 · 28m
Outbound HTTP and Connection Pooling Are Production Code
Configure http.Client, transports, retries, and pool limits deliberately so downstream dependencies cannot exhaust your service from the inside.
Teams obsess over inbound tuning and then call dependencies with a zero-timeout http.Get. That is how a slow payment provider becomes a self-inflicted denial of service. Outbound HTTP deserves the same seriousness as inbound handling: bounded time, bounded connections, explicit retries, and enough telemetry to see trouble before users do.
http.DefaultClient has no timeout
This is not a nuance; it is a trap:
resp, err := http.Get("https://api.stripe.com/v1/charges")Construct clients with intent:
client := &http.Client{
Timeout: 3 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 20,
MaxConnsPerHost: 50,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 2 * time.Second,
},
}The exact numbers depend on the dependency. The important part is that every number was chosen. MaxConnsPerHost prevents one slow dependency from consuming every socket.
Reuse clients and close bodies
Create one client per dependency configuration and reuse it. Creating a new transport per request defeats pooling and churns sockets. A response body is an ownership transfer:
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10))
return fmt.Errorf("dependency status %d", resp.StatusCode)
}Closing is required. Limited draining before close can improve connection reuse without reading an unbounded error body.
Retries require idempotency and a budget
Retries can rescue transient failure or multiply an outage:
GET /v1/customers/cus_123 usually safe to retry
POST /v1/charges unsafe without Idempotency-KeyUse exponential backoff with jitter, cap attempts, and respect cancellation. Do not retry ordinary validation failures. A deterministic 400 does not become less deterministic when repeated.
Proxy and DNS behavior are transport behavior
Transport owns dialing, proxy selection, TLS configuration, and connection reuse. In service meshes or restricted networks, those concerns may already belong to another layer. Know which layer owns what before adding another one.
Field notes
- Use separate clients when dependencies have different latency budgets.
- Log retry count and dependency name, not just final error. Retried success is still an early warning.
- Watch ephemeral port exhaustion under high churn before blaming the network.
- Do not copy sensitive headers across redirects unless the dependency contract explicitly requires it.
Was this lesson helpful?