Skip to Content
Skip to content
Go Advanced: Performance, Concurrency, and Production
Advanced
Courses
Go Advanced: Performance, Concurrency, and Production

Add Retries With Backoff and Jitter

Retry transient failures with exponential backoff and jitter while respecting context deadlines and skipping non-retryable 4xx responses. After this, callers recover from brief blips without thundering herds.

Course content

Sign in to save your progress.

Course Home

Imagine your checkout service calls a downstream payment or inventory API that briefly returns 503 Service Unavailable during a 3-second rolling deploy. If 500 concurrent workers retry immediately in a tight for loop—or all sleep for an identical 100ms—all 500 workers wake up on the exact same millisecond and knock the recovering upstream API right back offline.

A production-ready Go retry helper solves three separate problems at once: it filters retryable errors (429, 5xx, network resets) from permanent client bugs (400, 404), spreads retries with exponential backoff + full jitter, and aborts sleep immediately if ctx.Done() fires.

Skip ahead

If you already combine status-code filtering, exponential backoff with full jitter via math/rand/v2, and context-aware time.NewTimer sleeps, continue to "Protect Endpoints With Rate Limiting and Panic Recovery."

Experiment 1: Why fixed-interval retries create thundering herds

When an upstream API fails at t = 0.0s and 1,000 requests retry at a fixed 200 ms interval, all 1,000 retries hit simultaneously at t = 0.2s, then again at t = 0.4s. Adding full jitter—choosing a random wait uniformly in [0, min(base << attempt, maxDelay)]—smears those 1,000 retries evenly across time so the recovering server can breathe.

Experiment 2: Context-aware retry helper with full jitter

Notice three deliberate choices in doWithRetry below: shouldRetry rejects context.Canceled, context.DeadlineExceeded, and 4xx client errors (except 429); rand.N(ceil + 1) from Go 1.22+'s math/rand/v2 computes jitter safely across goroutines without a global lock; and time.NewTimer pairs with select so canceled requests stop sleeping immediately:

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 {
	if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
		return false
	}
	var se statusError
	if errors.As(err, &se) {
		return se.code == http.StatusTooManyRequests || se.code >= 500
	}
	return true // network/EOF errors
}

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 := min(baseDelay<<attempt, 2*time.Second)
		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) {
		if calls.Add(1) < 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)
}
$ go run .
attempts=3 err=<nil>
non_retryable=http 400

The transient 503 recovered cleanly on attempt 3, while the 400 Bad Request exited on attempt 1 without wasting retries or upstream quota.

Experiment 3: Idempotency—when retrying is dangerous

Suppose your client sends POST /charges to charge a credit card, the payment provider charges the card, and the TCP connection drops right before the 200 OK response reaches you. If your retry loop blindly sends POST /charges again, you just double-charged the customer! Only retry GET/PUT/DELETE calls—or POST calls that include a unique Idempotency-Key header recognized by the upstream server.

Experiment 4: Always cap backoff and honor Retry-After

Notice ceil := min(baseDelay<<attempt, 2*time.Second). Without a cap, large attempt counts can shift baseDelay into minutes or overflow time.Duration. And when an API returns 429 Too Many Requests with a Retry-After header, wait at least that long (clamped to your request deadline) instead of hammering the rate limiter early.

Common mistakes

  • Using time.Sleep(wait) between retries: Ignores ctx.Done(), keeping goroutines blocked long after the caller canceled or timed out.
  • Forgetting resp.Body.Close() on failed attempts: Leaks TCP connections from http.DefaultTransport every time a retry fires.
  • Retrying 400, 401, 403, or 404 responses: Client/auth bugs will never succeed on retry 2 or 3—they just multiply log noise and delay errors back to users.

💡 Tip

Put retries at the outermost client boundary only—not at every layer of a 3-service call chain. If Service A retries 3 times, Service B retries 3 times, and Service C retries 3 times, one failure multiplies into 3 × 3 × 3 = 27 requests (a retry storm).

What happens if you skip this step

Without status filtering, jitter, and idempotency checks, brief upstream blips escalate into synchronized retry storms—or worse, duplicate financial charges when a timed-out POST actually succeeded on the server.

Why should doWithRetry use time.NewTimer(wait) inside a select with <-ctx.Done() instead of calling time.Sleep(wait)?

About

Retry transient failures with exponential backoff and jitter while respecting context deadlines and skipping non-retryable 4xx responses. After this, callers recover from brief blips without thundering herds.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.