HTTP Retry With Exponential Backoff

Retry idempotent HTTP requests on server errors and throttling responses, backing off between attempts and honouring context cancellation.

GoResilience

Code

gosnippet
33 lines
package httpx

import (
	"context"
	"net/http"
	"time"
)

func Retry(ctx context.Context, client *http.Client, req *http.Request, attempts int) (*http.Response, error) {
	var lastErr error
	delay := 100 * time.Millisecond
	for i := 0; i < attempts; i++ {
		resp, err := client.Do(req.WithContext(ctx))
		if err == nil {
			if resp.StatusCode < 500 && resp.StatusCode != http.StatusTooManyRequests {
				return resp, nil
			}
			resp.Body.Close()
		} else {
			lastErr = err
		}
		select {
		case <-ctx.Done():
			return nil, ctx.Err()
		case <-time.After(delay):
		}
		delay *= 2
	}
	if lastErr != nil {
		return nil, lastErr
	}
	return nil, context.DeadlineExceeded
}

How it works

HTTP Retry With Exponential Backoff reduces to the function Retry.

Iteration happens inside for i := 0; i < attempts; i++ — everything outside it runs once.

Applying it

Entry signature: func Retry(ctx context.Context, client *http.Client, req *http.Request, attempts int) (*http.Response, error)

Retry is the public entry point; everything else in the file exists to support it.

Statements that matter

return nil, ctx.Err()

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Every import resolves inside the standard library — `context`, `net/http`, `time`. The file defines `Retry` at load time.