Retries: A Go HTTP Retry Transport

What it is

A custom http.RoundTripper you plug under your generated OpenAPI client to add safe, policy-driven retries.

Key goals

  • Retry only idempotent verbs (GET, DELETE).
  • Respect app SLOs via per-attempt timeout + caller’s overall deadline.
  • Play nice with servers (honor Retry-After), networks (reuse connections), and observability.

Where it sits

  • You create &http.Client{Transport: RetryTransport{...}} and pass it to your generated client.
  • Non-allowed methods (POST/PUT) bypass retries entirely.

Request body handling (why retries usually fail without this)

  • req.Body is a one-shot stream. After attempt #1, it’s consumed.
  • cloneRequestForRetries:

    • If the body isn’t already rewindable (GetBody == nil), it buffers it once in memory.
    • Sets req.Body to a new reader over that buffer and defines req.GetBody → a function that returns a fresh reader for each attempt.
  • Uses io.NopCloser(bytes.NewReader(buf)) because Body must be an io.ReadCloser; the close is a no-op for in-memory data.

Takeaway: Every attempt sends the full body, reliably.


Cloning per attempt (and why)

  • cloneRequest(origReq.WithContext(attemptCtx)) creates a fresh request each try:

    • Safe to mutate headers (deep-copies the header map).
    • Swaps in a per-attempt context.
    • If GetBody != nil, resets tryReq.Body to a new reader (offset 0).

Reason: Avoid cross-attempt mutations and ensure clean contexts/bodies every time.


Timeouts & cancellation (who’s the boss?)

  • Per-attempt timeout (PerAttemptTimeout):

    • If set, each try runs under context.WithTimeout(req.Context(), PerAttemptTimeout).
    • Cancels that attempt only; then the transport may retry.
  • Caller’s context / http.Client.Timeout:

    • This is the ultimate cap (covers all attempts + backoffs).
    • If it hits, all retries stop immediately.

Rule of thumb: Use PerAttemptTimeout (e.g., 2–5s) for each try; set a caller deadline (e.g., 8–10s) for the end-to-end request.


Why call cancel()?

Any time you create attemptCtx with WithTimeout, you must call cancel() on all exit paths:

  • Frees timers/goroutines → no leaks.
  • Doesn’t affect the parent context.
  • That’s why you see cancel() both on setup errors and right after RoundTrip.

Retry decision logic

  1. Method gate: only methods in Policy.Methods (GET/DELETE) are retryable.
  2. Success path: if no error and status not retryable → return immediately.
  3. Transport errors: retry if ShouldRetryError(err) says it’s transient (timeouts, temporary net errors, connection reset/EOF, etc.).
  4. HTTP status: retry on configured codes (408, 425, 429, 500, 502, 503, 504, etc.).

Delay between attempts

  • If server sends Retry-After (429/503 commonly), honor it (capped by MaxRetryAfter).
  • Else use exponential backoff with full jitter: BaseDelay * 2^attempt (capped by MaxDelay), then randomize in [0, cap].

During the sleep, the code still watches the caller’s context; if canceled, it stops immediately.


Connection reuse (critical for performance)

  • On retryable HTTP responses, the code drains and closes the body before sleeping:

    • Allows keep-alive connections to be reused (no extra TCP handshakes).
    • Prevents pool starvation under errors.

Observability

  • Adds X-Retry-Attempt: <n> (1-based) to each attempt for easy tracing.
  • You can log attempt count, delay, and reason (status vs error).

Defaults that work well

  • Methods: GET, DELETE
  • Max attempts: 3–5 (includes first try)
  • Backoff: base 100–200ms, max 1–3s, full jitter
  • Retryable statuses: 408, 425, 429, 500, 502, 503, 504
  • Respect Retry-After (cap \~30s)
  • Per-attempt timeout: 2–5s
  • Overall deadline: via caller context (or http.Client.Timeout) per endpoint SLO

Quick timeline example

Policy: MaxAttempts=4, PerAttemptTimeout=3s, backoff ≈ 100ms, 200ms, 400ms

  • #1 → 500 → drain → sleep \~100ms
  • #2 → 503 with Retry-After: 1 → drain → sleep 1s
  • #3 → net timeout (3s) → retry → sleep \~200ms
  • #4 → 200 OK → return

