Retry Transient Failures in Go With Exponential Backoff and Jitter
Build a Go retry helper that only retries 429 and 5xx errors, adds full jitter to avoid thundering herds, and respects context.Context cancellation between attempts. After this, flaky upstream calls recover cleanly without hammering a struggling API.
Retrying failed HTTP calls in a tight for loop makes outages worse. And retrying at fixed 100 ms intervals without jitter causes every client to wake up at the exact same millisecond—slamming a recovering upstream API with a synchronized thundering herd.
A production-ready retry helper in Go does three things: it only retries transient failures (429, 5xx, and transport errors), backs off exponentially with full jitter, and aborts immediately if ctx.Done() fires while sleeping.
Skip ahead
Want the copy-paste retry loop? Jump to doWithRetry or the status code retry table.
Exponential backoff with full jitter and context
Notice how math/rand/v2 picks a random sleep between 0 and baseDelay << attempt, and time.NewTimer pairs with select so canceled requests do not stay asleep:
package main
import (
"context"
"errors"
"fmt"
"math/rand/v2"
"net/http"
"net/http/httptest"
"sync/atomic"
"time"
)
type statusError struct{ code int }
func (e statusError) Error() string { return fmt.Sprintf("http %d", e.code) }
func shouldRetry(err error) bool {
var se statusError
if errors.As(err, &se) {
return se.code == http.StatusTooManyRequests || se.code >= 500
}
return true
}
func doWithRetry(ctx context.Context, maxAttempts int, baseDelay time.Duration, fn func() error) error {
var err error
for attempt := range maxAttempts {
if err = fn(); err == nil {
return nil
}
if !shouldRetry(err) || attempt == maxAttempts-1 {
return err
}
ceil := baseDelay << attempt
wait := rand.N(ceil + 1)
timer := time.NewTimer(wait)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
return err
}
func main() {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := calls.Add(1)
if n < 3 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}))
defer srv.Close()
err := doWithRetry(context.Background(), 4, 10*time.Millisecond, func() error {
resp, err := srv.Client().Get(srv.URL)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return statusError{code: resp.StatusCode}
}
return nil
})
fmt.Printf("attempts=%d err=%v\n", calls.Load(), err)
err400 := doWithRetry(context.Background(), 4, 10*time.Millisecond, func() error {
return statusError{code: http.StatusBadRequest}
})
fmt.Printf("non_retryable=%v\n", err400)
}
Output on Go 1.27:
$ go run .
attempts=3 err=<nil>
non_retryable=http 400
The transient 503 succeeds on the third attempt, while the 400 Bad Request fails fast on attempt 1 without wasting retries.
Which failures should you retry?
| Failure type | Retry? | Why |
|---|---|---|
429 Too Many Requests |
Yes (respect Retry-After if present) |
Rate limit is temporary; backing off lets quota refill |
502, 503, 504, network EOF/reset |
Yes (if idempotent) | Upstream deploy, brief overload, or dropped socket |
400, 401, 403, 404, 422 |
No | Client bug or missing resource; retrying wastes time and quota |
context.Canceled / DeadlineExceeded |
No | Caller already gave up; stop immediately |
💡 Tip
Cap the backoff ceiling (for example min(baseDelay << attempt, maxDelay)) so high attempt counts do not overflow time.Duration or sleep for minutes when the caller's request timeout is 5 seconds.
Common mistakes
- Retrying non-idempotent
POSTrequests blindly: If the server processed your charge or created the record before dropping the connection, retrying creates duplicates unless the API accepts an idempotency key. - Using
time.Sleep(wait)instead oftime.NewTimer+select:time.Sleepignores context cancellation, keeping goroutines blocked long after an incoming HTTP request was canceled. - Forgetting
resp.Body.Close()between attempts: Leaving failed response bodies unclosed leaks TCP connections fromhttp.DefaultTransport.
⚠ Warning
Never retry context.DeadlineExceeded or context.Canceled returned by fn(). Check errors.Is(err, context.Canceled) and errors.Is(err, context.DeadlineExceeded) before retrying so canceled calls exit right away.
What happens if you skip this
Without jitter and status filtering, a brief 2-second upstream hiccup turns into a self-inflicted DDoS from thousands of synchronized retries—and bad 400 requests sit in retry loops burning worker capacity.
Related course: Go Advanced.
About
Build a Go retry helper that only retries 429 and 5xx errors, adds full jitter to avoid thundering herds, and respects context.Context cancellation between attempts. After this, flaky upstream calls recover cleanly without hammering a struggling API.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.