Gin in the wider system · 7 MIN READ
Retrying upstream calls from Gin: only when safe, jittered backoff, a retry budget and a circuit breaker
Wrap upstream calls in a retry policy that respects idempotency, Retry-After and a shared budget, and use a circuit breaker so Gin answers 503 quickly while a dependency is down.
A retry turns a transient failure into a success and a persistent failure into extra load at the worst possible moment. Whether a retry helps depends on three questions: is it safe to send the request twice, is the failure likely to clear soon, and how much extra traffic is the fleet already sending. This lesson builds the client side of those answers behind a Gin handler, with a seeded random source and an injected clock so every wait is reproducible.
gin · A MAP OF THE IDEA
- Check idempotency
- Back off with jitter
- Spend the retry budget
- Trip the breaker
Useful when
- Transient blips are absorbed before the client notices.
- An outage gets fast 503s instead of queued, doomed attempts.
Watch out
- Retries at several layers multiply load; retry at one.
- Count only transport errors and 5xx as breaker failures.
- A request body must be replayable through GetBody to retry it.
Implementation & operation cost: A few hundred lines of policy code or a reviewed library, per-upstream state, and metrics for attempts, budget refusals and breaker transitions; thresholds need tuning against real traffic.
Which requests and which failures may be retried
RFC 9110 defines GET, HEAD, OPTIONS, TRACE, PUT and DELETE as idempotent: sending one twice has the same intended effect as sending it once. POST and PATCH are not, and a timeout is ambiguous, because the first attempt may have committed and only the response was lost. Retrying such a request can create a second order or a second charge. A client may retry a POST only when the upstream honors an Idempotency-Key and the client resends the same key on every attempt; the idempotency-keys lesson builds that server side. Worth retrying: connection errors, 502, 503, 504 and 429. Not worth retrying: other 4xx, which will fail again identically, and usually 500, which is often a deterministic bug. Retry at one layer only, ideally the one closest to the failing dependency; the cache-stampede lesson in the Go course shows how retries stacked at several layers multiply load.
Backoff, Retry-After, a budget and a breaker in one client
The upstream is a scripted RoundTripper, and the injected clock's Sleep only advances time, so the program runs in milliseconds and prints the same waits on every run. Jitter comes from math/rand/v2 with fixed PCG seeds. Eight client requests walk through a flaky success, a POST without and with an Idempotency-Key, upstream throttling with Retry-After, an outage that first empties the retry budget and then opens the breaker, a request rejected while the breaker is open, and the half-open probe that closes it.
package main
import (
"errors"
"fmt"
"io"
"math/rand/v2"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
// fakeClock is the injected clock: Sleep advances time instead of blocking.
type fakeClock struct{ now time.Time }
func (c *fakeClock) Now() time.Time { return c.now }
func (c *fakeClock) Sleep(d time.Duration) { c.now = c.now.Add(d) }
// scripted plays the upstream: each call takes the next step of the script.
type scripted struct {
script []string // "200", "503", "429:2" (status:Retry-After)
calls int
}
func (s *scripted) RoundTrip(req *http.Request) (*http.Response, error) {
s.calls++
step := "200"
if len(s.script) > 0 {
step, s.script = s.script[0], s.script[1:]
}
code, after, _ := strings.Cut(step, ":")
status, _ := strconv.Atoi(code)
h := http.Header{}
if after != "" {
h.Set("Retry-After", after)
}
return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader("{}")), Request: req}, nil
}
type state int
const (
closed state = iota
open
halfOpen
)
// Breaker opens after Threshold consecutive failures, stays open for
// Cooldown, then lets exactly one probe through.
type Breaker struct {
mu sync.Mutex
Clock *fakeClock
Threshold int
Cooldown time.Duration
state state
failures int
openedAt time.Time
probing bool
}
// Allow reports whether a call may go out and, if not, when to try again.
func (b *Breaker) Allow() (time.Duration, bool) {
b.mu.Lock()
defer b.mu.Unlock()
if b.state == open {
if wait := b.openedAt.Add(b.Cooldown).Sub(b.Clock.Now()); wait > 0 {
return wait, false
}
b.state, b.probing = halfOpen, false
}
if b.state == halfOpen {
if b.probing {
return time.Second, false // one probe at a time
}
b.probing = true
}
return 0, true
}
func (b *Breaker) Record(ok bool) {
b.mu.Lock()
defer b.mu.Unlock()
switch {
case ok:
b.state, b.failures, b.probing = closed, 0, false
case b.state == halfOpen:
b.state, b.openedAt, b.probing = open, b.Clock.Now(), false
default:
b.failures++
if b.failures >= b.Threshold {
b.state, b.openedAt = open, b.Clock.Now()
}
}
}
func (b *Breaker) Open() bool {
b.mu.Lock()
defer b.mu.Unlock()
return b.state == open
}
// Budget caps retries at a fraction of traffic: every call deposits Ratio,
// every retry spends one token, and the balance never exceeds Max.
type Budget struct {
mu sync.Mutex
Tokens, Ratio, Max float64
}
func (b *Budget) Deposit() {
b.mu.Lock()
defer b.mu.Unlock()
b.Tokens = min(b.Max, b.Tokens+b.Ratio)
}
func (b *Budget) Spend() bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.Tokens < 1 {
return false
}
b.Tokens--
return true
}
type OpenError struct{ RetryAfter time.Duration }
func (e *OpenError) Error() string { return "circuit open" }
type Retrier struct {
Client *http.Client
Clock *fakeClock
Rand *rand.Rand // seeded, so the jitter below is reproducible
Breaker *Breaker
Budget *Budget
MaxAttempts int
Base, Cap time.Duration
MaxWait time.Duration // total waiting allowed for one call
trace []string
}
func safeToRetry(req *http.Request) bool {
if req.Body != nil && req.Body != http.NoBody && req.GetBody == nil {
return false // the body was consumed and cannot be sent again
}
switch req.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
return true
}
return req.Header.Get("Idempotency-Key") != ""
}
func retryableStatus(code int) bool {
return code == http.StatusTooManyRequests || code == http.StatusBadGateway ||
code == http.StatusServiceUnavailable || code == http.StatusGatewayTimeout
}
// retryAfter accepts delay-seconds or an HTTP-date, as RFC 9110 allows.
func retryAfter(v string, now time.Time) (time.Duration, bool) {
if s, err := strconv.Atoi(v); err == nil && s >= 0 {
return time.Duration(s) * time.Second, true
}
if t, err := http.ParseTime(v); err == nil {
return max(0, t.Sub(now)), true
}
return 0, false
}
// backoff is "full jitter": uniform in [0, min(Cap, Base*2^(attempt-1))).
func (r *Retrier) backoff(attempt int) time.Duration {
ceiling := min(r.Cap, r.Base<<(attempt-1))
return time.Duration(r.Rand.Int64N(int64(ceiling))).Truncate(time.Millisecond)
}
func (r *Retrier) Do(req *http.Request) (*http.Response, error) {
r.trace = r.trace[:0]
r.Budget.Deposit()
deadline := r.Clock.Now().Add(r.MaxWait)
for attempt := 1; ; attempt++ {
if wait, ok := r.Breaker.Allow(); !ok {
r.trace = append(r.trace, "rejected by open breaker")
return nil, &OpenError{RetryAfter: wait}
}
if req.GetBody != nil {
req.Body, _ = req.GetBody() // a fresh copy of the body for every attempt
}
resp, err := r.Client.Do(req)
r.Breaker.Record(err == nil && resp.StatusCode < 500)
if err == nil && !retryableStatus(resp.StatusCode) {
r.trace = append(r.trace, strconv.Itoa(resp.StatusCode))
return resp, nil
}
label := "error"
wait := r.backoff(attempt)
if err == nil {
label = strconv.Itoa(resp.StatusCode)
if d, ok := retryAfter(resp.Header.Get("Retry-After"), r.Clock.Now()); ok {
wait = d // the server named the wait; honor it instead of guessing
}
}
stop := ""
switch {
case !safeToRetry(req):
stop = "not idempotent"
case attempt == r.MaxAttempts:
stop = "attempts used"
case r.Breaker.Open():
stop = "circuit opened"
case r.Clock.Now().Add(wait).After(deadline):
stop = "deadline"
case !r.Budget.Spend():
stop = "budget empty"
}
if stop != "" {
r.trace = append(r.trace, label+" stop: "+stop)
return resp, err
}
if resp != nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
r.trace = append(r.trace, label+" wait "+wait.String())
r.Clock.Sleep(wait)
}
}
// respond turns the outcome into this API's answer.
func respond(c *gin.Context, resp *http.Response, err error) {
var open *OpenError
switch {
case errors.As(err, &open):
secs := int((open.RetryAfter + time.Second - 1) / time.Second)
c.Header("Retry-After", strconv.Itoa(secs))
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "quotes_unavailable"})
case err != nil || resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests:
c.JSON(http.StatusBadGateway, gin.H{"error": "quotes_failed"})
default:
resp.Body.Close()
c.JSON(resp.StatusCode, gin.H{"ok": true})
}
}
func main() {
gin.SetMode(gin.TestMode)
clock := &fakeClock{now: time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC)}
up := &scripted{}
rt := &Retrier{
Client: &http.Client{Transport: up},
Clock: clock,
Rand: rand.New(rand.NewPCG(1, 2)),
Breaker: &Breaker{Clock: clock, Threshold: 3, Cooldown: 30 * time.Second},
Budget: &Budget{Tokens: 3, Ratio: 0.5, Max: 3},
MaxAttempts: 3,
Base: 100 * time.Millisecond,
Cap: time.Second,
MaxWait: 3 * time.Second,
}
const upstream = "https://quotes.internal.example/v1"
r := gin.New()
r.GET("/quotes/:sym", func(c *gin.Context) {
req, _ := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, upstream+"/quotes/"+c.Param("sym"), nil)
resp, err := rt.Do(req)
respond(c, resp, err)
})
r.POST("/orders", func(c *gin.Context) {
body, _ := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20))
req, _ := http.NewRequestWithContext(c.Request.Context(), http.MethodPost, upstream+"/orders", strings.NewReader(string(body)))
if key := c.GetHeader("Idempotency-Key"); key != "" {
req.Header.Set("Idempotency-Key", key) // the upstream dedupes on it
}
resp, err := rt.Do(req)
respond(c, resp, err)
})
call := func(label, method, path, key string, script ...string) {
up.script = script
req := httptest.NewRequest(method, path, strings.NewReader(`{"qty":1}`))
if key != "" {
req.Header.Set("Idempotency-Key", key)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
extra := ""
if ra := w.Header().Get("Retry-After"); ra != "" {
extra = " Retry-After=" + ra
}
fmt.Printf("%-14s %s -> %d%s\n", label, strings.Join(rt.trace, ", "), w.Code, extra)
}
call("GET flaky", "GET", "/quotes/GO", "", "503", "503", "200")
call("POST no key", "POST", "/orders", "", "503")
call("POST with key", "POST", "/orders", "k-7f3a", "503", "201")
call("GET throttled", "GET", "/quotes/GO", "", "429:2", "200")
call("GET outage", "GET", "/quotes/GO", "", "503", "503")
call("GET outage", "GET", "/quotes/GO", "", "503")
call("GET while open", "GET", "/quotes/GO", "")
clock.Sleep(31 * time.Second)
call("GET probe", "GET", "/quotes/GO", "", "200")
fmt.Println("upstream calls:", up.calls, "for 8 client requests; breaker open:", rt.Breaker.Open())
}Do deposits into the budget once per call, then loops. Each attempt first asks the breaker, refreshes the body through GetBody, sends, and records success or failure; only transport errors and 5xx count against the breaker, so the 429 does not. A non-retryable status returns at once. Otherwise the wait is the jittered backoff, replaced by Retry-After when the upstream sends one, and the switch names the first reason to stop: unsafe method, attempts used, breaker now open, wait past the deadline, or no budget. The first outage request spends the last whole token on one retry and then finds the budget empty; the second takes the third consecutive failure, which opens the breaker. The next request never reaches the upstream, and respond turns OpenError into 503 with Retry-After rounded up to whole seconds. After 31 simulated seconds one probe succeeds and the breaker closes. trace exists only to print attempts and is not safe for concurrent use; a real client would emit metrics instead.
Jitter spreads the herd; seeds and clocks make it testable
Clients that failed together and back off by the same schedule retry together, in synchronized waves that knock the recovering upstream over again. Full jitter draws each wait uniformly from zero to min(Cap, Base times 2 to the power of the attempt number minus one): the ceiling grows exponentially while individual waits spread across it, and the cap keeps the exponent from producing minute-long waits. In production every process should draw differently, which math/rand/v2's top-level functions already do because they are randomly seeded; in tests inject a *rand.Rand built from rand.NewPCG with fixed seeds, which yields the same sequence every run. Time works the same way: depend on a clock interface, give tests a fake one, and give production a sleep that also watches the request context, as in the fragment below. Retry-After, defined in RFC 9110 section 10.2.3, may hold seconds or an HTTP-date; prefer it over your own guess, but a value longer than the remaining budget means give up now and tell your own client when to return.
// realClock sleeps on a timer but wakes as soon as the request is canceled.
type realClock struct{}
func (realClock) Now() time.Time { return time.Now() }
func (realClock) Sleep(ctx context.Context, d time.Duration) error {
if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < d {
return context.DeadlineExceeded // the wait cannot finish in time: give up now
}
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}This fragment is the production counterpart of fakeClock and runs in your own native environment. It refuses a wait that would end after the context deadline, because a retry that starts after the caller gave up is pure waste. time.NewTimer with a deferred Stop releases the timer when the request is canceled first, and the select returns ctx.Err() so the retry loop stops instead of sending another attempt for a client that has already left.
A retry budget caps amplification across requests
MaxAttempts bounds one call, not the fleet. When every request fails, three attempts each triple the load on a dependency that may be failing precisely because it is overloaded. A budget ties retries to overall traffic: every call deposits Ratio tokens, every retry spends one, and the balance is capped, so over time retries add at most Ratio times the request rate. Google's SRE book describes the same idea as a per-client retry budget of about ten percent; the program uses 0.5 only so that the effect appears within eight requests. Keep one budget per upstream in each process; coordinating budgets across instances is rarely worth the complexity. Export the number of retries and of budget refusals as metrics: a sudden rise in refusals is an early, cheap signal that a dependency is degrading.
Breaker states and what the Gin handler returns while open
Closed: calls pass and consecutive failures are counted; at the threshold the breaker opens. Open: calls fail immediately with no socket and no waiting, which protects both the upstream and your own goroutines. After the cooldown the breaker turns half-open and lets exactly one probe through; success closes it, failure reopens it for a fresh cooldown, and other callers are refused while the probe is in flight. Allow and Record take a mutex because every request touches them concurrently. While open, the handler chose not to do the work, so it answers 503 Service Unavailable with Retry-After set to the remaining cooldown, in your own error format, consistent with the timeouts lesson's convention; if the product allows, serve a stale cached value instead. Keep one breaker per upstream, or per endpoint when endpoints fail independently, never one for everything. Consecutive failures are the simplest trigger; production breakers often use a failure rate over a sliding window with a minimum request volume, so two failures in a quiet hour do not trip it.
Test the policy as a table of scripts
Each test row is a method, an optional Idempotency-Key, an upstream script and the expected attempts, waits, final status and breaker state; with an injected clock and seeded random source the assertions can be exact. Add a concurrency test in which many goroutines hit a half-open breaker and exactly one RoundTrip call happens. Check that every attempt resends the body: http.NewRequest sets GetBody only for *bytes.Buffer, *bytes.Reader and *strings.Reader bodies, so for any other reader GetBody is nil and safeToRetry refuses rather than sending an empty second attempt. In staging, inject faults by making a test upstream return 503 or hang, and watch the attempt counts, budget refusals and breaker transitions on your dashboards before a real outage does it for you.
TAKE THIS WITH YOU
Retry only idempotent requests or those carrying an Idempotency-Key, only on transient failures, with capped full-jitter backoff, honored Retry-After and a shared retry budget, and put a per-upstream circuit breaker in front so an outage gets fast 503s with Retry-After instead of more load.
Check your understanding
A POST to a payment upstream times out after the request was fully sent. When may the client retry it automatically?
Go to the source
Progress stays in this browser. No account needed.