If the caller’s deadline is 5s total, retries stop when 5s elapse—no matter what.


Edge notes

  • Large bodies: buffering uses RAM—consider a size limit or spill to temp file if needed.
  • POST/PUT later: only enable if idempotent (e.g., Idempotency-Key) and add them explicitly to Methods.
  • Pair with a Circuit Breaker if a dependency remains unhealthy to avoid hammering it.

Appendix: the full retry.go

The complete transport this page walks through.

package retryhttp

import (
	"bytes"
	"context"
	"crypto/rand"
	"encoding/binary"
	"io"
	"math"
	"net"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type RetryPolicy struct {
	// Attempts includes the initial try; e.g., 3 means 1 try + up to 2 retries.
	MaxAttempts int

	// Methods allowed to be retried (e.g., "GET", "DELETE").
	Methods map[string]struct{}

	// HTTP status codes that should be retried (e.g., 408, 429, 5xx).
	StatusCodes map[int]struct{}

	// Base backoff and max backoff.
	BaseDelay time.Duration
	MaxDelay  time.Duration

	// If Retry-After is present, respect it up to this cap.
	MaxRetryAfter time.Duration

	// Optional per-attempt timeout. 0 means “use request’s context only”.
	// 0 means “no extra per-attempt cap.” In that case, each attempt just uses the original req.Context() deadline/cancellation (or runs unbounded if your context has no deadline).
	PerAttemptTimeout time.Duration

	// Decide whether a transport error is retryable.
	ShouldRetryError func(error) bool
}

func NewDefaultPolicy() *RetryPolicy {
	return &RetryPolicy{
		MaxAttempts: 3,
		Methods:     map[string]struct{}{"GET": {}, "DELETE": {}},
		StatusCodes: map[int]struct{}{
			http.StatusRequestTimeout:          {}, // 408
			425:                                {}, // Too Early (HTTP/2/3 backpressure)
			http.StatusTooManyRequests:         {}, // 429
			http.StatusInternalServerError:     {}, // 500
			http.StatusBadGateway:              {}, // 502
			http.StatusServiceUnavailable:      {}, // 503
			http.StatusGatewayTimeout:          {}, // 504
		},
		BaseDelay:         100 * time.Millisecond,
		MaxDelay:          2 * time.Second,
		MaxRetryAfter:     30 * time.Second,
		PerAttemptTimeout: 5 * time.Second,
		ShouldRetryError:  defaultRetryableError,
	}
}

type RetryTransport struct {
	Base   http.RoundTripper
	Policy *RetryPolicy
}

func NewRetryTransport(base http.RoundTripper, policy *RetryPolicy) *RetryTransport {
	if base == nil {
		base = http.DefaultTransport
	}
	if policy == nil {
		policy = NewDefaultPolicy()
	}
	return &RetryTransport{Base: base, Policy: policy}
}

func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	// If method not allowed for retry, just pass through.
	if _, ok := t.Policy.Methods[strings.ToUpper(req.Method)]; !ok {
		return t.Base.RoundTrip(req)
	}

	// Make body re-readable if present.
	origReq, err := cloneRequestForRetries(req)
	if err != nil {
		return nil, err
	}

	var lastResp *http.Response
	var lastErr error

	for attempt := 1; attempt <= t.Policy.MaxAttempts; attempt++ {
		// Respect caller’s context; bail if canceled.
		if err := req.Context().Err(); err != nil {
			return nil, err
		}

		// Create per-attempt context, if configured.
		attemptCtx := req.Context()
		var cancel func()
		if t.Policy.PerAttemptTimeout > 0 {
			attemptCtx, cancel = context.WithTimeout(req.Context(), t.Policy.PerAttemptTimeout)
		}

		tryReq := cloneRequest(origReq.WithContext(attemptCtx))
		if origReq.GetBody != nil {
			if tryReq.Body, err = origReq.GetBody(); err != nil {
				if cancel != nil {
					cancel()
				}
				return nil, err
			}
		}

		// Add observability.
		tryReq.Header.Set("X-Retry-Attempt", strconv.Itoa(attempt))

		resp, err := t.Base.RoundTrip(tryReq)
		if cancel != nil {
			cancel()
		}

		// Success path.
		if err == nil && !t.shouldRetryStatus(resp.StatusCode) {
			return resp, nil
		}

		// Decide whether to retry.
		shouldRetry := false
		var delay time.Duration

		if err != nil {
			shouldRetry = t.Policy.ShouldRetryError(err)
		} else if t.shouldRetryStatus(resp.StatusCode) {
			shouldRetry = true
			// Drain/close body so the connection can be reused.
			_ = drainAndClose(resp.Body)
			if ra := parseRetryAfter(resp); ra > 0 {
				if ra > t.Policy.MaxRetryAfter {
					ra = t.Policy.MaxRetryAfter
				}
				delay = ra
			}
		}

		if !shouldRetry || attempt == t.Policy.MaxAttempts {
			// return the last observed outcome
			if err != nil {
				return nil, err
			}
			return resp, nil
		}

		// Compute backoff if not set via Retry-After.
		if delay == 0 {
			delay = jitteredBackoff(t.Policy.BaseDelay, t.Policy.MaxDelay, attempt-1)
		}

		timer := time.NewTimer(delay)
		select {
		case <-req.Context().Done():
			timer.Stop()
			if err != nil {
				return nil, err
			}
			return resp, req.Context().Err()
		case <-timer.C:
		}

		lastResp, lastErr = resp, err
	}

	return lastResp, lastErr
}

