Retry with Backoff Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Retry with Backoff runs in O(attempts) time and O(1) space, in Go as in every other language.
- ✓The standard library gives you time.After, time.NewTimer, math/rand and context, which is enough to write this correctly in about twenty lines, and that is the common Go choice.
- ✓Select on ctx.Done() alongside the backoff timer so a cancelled request stops retrying immediately instead of continuing to hammer a dependency for a client that has already disconnected.
- ✓The Go trap: Sleeping with time.Sleep instead of selecting on the context means a cancelled or timed-out request keeps retrying in the background, the client is gone, the deadline has passed, and your service is still generating load on the failing dependency, which is precisely the amplification that turns a partial outage into a full one.
- ✓Timers are cheap and goroutines are cheap, which is exactly why Go services amplify retries so effectively, a naive per-request retry loop across a large fleet multiplies load on a failing dependency by the attempt count with no local symptom.
What Retry with Backoff actually is
Retry with Backoff in Go: what you actually reach for
Go implementation
package retry
import (
"context"
"errors"
"math"
"math/rand"
"net/http"
"time"
)
func fullJitter(attempt int, base, cap time.Duration) time.Duration {
ceiling := time.Duration(math.Min(float64(cap), float64(base)*math.Pow(2, float64(attempt))))
return time.Duration(rand.Int63n(int64(ceiling) + 1))
}
var errPermanent = errors.New("permanent")
func Do(ctx context.Context, attempts int, op func(context.Context) error) error {
var last error
for attempt := 0; attempt < attempts; attempt++ {
// Each attempt gets its OWN deadline.
attemptCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
err := op(attemptCtx)
cancel()
if err == nil {
return nil
}
if errors.Is(err, errPermanent) {
return err // never retried
}
last = err
timer := time.NewTimer(fullJitter(attempt, 200*time.Millisecond, 10*time.Second))
select {
case <-timer.C:
case <-ctx.Done(): // client gone: STOP, do not keep loading the dependency
timer.Stop()
return ctx.Err()
}
}
return last
}
// http.Client has NO default timeout: without one, an attempt can hang
// forever and the attempt cap never fires.
var client = &http.Client{Timeout: 3 * time.Second}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(attempts)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Retry with Backoff?
The standard library gives you time.After, time.NewTimer, math/rand and context, which is enough to write this correctly in about twenty lines, and that is the common Go choice. github.com/cenkalti/backoff/v4 is the established library when you want named strategies and a Retry helper. context.Context is the piece that makes a Go retry loop correct rather than merely functional.
What is the most common Go mistake when implementing Retry with Backoff?
Sleeping with time.Sleep instead of selecting on the context means a cancelled or timed-out request keeps retrying in the background, the client is gone, the deadline has passed, and your service is still generating load on the failing dependency, which is precisely the amplification that turns a partial outage into a full one. Second, http.Client has NO default timeout, so an attempt can hang indefinitely and the attempt cap never fires; set Timeout on the client or use a per-attempt context. Third, a response body that is not closed leaks a connection on every retry.
How does Retry with Backoff actually perform in Go?
Timers are cheap and goroutines are cheap, which is exactly why Go services amplify retries so effectively, a naive per-request retry loop across a large fleet multiplies load on a failing dependency by the attempt count with no local symptom. Cap attempts, jitter the delay, and put a circuit breaker in front. Worst-case latency remains the sum of attempt timeouts plus delays and must fit the deadline in the context. Time complexity is O(attempts) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.