---
title: Retry and fall back when a provider fails
description: Wrap the model with mw.Retry to retry rate limits, overload and transport errors with backoff and the provider's retry-after, add mw.Fallback for a backup model, and see each attempt on the run's record.
url: https://weftgo.dev/docs/guides/retries-and-fallback/
type: how-to
sources:
  - 'weft/core/report.go:36-82 (AttemptInfo.Layer with AttemptLayerRetry, Wait, HTTPStatus, GiveUp and its values), 522-559 (attemptErrorType: the classes)'
  - 'weft/CHANGELOG.md:39 (0.20.0: GiveUp, weft.attempt.giveup_reason, Studio''s words, the wait hatch), 74 (0.20.0 breaking: classified attempt error.type, layer retry), 98 (0.20.0 fixed: a backup''s retries marked fallback)'
  - 'docs-site/examples/middleware/middleware_test.go: TestDemos (its output now carries layer=retry; passes against ../weft-rc020 through a scratch go.work)'
  - weft/AGENTS.md:94 (block 2), 103-108 (the reporting hook)
  - weft/core/mw/doc.go:7-19 (order)
  - weft/core/mw/retry.go:19-23 (ErrRetryAfterTooLong), 25-30 (defaults), 43-91 (options), 93-133 (Retry), 161-233 (the retry loop), 237-267 (delay, backoff; jitter after the cap, 199-215), 283-318 (Retryable), 320-355 (RetryAfter), 361-383 (HTTPStatus), 456-482 (IsContextOverflow)
  - weft/core/mw/model.go:16-62 (Fallback, FallbackWhen, defaultFallback), 104-129 (Fallback's chain), 118-125 (an exhausted chain yields the last model's error alone; the predicate gets each failed model's error), 131-224 (replay), 254-283 (reportsItself, ReportsAttempts)
  - weft/mw/facade.go:34, 39, 68, 71, 77, 83, 89, 97, 118, 129, 140, 147, 155
  - weft/core/report.go:17-69 (AttemptInfo), 79-81 (AttemptLayerFallback), 136-158 (Reporter), 162-176 (ReportFromContext), 178-188 (Attempt), 190-202 (Raw), 281-363 (the attempt span and log line)
  - weft/core/example_test.go:1147-1181 (timedModel, ExampleReportFromContext)
  - weft/mw/example_test.go:22 (ExampleRetry), 44 (ExampleFallback)
  - weft/docs/adr/0006-seams.md:88-111 (Retry policy)
  - weft/docs/record-contract.md:374-423 (the attempt span), 1036 (attempts_retried, fallbacks)
  - weft/openai/model.go:114-122 (MaxRetries), weft/anthropic/model.go:106 (MaxRetries)
  - weft/CHANGELOG.md:2991, 5660
  - docs-site/examples/middleware/retries.go, middleware_test.go TestDemos, TestRetryCount, TestFallbackLayer, TestRetryAfterTooLong
---

# Retry and fall back when a provider fails

[`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) is model middleware that retries a model call which failed before yielding any event: rate limits, overload, transport errors, an idle stream. It backs off between tries and honours the provider's retry-after. [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) tries a backup model when the primary still fails. Both report every attempt on the run's record.

Retry the model, in `middleware/retries.go`:

```go title="middleware/retries.go"
agt := weft.New(primary,
	weft.WrapModel(mw.Retry(
		mw.MaxRetries(3),                  // retries after the first try (default 3)
		mw.BaseDelay(10*time.Millisecond), // first backoff (default 500ms), doubling, capped at 8s
		mw.MaxWait(30*time.Second),        // a longer retry-after fails at once (default 60s)
		mw.Classifier(func(err error) bool {
			return mw.Retryable(err) || errors.Is(err, errWarmingUp)
		}),
	)),
	attempts(w), // print each reported attempt
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

The scripted model fails twice, then answers. The agent's `weft.Logger` prints each reported attempt:

```text
  attempt attempt=1 model=large err=model is warming up
  attempt attempt=2 model=large retry_after=5ms layer=retry wait=10ms status=429 err=provider: 429 Too Many Requests
  attempt attempt=3 model=large layer=retry wait=5ms
retry: "Order 1234 has shipped." after 3 requests
```

The first failure is retried because the custom classifier accepts it, after a backoff of about 10 ms (between 7.5 and 12.5 ms: ±25% jitter). The second is a 429 that asked for 5 ms, and Retry waited exactly that.

## How it works

The loop never retries a model call itself. Retries are model-seam middleware, installed with [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) like any other: see [Add behaviour with middleware](https://weftgo.dev/docs/guides/middleware/).

`Retry` and `Fallback` act only on a call that failed **before any event reached the loop**. Once part of a reply has been consumed, no middleware can take it back, so a failure after the first event is the run's error. With the default classifier and fallback predicate, context cancellation and the `WEFT_MODEL_REQUESTS=deny` kill switch never retry and never fall through; a custom `mw.Classifier` or `mw.FallbackWhen` predicate replaces those rules and can change that. `Retry` itself never retries once the run's context is done.

Each attempt gets its own copy of the request's slices and `Params` values. What a failed attempt's model, or a middleware inside `Retry`, wrote into its request never reaches the next attempt ([rewrite a request](https://weftgo.dev/docs/guides/middleware/#model-middleware)).

The vendor SDKs have transport retries of their own, below the adapter. `mw.Retry` is the layer above them that you can see: its backoff shows in the attempt records and in `mw.Log`.

## Retry

`mw.Retry(opts...)` takes [`mw.RetryOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryOption) values:

| Option | Default | Effect |
|---|---|---|
| [`mw.MaxRetries(n)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxRetries) | 3 | Retries after the first try. `0` disables retrying; the retry-after rule and the classifier still apply. A negative `n` is ignored. |
| [`mw.BaseDelay(d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#BaseDelay) | 500ms | The first backoff. Delays double per retry (0.5s, 1s, 2s, …), capped at 8s; ±25% jitter is applied after the cap, so a capped delay lands between 6s and 10s. `0` means no delay. |
| [`mw.MaxWait(d)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxWait) | 60s | The longest retry-after ask Retry sleeps on. A longer ask fails at once. `0` removes the cap. |
| [`mw.Classifier(fn)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Classifier) | `mw.Retryable` | Replaces the test that decides whether an error is retried. |

A retry-after the provider sends wins over the backoff. Retry reads the `retry-after-ms` header, then `retry-after` (seconds, or an HTTP date), and an `x-should-retry` header overrides the status rule. When the retries run out, the last error comes back wrapped as `mw: giving up after 3 retries: …`, so `errors.As` on the SDK's error type still works. The package example is [`ExampleRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Retry).

### Fail at once on a long retry-after

A provider that asks for longer than `MaxWait` gets no sleep. The call fails at once wrapping [`mw.ErrRetryAfterTooLong`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#ErrRetryAfterTooLong), with the provider's own error underneath, so a queue or a person can decide:

```go title="middleware/retries.go"
_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
var apiErr *apiError
fmt.Fprintln(w, "too long:", errors.Is(err, mw.ErrRetryAfterTooLong), errors.As(err, &apiErr))
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

Here the provider asked for two minutes against the 60-second default; the output is `too long: true true` after one request. This check outranks the retry budget, so even `MaxRetries(0)` reports `ErrRetryAfterTooLong` rather than the raw error.

### Choose what is retried

The default classifier is [`mw.Retryable`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retryable):

- **Retried:** `weft.ErrStreamIdle`, any `net.Error`, and HTTP 408, 409, 429 and 5xx.
- **Never retried:** context errors, the kill switch, `weft.ErrUnsupported`, `weft.ErrModelContract`, every other 4xx (quota, billing, a bad request), and a context-window overflow.

`mw` imports no vendor SDK. It finds the status and headers on the error chain by shape, which the helpers expose for your own classifier:

```go title="middleware/retries.go"
err := providerError(429, "250")
status, _ := mw.HTTPStatus(err)          // 429, from the StatusCode field
ask, _ := mw.RetryAfter(err, time.Now()) // 250ms, from retry-after-ms
fmt.Fprintln(w, "helpers:", status, ask, mw.Retryable(err))

overflow := errors.New("400: prompt is too long: 210000 tokens > 200000 maximum")
fmt.Fprintln(w, "overflow:", mw.IsContextOverflow(overflow), mw.Retryable(overflow))
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

- [`mw.HTTPStatus(err)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#HTTPStatus) reads an exported integer `StatusCode` field (openai-go, anthropic-sdk-go) or `Code` field (genai) on any error in the chain.
- [`mw.RetryAfter(err, now)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryAfter) reads the retry-after headers from a `Response` field on the chain. It reports false for a missing header and for a value that cannot become a duration (unparseable, negative, or too large).

The example prints `helpers: 429 250ms true` and `overflow: true false`.

### Context overflow

[`mw.IsContextOverflow(err)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#IsContextOverflow) reports whether the error's text names a context-window overflow, such as `context_length_exceeded` or `prompt is too long`. `Retryable` treats such an error, and `weft.ErrContextOverflow` that the first-party adapters wrap, as terminal: the same request cannot succeed again. Route it to compaction instead; see [Keep long sessions inside the context window](https://weftgo.dev/docs/sessions/compaction/).

### Pair Retry with the adapter's `MaxRetries(0)`

The OpenAI and Anthropic SDKs retry twice by default, and they sleep on the provider's retry-after inside the adapter's idle timer. A long ask then fails as `ErrStreamIdle` with the 429 and its header discarded. Pass `openai.MaxRetries(0)` or `anthropic.MaxRetries(0)` to switch the SDK's retries off, so `mw.Retry` owns every retry, honours the ask under `MaxWait` and records it. See [Connect a model provider](https://weftgo.dev/docs/guides/providers/).

## Fallback

`mw.Fallback(models...)` tries the given models in order when the wrapped model fails before yielding any event, for example an outage or a capability gap (`weft.ErrUnsupported`). Put it outside `mw.Retry` so the primary is retried first:

```go title="middleware/retries.go"
agt := weft.New(primary,
	weft.WrapModel(
		mw.Fallback(backup), // outer: switch models once Retry gives up
		mw.Retry(mw.MaxRetries(1), mw.BaseDelay(10*time.Millisecond)), // inner: retry the primary
	),
	attempts(w),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

```text
  attempt attempt=1 model=large retry_after=5ms status=503 err=provider: 503 Service Unavailable
  attempt attempt=2 model=large retry_after=5ms layer=retry wait=5ms status=503 err=provider: 503 Service Unavailable
  attempt attempt=3 model=small layer=fallback
fallback: "Order 1234 has shipped.", backup requests 1
```

Retry spent its one retry on the primary, gave up, and Fallback sent the request to `small`, marked `layer=fallback`. A `max_tokens` finish is a successful stream, so Fallback does not switch on it. A failure after events were yielded is not retried anywhere. The agent's `Info` still reports the primary. The package example is [`ExampleFallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#example-Fallback).

When every model in the chain fails, the run error is the last model's error alone. The earlier models' errors are not on its chain; they are on the `attempt` spans, one per request, and in Studio's attempts.

The order matters. With `Retry` outside `Fallback`, Retry retries the fallback chain as a whole: the primary gets one try per retry cycle, each followed by the backup, and Retry never sees the primary's transient failures.

### Fall back only for some errors

[`mw.FallbackWhen(when, models...)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#FallbackWhen) tries the next model only for errors `when` accepts. A nil `when` is `Fallback`'s default: anything but cancellation and the kill switch.

```go title="middleware/retries.go"
onlyUnsupported := func(err error) bool { return errors.Is(err, weft.ErrUnsupported) }
agt := weft.New(primary, weft.WrapModel(mw.FallbackWhen(onlyUnsupported, backup)))
res, err := agt.Generate(ctx, weft.Prompt("Read the attached invoice."))
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

The `ErrUnsupported` failure (a PDF the primary cannot read) goes to the `vision` backup; a 503 is not accepted, so the run fails with it.

The predicate receives each failed model's error before the next model is tried, so it is the place to classify the primary's failure: count a 429 or log the outage there.

## Report attempts

Inside the model chain, [`weft.ReportFromContext(ctx)`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) returns the current model call's [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter). [`Reporter.Attempt`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Attempt) records one provider request: an `attempt` span under the step's `chat` span and, with the agent's logger at Debug, a `model attempt` line. `mw.Retry` and `mw.Fallback` report every try this way; your own middleware can too:

```go title="middleware/retries.go"
// reportAttempts reports every call through it as one attempt on the
// run's record: an attempt span under the step's chat span, and a
// "model attempt" Debug line on the agent's Logger.
func reportAttempts(next weft.Model) weft.Model { return attemptReporter{next} }

type attemptReporter struct{ next weft.Model }

func (m attemptReporter) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	return func(yield func(weft.ModelEvent, error) bool) {
		info, start := weft.InfoOf(m.next), time.Now()
		var failed error
		for ev, err := range m.next.Stream(ctx, req) {
			failed = err
			if !yield(ev, err) || err != nil {
				break
			}
		}
		status, _ := mw.HTTPStatus(failed)
		weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{
			Model: info.Name, Provider: info.Provider,
			Start: start, End: time.Now(),
			Err: failed, HTTPStatus: status,
		})
	}
}

func (m attemptReporter) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m attemptReporter) Unwrap() weft.Model   { return m.next }

// ReportsAttempts tells a reporting layer above (mw.Retry, mw.Fallback)
// that this one reports, so each request is reported once.
func (m attemptReporter) ReportsAttempts() bool { return true }
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

Install it like any model middleware. Its `ReportsAttempts` method tells the `mw.Retry` above it to stay silent, so each request is reported once:

```go title="middleware/retries.go"
agt := weft.New(primary,
	weft.WrapModel(mw.Retry(mw.BaseDelay(0)), reportAttempts), // Retry stays silent: reportAttempts reports
	attempts(w),
)
res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

```text
  attempt attempt=1 model=large status=500 err=provider: 500 Internal Server Error
  attempt attempt=2 model=large
```

![A run whose model call was retried: the header counts one model attempt retried, and the waterfall's model row holds attempt 1, marked model_error, and attempt 2, which answered](https://weftgo.dev/docs/_astro/studio-attempts.light.CjIZR-GH.webp)

*A run page with a retried model call: the model row holds attempt 1, which failed, and attempt 2, which answered.*

The reporter numbers the attempts 1, 2, … itself, per model call. An [`weft.AttemptInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptInfo) carries what the reporting code saw; a field it does not know stays zero:

| Field | Meaning | On the `attempt` span |
|---|---|---|
| `Model`, `Provider` | The model id requested and its provider | `gen_ai.request.model`, `gen_ai.provider.name` |
| `Start`, `End` | When the attempt ran; both or neither, else ignored | the span's times |
| `Err` | The failure, nil on success | `error.type` (classified, below), status `Error` |
| `RetryAfter` | The wait the provider asked for | `weft.attempt.retry_after_ms` |
| `Layer` | `weft.AttemptLayerFallback` (`"fallback"`) on a request `mw.Fallback` sent to a backup, [`weft.AttemptLayerRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptLayerRetry) (`"retry"`) on one `mw.Retry` sent again after a failure; empty on a first try | `weft.attempt.layer` |
| `Wait` | How long the layer waited before sending it | `weft.attempt.wait_ms` |
| `HTTPStatus` | The provider's HTTP status, when known; `mw.Retry` and `mw.Fallback` read it with `mw.HTTPStatus` | `http.response.status_code` |
| `GiveUp` | Why the reporting layer stopped after this failed attempt: [`weft.AttemptGiveUpBudget`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptGiveUpBudget) (`budget`, its retries spent), `AttemptGiveUpNotRetryable` (`not_retryable`, a failure it does not retry), `AttemptGiveUpRetryAfter` (`retry_after_too_long`, a retry-after past `MaxWait`) | `weft.attempt.giveup_reason` |

`mw.Retry` fills `Wait`, `HTTPStatus` and `GiveUp`. `GiveUp` is that layer's stop, not always the call's: a `Retry` under a `Fallback` marks where it stopped, and the call may go on to the backup. It is empty on an attempt the layer followed with another and on a success. It is also empty when the run was cancelled (the run names its own cause), when the failed attempt had already streamed output (`Retry` stops once output was yielded, without a give-up reason), and when a model that reports its own attempts sits under the layer. The package example [`ExampleAttemptInfo (giveUp)`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-AttemptInfo-GiveUp) shows it.

A failed attempt's `error.type` is a closed set, finer than the run's: the context errors and weft's own failures as the run reads them (`stream_idle`, …), `context_overflow`, then by the provider's HTTP status `rate_limit` (429), `overloaded` (503, 529), `timeout` (408, 504, or a transport timeout), `auth` (401, 403), `server_error` (any other 5xx), and `model_error` for the rest. Before 0.20.0 every provider failure read `model_error`; the run's own `error.type` keeps its table. Studio words each cause in the attempts list ("rate limited (429)"), ends a failed call with "gave up: retries spent (2 attempts)", and draws an attempt's `weft.attempt.wait_ms` as a hatch before its bar.

From the second attempt on, each report also adds its own `request` record. A layer that holds the attempt's wire bytes can report them with [`Reporter.Raw`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Raw) before its `Attempt`; they are recorded only when a destination asks for raw bodies (`otel.RawBodies`, development only), and dropped otherwise. Reporting is not a seam: no report changes a step, a retry or the model chosen. A report never returns an error, never blocks, and a panicking tracer or log handler is contained and counted in `Agent.TapPanics`.

Outside a run's model call the reporter is a no-op, never nil: in a tool handler, on a bare `Model.Stream`, or on a context the loop did not hand the chain. [`AttemptLayerFallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptLayerFallback) is what Studio's `fallbacks` counter keys on, never a comparison of model names; a reader that took any non-empty layer for a fallback must compare with `fallback` since 0.20.0 added `retry`. A backup under its own `mw.Retry` beneath `mw.Fallback` marks every request it sends `fallback`, its retries included, so the counter counts the run it answered. The run row also counts `attempts_retried`: failed attempts a later attempt of the same call followed. The package example [`ExampleReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#example-ReportFromContext) wraps a model the same way. To see the attempts on a run, open it in Studio: [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/).

## Complete example

`middleware/retries.go` runs every snippet on this page. Its `apiError` type stands in for a vendor SDK's error, which `mw` reads by shape:

```go title="middleware/retries.go"
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"iter"
	"log/slog"
	"net/http"
	"strings"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/mw"
	"github.com/weftgo/weft/wefttest"
)

// apiError stands in for a vendor SDK's error type. mw reads it the way
// it reads openai-go's and anthropic-sdk-go's: structurally, an int
// StatusCode field and a Response whose Header carries retry-after.
type apiError struct {
	StatusCode int
	Response   *http.Response
}

func (e *apiError) Error() string {
	return fmt.Sprintf("provider: %d %s", e.StatusCode, http.StatusText(e.StatusCode))
}

// providerError is a failed response; retryAfterMS, when set, is the
// provider's retry-after-ms header.
func providerError(status int, retryAfterMS string) error {
	h := http.Header{}
	if retryAfterMS != "" {
		h.Set("retry-after-ms", retryAfterMS)
	}
	return &apiError{StatusCode: status, Response: &http.Response{StatusCode: status, Header: h}}
}

// named gives a scripted model a provider and model name, as an adapter
// reports them.
type named struct {
	weft.Model
	info weft.ModelInfo
}

func (n named) Info() weft.ModelInfo { return n.info }

func model(provider, name string, turns ...wefttest.Turn) (*wefttest.Model, weft.Model) {
	s := wefttest.Script(turns...)
	return s, named{Model: s, info: weft.ModelInfo{Provider: provider, Name: name}}
}

// attemptLog is a slog handler that prints the loop's "model attempt"
// Debug lines, the log form of each reported attempt, and drops the rest.
type attemptLog struct{ w io.Writer }

func (h attemptLog) Enabled(context.Context, slog.Level) bool { return true }
func (h attemptLog) WithAttrs([]slog.Attr) slog.Handler       { return h }
func (h attemptLog) WithGroup(string) slog.Handler            { return h }
func (h attemptLog) Handle(_ context.Context, r slog.Record) error {
	if r.Message != "model attempt" {
		return nil
	}
	var b strings.Builder
	r.Attrs(func(a slog.Attr) bool {
		switch a.Key {
		case "wait": // rounded to 5 ms: a backoff carries ±25% jitter
			fmt.Fprintf(&b, " wait=%v", a.Value.Duration().Round(5*time.Millisecond))
		case "attempt", "model", "layer", "retry_after", "status", "err":
			fmt.Fprintf(&b, " %s=%v", a.Key, a.Value)
		}
		return true
	})
	fmt.Fprintln(h.w, "  attempt"+b.String())
	return nil
}

func attempts(w io.Writer) weft.Option { return weft.Logger(slog.New(attemptLog{w})) }

// errWarmingUp is an application error a custom classifier retries.
var errWarmingUp = errors.New("model is warming up")

func retryDemo(ctx context.Context, w io.Writer) error {
	script, primary := model("acme", "large",
		wefttest.Fail(errWarmingUp),            // retried by the custom classifier, after a backoff
		wefttest.Fail(providerError(429, "5")), // rate limited: asks for 5 ms
		wefttest.Say("Order 1234 has shipped."),
	)
	agt := weft.New(primary,
		weft.WrapModel(mw.Retry(
			mw.MaxRetries(3),                  // retries after the first try (default 3)
			mw.BaseDelay(10*time.Millisecond), // first backoff (default 500ms), doubling, capped at 8s
			mw.MaxWait(30*time.Second),        // a longer retry-after fails at once (default 60s)
			mw.Classifier(func(err error) bool {
				return mw.Retryable(err) || errors.Is(err, errWarmingUp)
			}),
		)),
		attempts(w), // print each reported attempt
	)
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "retry: %q after %d requests\n", res.Text(), len(script.Requests()))
	return nil
}

func retryAfterTooLong(ctx context.Context, w io.Writer) error {
	script, primary := model("acme", "large", wefttest.Fail(providerError(429, "120000"))) // asks for 2 minutes
	agt := weft.New(primary, weft.WrapModel(mw.Retry()))
	_, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	var apiErr *apiError
	fmt.Fprintln(w, "too long:", errors.Is(err, mw.ErrRetryAfterTooLong), errors.As(err, &apiErr))
	fmt.Fprintf(w, "too long: %d request\n", len(script.Requests()))
	return nil
}

func retryHelpers(w io.Writer) {
	err := providerError(429, "250")
	status, _ := mw.HTTPStatus(err)          // 429, from the StatusCode field
	ask, _ := mw.RetryAfter(err, time.Now()) // 250ms, from retry-after-ms
	fmt.Fprintln(w, "helpers:", status, ask, mw.Retryable(err))

	overflow := errors.New("400: prompt is too long: 210000 tokens > 200000 maximum")
	fmt.Fprintln(w, "overflow:", mw.IsContextOverflow(overflow), mw.Retryable(overflow))
}

func fallbackDemo(ctx context.Context, w io.Writer) error {
	_, primary := model("acme", "large",
		wefttest.Fail(providerError(503, "5")),
		wefttest.Fail(providerError(503, "5")),
	)
	backupScript, backup := model("other", "small", wefttest.Say("Order 1234 has shipped."))
	agt := weft.New(primary,
		weft.WrapModel(
			mw.Fallback(backup), // outer: switch models once Retry gives up
			mw.Retry(mw.MaxRetries(1), mw.BaseDelay(10*time.Millisecond)), // inner: retry the primary
		),
		attempts(w),
	)
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "fallback: %q, backup requests %d\n", res.Text(), len(backupScript.Requests()))
	return nil
}

func fallbackWhenDemo(ctx context.Context, w io.Writer) error {
	for _, failure := range []error{
		fmt.Errorf("%w: pdf input", weft.ErrUnsupported),
		providerError(503, ""),
	} {
		_, primary := model("acme", "large", wefttest.Fail(failure))
		_, backup := model("other", "vision", wefttest.Say("The invoice total is 120 EUR."))
		onlyUnsupported := func(err error) bool { return errors.Is(err, weft.ErrUnsupported) }
		agt := weft.New(primary, weft.WrapModel(mw.FallbackWhen(onlyUnsupported, backup)))
		res, err := agt.Generate(ctx, weft.Prompt("Read the attached invoice."))
		if err != nil {
			fmt.Fprintln(w, "fallback-when:", err) // a 503 is not ErrUnsupported: no fallback
			continue
		}
		fmt.Fprintf(w, "fallback-when: %q\n", res.Text())
	}
	return nil
}

// reportAttempts reports every call through it as one attempt on the
// run's record: an attempt span under the step's chat span, and a
// "model attempt" Debug line on the agent's Logger.
func reportAttempts(next weft.Model) weft.Model { return attemptReporter{next} }

type attemptReporter struct{ next weft.Model }

func (m attemptReporter) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	return func(yield func(weft.ModelEvent, error) bool) {
		info, start := weft.InfoOf(m.next), time.Now()
		var failed error
		for ev, err := range m.next.Stream(ctx, req) {
			failed = err
			if !yield(ev, err) || err != nil {
				break
			}
		}
		status, _ := mw.HTTPStatus(failed)
		weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{
			Model: info.Name, Provider: info.Provider,
			Start: start, End: time.Now(),
			Err: failed, HTTPStatus: status,
		})
	}
}

func (m attemptReporter) Info() weft.ModelInfo { return weft.InfoOf(m.next) }
func (m attemptReporter) Unwrap() weft.Model   { return m.next }

// ReportsAttempts tells a reporting layer above (mw.Retry, mw.Fallback)
// that this one reports, so each request is reported once.
func (m attemptReporter) ReportsAttempts() bool { return true }

func reportDemo(ctx context.Context, w io.Writer) error {
	_, primary := model("acme", "large",
		wefttest.Fail(providerError(500, "")),
		wefttest.Say("Order 1234 has shipped."),
	)
	agt := weft.New(primary,
		weft.WrapModel(mw.Retry(mw.BaseDelay(0)), reportAttempts), // Retry stays silent: reportAttempts reports
		attempts(w),
	)
	res, err := agt.Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		return err
	}
	// Outside a run's model call the reporter is a no-op: nothing prints.
	weft.ReportFromContext(ctx).Attempt(weft.AttemptInfo{Model: "ignored"})
	fmt.Fprintf(w, "report: %q\n", res.Text())
	return nil
}

// demoRetries is the retries-and-fallback page's complete example.
func demoRetries(ctx context.Context, w io.Writer) error {
	if err := retryDemo(ctx, w); err != nil {
		return err
	}
	if err := retryAfterTooLong(ctx, w); err != nil {
		return err
	}
	retryHelpers(w)
	for _, demo := range []func(context.Context, io.Writer) error{fallbackDemo, fallbackWhenDemo, reportDemo} {
		if err := demo(ctx, w); err != nil {
			return err
		}
	}
	return nil
}
```

[middleware/retries.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/middleware/retries.go)

Run it from `docs-site/examples`:

```sh
go run ./middleware retries
go test ./middleware
```

```text
  attempt attempt=1 model=large err=model is warming up
  attempt attempt=2 model=large retry_after=5ms layer=retry wait=10ms status=429 err=provider: 429 Too Many Requests
  attempt attempt=3 model=large layer=retry wait=5ms
retry: "Order 1234 has shipped." after 3 requests
too long: true true
too long: 1 request
helpers: 429 250ms true
overflow: true false
  attempt attempt=1 model=large retry_after=5ms status=503 err=provider: 503 Service Unavailable
  attempt attempt=2 model=large retry_after=5ms layer=retry wait=5ms status=503 err=provider: 503 Service Unavailable
  attempt attempt=3 model=small layer=fallback
fallback: "Order 1234 has shipped.", backup requests 1
fallback-when: "The invoice total is 120 EUR."
fallback-when: weft: run failed at step 0: model stream: provider: 503 Service Unavailable
  attempt attempt=1 model=large status=500 err=provider: 500 Internal Server Error
  attempt attempt=2 model=large
report: "Order 1234 has shipped."
```

The `attemptLog` handler rounds `wait` to 5 ms, because a backoff carries jitter.

## Best practices & gotchas

- **Put `mw.Fallback` outside `mw.Retry`.** The primary is retried to exhaustion before the backup is tried. (Source: `weft/core/mw/doc.go:15-19`)
- **Switch the SDK's retries off when you use `mw.Retry`.** `openai.MaxRetries(0)` and `anthropic.MaxRetries(0)` stop the SDK sleeping on a retry-after inside the idle timer. (Source: `weft/core/mw/retry.go:93-108`, `weft/CHANGELOG.md:5660`)
- **Expect nothing to be retried after the first event.** Part of the reply has reached the loop; the failure is the run's error. (Source: `weft/docs/adr/0006-seams.md:93-96`)
- **Do not retry a context overflow.** The same bytes cannot fit; compact or shorten the request. (Source: `weft/core/mw/retry.go:283-291`, `weft/core/mw/retry.go:467-473`)
- **Use `BaseDelay(0)` only in tests.** The default is 500ms doubling to 8s; zero removes the spacing a rate-limited provider needs. (Source: `weft/mw/example_test.go:28`)
- **Expect the backup's error when the backup fails too.** `errors.Is(err, weft.ErrUnsupported)`, an `mw.HTTPStatus` check for a 429, or a log line on the run error all see the last model's error, so a misconfigured backup (no key, a wrong model id) hides the primary's real failure. Read the primary's error on the `attempt` spans or in Studio's attempts, or classify it in a `FallbackWhen` predicate before the backup runs. (Source: `weft/core/mw/model.go:118-125`, `weft/core/mw/model.go:38-44`)
- **Declare `ReportsAttempts` when your layer reports.** Without it, a `mw.Retry` above reports the same requests again. (Source: `weft/core/report.go:151-157`, `weft/core/mw/model.go:253-283`)

## See also

- [Add behaviour with middleware (the two seams)](https://weftgo.dev/docs/guides/middleware/)
- [Connect a model provider: OpenAI, Anthropic, Gemini](https://weftgo.dev/docs/guides/providers/)
- [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/)
- [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/)
- [The record contract](https://weftgo.dev/docs/reference/record-contract/)

Symbols used: [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) · [`mw.RetryOption`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryOption) · [`mw.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxRetries) · [`mw.BaseDelay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#BaseDelay) · [`mw.MaxWait`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxWait) · [`mw.Classifier`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Classifier) · [`mw.Retryable`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retryable) · [`mw.RetryAfter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#RetryAfter) · [`mw.HTTPStatus`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#HTTPStatus) · [`mw.IsContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#IsContextOverflow) · [`mw.ErrRetryAfterTooLong`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#ErrRetryAfterTooLong) · [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) · [`mw.FallbackWhen`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#FallbackWhen) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.ReportFromContext`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ReportFromContext) · [`weft.Reporter`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Reporter) · [`Reporter.Attempt`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Attempt) · [`Reporter.Raw`](https://pkg.go.dev/github.com/weftgo/weft/core@v0.20.2#Reporter.Raw) · [`weft.AttemptInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptInfo) · [`weft.AttemptLayerFallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#AttemptLayerFallback) · [`weft.InfoOf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#InfoOf) · [`weft.Logger`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Logger) · [`weft.ErrStreamIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrStreamIdle) · [`weft.ErrUnsupported`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrUnsupported) · [`weft.ErrContextOverflow`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrContextOverflow) · [`openai.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#MaxRetries) · [`anthropic.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/anthropic#MaxRetries) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
