---
title: "Retries"
description: "Exponential backoff with full jitter: when to retry, when not to, and how to avoid making a bad situation worse."
---

> Documentation Index
> Fetch the complete documentation index at: https://codex.mirio.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Retries

A [timeout](https://codex.mirio.dev/reliability/timeouts/) tells you a call failed. Retries decide what to do
about it. The naive answer (try again immediately, as many times as it takes) turns a
struggling downstream into a completely dead one. Every retry under load is a new
request the target must handle while it's already overwhelmed. When a downstream is
consistently failing rather than transiently, retrying amplifies the damage; see
[Circuit Breaking](https://codex.mirio.dev/reliability/circuit-breaking/) for when to stop calling entirely.

The right pattern is exponential backoff with jitter: wait longer after each
failure, and randomize the wait so clients don't all resume at the same instant.

## When to retry

Only retry errors that are **transient** and only on operations that are
**idempotent**.

**Retryable:**

| Signal                      | Reason                                             |
| --------------------------- | -------------------------------------------------- |
| Network error / timeout     | Connection lost or server didn't respond in time   |
| `429 Too Many Requests`     | Explicitly told to back off; respect `Retry-After` |
| `500 Internal Server Error` | Server-side fault, may be transient                |
| `502 Bad Gateway`           | Upstream proxy couldn't reach the backend          |
| `503 Service Unavailable`   | Server is temporarily overloaded or in maintenance |
| `504 Gateway Timeout`       | Upstream proxy timed out waiting for the backend   |

**Not retryable:**

| Signal              | Reason                                                        |
| ------------------- | ------------------------------------------------------------- |
| `400 Bad Request`   | The request is malformed; retrying sends the same bad request |
| `401 Unauthorized`  | Missing or invalid credentials; fix the credentials first     |
| `403 Forbidden`     | Authenticated but not authorized; retrying won't change that  |
| `404 Not Found`     | The resource doesn't exist; it won't appear on retry          |
| `422 Unprocessable` | Validation failed; the same payload will fail again           |

Idempotency is the other gate. `GET`, `HEAD`, `PUT`, and `DELETE` are safe to
retry by definition. `POST` is not unless the server assigns an idempotency key
you can reuse, or the operation is naturally idempotent (e.g., "set the status
to `published`" vs. "increment the view count").

## Backoff with full jitter

The standard formula caps the exponential growth and adds full jitter: a
uniform random value in `[0, cap]` rather than the raw exponential. Full jitter
spreads retries across the entire window rather than clustering them at the top,
which maximizes load distribution when many clients are backing off simultaneously.

```
delay = random(0, min(cap, base × 2^attempt))
```

:::caution
Without jitter, all clients that started failing at the same time will retry at the same time: a
**thundering herd** that hits the recovering service in a synchronized wave. Full jitter breaks
the synchronization.
:::

## Go

A generic retry helper that respects context cancellation, applies backoff
between attempts, and bails immediately on errors marked permanent:

```go
// permanent marks an error as non-retryable; withRetry returns it immediately.
func permanent(err error) error { return &permanentError{err} }

type permanentError struct{ err error }

func (e *permanentError) Error() string { return e.err.Error() }
func (e *permanentError) Unwrap() error { return e.err }

func withRetry(ctx context.Context, maxAttempts int, fn func() error) error {
    var err error
    for attempt := range maxAttempts {
        if attempt > 0 {
            select {
            case <-time.After(retryDelay(err, attempt)):
            case <-ctx.Done():
                return ctx.Err()
            }
        }
        err = fn()
        if err == nil {
            return nil
        }
        var perm *permanentError
        if errors.As(err, &perm) {
            return perm.err
        }
    }
    return err
}

func retryBackoff(attempt int) time.Duration {
    const (
        base = 100 * time.Millisecond
        cap  = 30 * time.Second
    )
    exp := base * (1 << min(attempt, 10)) // cap the shift to avoid overflow
    if exp > cap {
        exp = cap
    }
    return time.Duration(rand.Int64N(int64(exp)))
}
```

Without the permanent marker, a `404` or a validation failure would burn every
attempt on a request that can never succeed.

Usage with an HTTP call that checks whether the error is retryable:

```go
var httpClient = &http.Client{Timeout: 10 * time.Second}

func fetchWithRetry(ctx context.Context, url string) (*http.Response, error) {
    var resp *http.Response
    err := withRetry(ctx, 4, func() error {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
        if err != nil {
            return permanent(err)
        }
        r, err := httpClient.Do(req)
        if err != nil {
            return err // network error: retryable
        }
        if r.StatusCode == http.StatusTooManyRequests ||
            r.StatusCode >= 500 {
            r.Body.Close()
            return fmt.Errorf("server returned %d", r.StatusCode)
        }
        if r.StatusCode >= 400 {
            r.Body.Close()
            return permanent(fmt.Errorf("server returned %d", r.StatusCode))
        }
        resp = r
        return nil
    })
    return resp, err
}
```

The context is threaded through both `withRetry` (for the backoff sleep) and
`NewRequestWithContext` (for the in-flight request). If the caller's context
is cancelled mid-retry, both the sleep and the request abort cleanly.

### Respecting `Retry-After`

When the server sends a `429` with a `Retry-After` header, use that value
instead of your own backoff. Carry the delay on the error so `withRetry` can
honor it; this is the `retryDelay` function the helper above calls:

```go
type retryAfterError struct {
    delay time.Duration
    err   error
}

func (e *retryAfterError) Error() string { return e.err.Error() }
func (e *retryAfterError) Unwrap() error { return e.err }

func retryDelay(err error, attempt int) time.Duration {
    var ra *retryAfterError
    if errors.As(err, &ra) {
        return ra.delay
    }
    return retryBackoff(attempt)
}
```

In the closure, wrap the `429` case:

```go
if r.StatusCode == http.StatusTooManyRequests {
    r.Body.Close()
    err := fmt.Errorf("server returned 429")
    if secs, parseErr := strconv.Atoi(r.Header.Get("Retry-After")); parseErr == nil {
        return &retryAfterError{delay: time.Duration(secs) * time.Second, err: err}
    }
    return err
}
```

---

## Rust (tokio)

The same shape: a generic async retry wrapper with backoff, and an error enum
that distinguishes transient failures (retried) from permanent ones (returned
immediately):

```rust
use std::time::Duration;
use rand::Rng;
use tokio::time::sleep;

pub enum RetryError<E> {
    Transient(E),
    Permanent(E),
}

pub async fn with_retry<F, Fut, T, E>(max_attempts: u32, mut f: F) -> Result<T, E>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Result<T, RetryError<E>>>,
{
    let mut attempt = 0;
    loop {
        match f().await {
            Ok(val) => return Ok(val),
            Err(RetryError::Permanent(e)) => return Err(e),
            Err(RetryError::Transient(e)) => {
                attempt += 1;
                if attempt >= max_attempts {
                    return Err(e);
                }
                sleep(backoff(attempt)).await;
            }
        }
    }
}

fn backoff(attempt: u32) -> Duration {
    const BASE_MS: u64 = 100;
    const CAP_MS: u64 = 30_000;

    let exp = BASE_MS.saturating_mul(1 << attempt.min(10));
    let ceil = exp.min(CAP_MS);
    let jitter = rand::rng().random_range(0..=ceil);
    Duration::from_millis(jitter)
}
```

Usage with `reqwest`, classifying each status code:

```rust
use reqwest::{Client, StatusCode};

async fn fetch_with_retry(client: &Client, url: &str) -> anyhow::Result<String> {
    with_retry(4, || async {
        let resp = client
            .get(url)
            .send()
            .await
            .map_err(|e| RetryError::Transient(anyhow::Error::from(e)))?;

        match resp.status() {
            s if s.is_success() => resp
                .text()
                .await
                .map_err(|e| RetryError::Transient(anyhow::Error::from(e))),
            s if s == StatusCode::TOO_MANY_REQUESTS || s.is_server_error() => {
                Err(RetryError::Transient(anyhow::anyhow!("server returned {s}")))
            }
            s => Err(RetryError::Permanent(anyhow::anyhow!(
                "non-retryable status {s}"
            ))),
        }
    })
    .await
}
```

:::note
The closure passed to `with_retry` must be `FnMut` because it's called multiple times. Captured
values that are moved into an `async` block are consumed on the first call; clone them outside the
closure or reconstruct them inside it.
:::

---

## Setting a retry budget

Bounding by attempt count is simple but can still burn too much wall time. An
alternative is a total deadline that the entire retry loop must fit within:

**Go:** pass a context with a timeout wrapping the whole `withRetry` call:

```go
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
err := withRetry(ctx, 5, fn)
```

**Rust:** wrap the retry loop with `tokio::time::timeout`:

```rust
use tokio::time::{timeout, Duration};

let result = timeout(Duration::from_secs(45), with_retry(5, || async {
    // ...
}))
.await;
```

The deadline becomes the outer constraint; individual attempts stop as soon as
it fires. This is more predictable than counting attempts when backoff intervals
vary widely.

Source: https://codex.mirio.dev/reliability/retries/index.mdx
