0Pricing
Go Academy · Lesson

Backoff and Retry

Retry with backoff.

Backoff and Retry is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Retry

Transient failures, timeouts, dropped connections, brief 503s, often succeed on a second attempt. Retrying turns a flaky operation into a reliable one without bothering the caller.

Naive Retry Is Dangerous

Retrying immediately in a tight loop hammers a struggling service and can cause a retry storm. We need delays between attempts, and the delays should grow.

Exponential Backoff

Exponential backoff doubles the wait after each failure: 100ms, 200ms, 400ms, 800ms. This gives the downstream service room to recover.

delay := 100 * time.Millisecond
for attempt := 0; attempt < 5; attempt++ {
    // try, on failure:
    time.Sleep(delay)
    delay *= 2
}

Adding Jitter

If many clients back off in lockstep they retry at the same moment, a thundering herd. Jitter randomizes each delay slightly so retries spread out in time.

jitter := time.Duration(rand.Int63n(int64(delay) / 2))
time.Sleep(delay + jitter)

Capping the Delay

Exponential growth gets huge fast. Cap the delay at a maximum so you do not wait minutes between attempts.

if delay > 2*time.Second {
    delay = 2 * time.Second
}

Bounding Attempts

Always limit the number of attempts. After the cap, return the last error so the caller can decide what to do instead of retrying forever.

Retry Only Idempotent Work

Retrying is safe only when the operation can run twice without harm. A GET is idempotent; a non-idempotent POST that charges a card should not be retried blindly. Use idempotency keys when needed.

A Complete Backoff Retry

This program retries a function that fails twice then succeeds, doubling the delay each time. It uses only the standard library.

package main

import (
    "errors"
    "fmt"
    "time"
)

func flaky(attempt int) error {
    if attempt < 2 {
        return errors.New("temporary failure")
    }
    return nil
}

func main() {
    delay := 50 * time.Millisecond
    var err error
    for attempt := 0; attempt < 5; attempt++ {
        err = flaky(attempt)
        if err == nil {
            fmt.Println("succeeded on attempt", attempt)
            return
        }
        fmt.Printf("attempt %d failed, waiting %v\n", attempt, delay)
        time.Sleep(delay)
        delay *= 2
    }
    fmt.Println("gave up:", err)
}

Respecting context

Pass a context into the retry loop and select on ctx.Done() while sleeping. This lets a cancelled or timed-out caller stop retrying immediately.

select {
case <-ctx.Done():
    return ctx.Err()
case <-time.After(delay):
}

Distinguishing Errors

Not every error is retryable. A 400 Bad Request will fail forever. Inspect the error or status code and only retry on transient classes like timeouts, 429, and 5xx.

Circuit Breakers

When failures persist, a circuit breaker stops sending requests for a cooldown period instead of retrying each call. It complements backoff by protecting a clearly down dependency.

Quick Check

Test your backoff knowledge.

Recap

You learned backoff and retry:

  • Exponential backoff doubles the delay each failure
  • Jitter prevents synchronized retry storms
  • Cap the delay and bound the attempts
  • Retry only idempotent or retryable errors
  • Respect context for cancellation

Frequently asked questions

Is the “Backoff and Retry” lesson free?

Yes — the full text of “Backoff and Retry” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “Backoff and Retry”?

Retry with backoff. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Backoff and Retry” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Token Bucket Concept
  2. golang.org/x/time/rate
  3. Throttling Goroutines
  4. Backoff and Retry
← Back to Go Academy