HTTP Retry With Exponential Backoff
Retry idempotent HTTP requests on server errors and throttling responses, backing off between attempts and honouring context cancellation.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.