Skip to content

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.Timeout wraps the whole exchange; the http.Transport knobs — ResponseHeaderTimeout, TLSHandshakeTimeout, ExpectContinueTimeout — bound the phases separately when one cap isn't enough.
  • Honor Retry-After on 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 WithTimeout on 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.