Lesson 7 of 13 · 22m
Calling Upstreams: Retries, Jitter, and Backpressure
Retries only for transient failures on idempotent calls — full jitter, circuit breakers, outbound rate limits, and a fast 503 over an unbounded queue.
Your service calls an upstream that's having a bad evening. Every request blocks for sixty seconds, each holding a goroutine and a pooled connection, and inbound traffic doesn't care — it stacks until your service is having the same bad evening. The wrong mental model: a client Timeout alone is resilience. Timeouts cap the blast radius; they don't stop the blast. Retries, budgets, and backpressure decide whether a sick dependency makes you sick too.
Retry like you mean it
A retry is justified for transient failures — connection refused mid-restart, a 502/503, a 429 with Retry-After. It is a multiplier for everything else. Retrying a 400 fails slowly; retrying a non-idempotent POST without an Idempotency-Key is how you charge a card twice. Stripe built idempotency keys into its API because "just retry it" is a payments bug, not a strategy — accept a client-supplied key, dedupe on it, and retries become safe.
The formula that works: exponential backoff with full jitter:
func callUpstream(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
var resp *http.Response
var err error
delay := 100 * time.Millisecond
for attempt := 0; attempt < 4; attempt++ {
resp, err = client.Do(req.WithContext(ctx))
if err == nil && !isRetryableStatus(resp.StatusCode) {
return resp, nil
}
if resp != nil {
drainClose(resp) // reuse the connection on retried responses
}
if err != nil && !isTransientNetErr(err) {
return nil, err // 4xx, TLS failures, ctx cancellation: don't retry
}
sleep := time.Duration(rand.Int64N(int64(delay))) // full jitter
select {
case <-time.After(sleep):
case <-ctx.Done():
return nil, ctx.Err()
}
delay *= 2
}
return resp, err
}Full jitter — sleep a random duration between zero and the backoff cap — is the variant that prevents retry synchronization; Marc Brooker's "Exponential Backoff And Jitter" on the AWS Architecture Blog (2015) is still the reference. Without jitter, a thousand clients that failed together retry together and fail together again: the thundering herd. And never retry once ctx is done — a canceled caller retrying is a zombie generator.
Budgets, breakers, and self-rate-limits
Retries raise each request's cost; against a dead upstream they amplify outbound volume at the worst possible time. A circuit breaker flips open after consecutive failures and fails fast for a cooldown — sony/gobreaker is the standard small implementation — turning "hang 30s" into "fail in 1ms" so your workers survive the outage.
Rate-limit yourself on the way out too: golang.org/x/time/rate.NewLimiter(rate.Every(20*time.Millisecond), burst) is a token bucket in three lines. It keeps you under a partner's limits and smooths your own bursts so a traffic spike doesn't become an upstream incident you authored.
Then bound concurrency into the dependency: golang.org/x/sync/semaphore.Weighted or a channel-of-N caps how many calls may be in-flight at once. If inbound is unbounded and outbound is unbounded, your process is the queue — memory and goroutines grow until something snaps, and the something is your pod.
Backpressure at the door
When a bounded queue is full, the correct answer is a fast 503 with Retry-After, not a bigger queue. An unbounded queue converts a latency problem into a memory problem; a fast rejection keeps the process alive and tells a well-behaved client exactly when to come back. Load balancers understand 503. Nobody understands a hung socket.
Field notes
http.Client.Timeoutwraps the whole exchange; thehttp.Transportknobs —ResponseHeaderTimeout,TLSHandshakeTimeout,ExpectContinueTimeout— bound the phases separately when one cap isn't enough.- Honor
Retry-Afteron 429/503 — it's the upstream telling you its own budget, in seconds or an HTTP date. - Retries multiply timeouts: 4 attempts × 10s client timeout is 40s worst case. Put the outer
WithTimeouton the request ctx so retries share the caller's deadline.
Try this
Point a retrying client at an httptest.NewServer that returns 503 twice then 200. Verify one success in about three attempts, and log the jittered sleeps — if they march in lockstep across runs, your jitter is broken. Then make the upstream fail forever and measure how fast your breaker opens versus how fast a bare client gives up.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
What is Go? The Language Google Built for Production Engineering
Go is a statically typed, compiled language built at Google in 2009. It compiles to a single binary with no runtime dependency, starts in milliseconds, and handles concurrency through goroutines and channels. Docker, Kubernetes, and Terraform are all written in Go. Here is why.
Go Lang 1.19: Refines Generics and Memory Model
Go 1.19, the latest version of Google’s Go (Golang) programming language, has reached production availability. The update improves recently added generics and debuts an enhanced memory model. With Go Language version 1.19, released August 2, generics development focused on addressing subtle…
One Slow Call, Three Runtimes: How PHP-FPM, Python ASGI and Node Fall Over When a Dependency Takes 200 ms
I put the same 200 ms wait behind PHP-FPM, FastAPI on uvicorn and a plain Node server, then hit each one with 50 concurrent requests. Handled correctly, the async runtimes served 205-211 req/s against FPM's 19.6. One blocking call in the wrong place took both of them down to 4.98, slower than...
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.