func (t *RetryTransport) shouldRetryStatus(code int) bool {
	_, ok := t.Policy.StatusCodes[code]
	return ok
}

func cloneRequestForRetries(r *http.Request) (*http.Request, error) {
	// If body already rewindable, use it.
	if r.GetBody != nil || r.Body == nil {
		return r, nil
	}
	// Buffer body to support retries.
	buf, err := io.ReadAll(r.Body)
	if err != nil {
		return nil, err
	}
	_ = r.Body.Close()

	
	r.Body = io.NopCloser(bytes.NewReader(buf))
	r.GetBody = func() (io.ReadCloser, error) {
		return io.NopCloser(bytes.NewReader(buf)), nil
	}
	return r, nil
}

func cloneRequest(r *http.Request) *http.Request {
	// Shallow copy, but copy the Header map.
	cr := new(http.Request)
	*cr = *r
	cr.Header = make(http.Header, len(r.Header))
	for k, v := range r.Header {
		cr.Header[k] = append([]string(nil), v...)
	}
	return cr
}

func drainAndClose(rc io.ReadCloser) error {
	if rc == nil {
		return nil
	}
	_, _ = io.Copy(io.Discard, rc)
	return rc.Close()
}

func parseRetryAfter(resp *http.Response) time.Duration {
	ra := resp.Header.Get("Retry-After")
	if ra == "" {
		return 0
	}
	// seconds
	if secs, err := strconv.Atoi(ra); err == nil && secs >= 0 {
		return time.Duration(secs) * time.Second
	}
	// HTTP-date
	if t, err := http.ParseTime(ra); err == nil {
		d := time.Until(t)
		if d < 0 {
			return 0
		}
		return d
	}
	return 0
}

func jitteredBackoff(base, max time.Duration, attempt int) time.Duration {
	// exponential: base * 2^attempt (capped), then full jitter [0, cap]
	pow := float64(base) * math.Pow(2, float64(attempt))
	capDur := time.Duration(pow)
	if capDur > max {
		capDur = max
	}
	return randBetween(0, capDur)
}

func randBetween(min, max time.Duration) time.Duration {
	if max <= min {
		return min
	}
	// crypto/rand for simplicity; math/rand seeded is fine too.
	var u64 uint64
	_ = binary.Read(rand.Reader, binary.LittleEndian, &u64)
	n := u64 % uint64(max-min)
	return min + time.Duration(n)
}

func defaultRetryableError(err error) bool {
	// Retry on temporary or timeout network errors.
	if ne, ok := err.(net.Error); ok {
		if ne.Timeout()  {
			return true
		}
	}
	// Retry on common transient errors (connection reset/EOF mid-flight).
	msg := strings.ToLower(err.Error())
	if strings.Contains(msg, "connection reset") ||
		strings.Contains(msg, "broken pipe") ||
		strings.Contains(msg, "unexpected eof") {
		return true
	}
	return false
}