← Home · Tutorial 17 · Production engineering

Retries and failure handling

How many attempts, how long to wait, and what to wrap: retrying failed AI calls with Tenacity, and the mistake hiding in the wait settings.

Last reviewed 28 October 2026 · Written with AI assistance and reviewed by me

Where this comes from: a support agent I built, which wraps its outside calls with the Python library Tenacity. The error-code guidance follows Anthropic's API errors page (checked 28 October 2026). Tenacity's official docs could not be fetched this session, so every Tenacity behaviour on this page was confirmed by running it against Tenacity 9.2.1 instead. The examples are my own, and every snippet was run to produce the output shown.
Who this is for: anyone whose AI app calls a model or a search service over the network and has seen one of those calls fail for no clear reason. You will learn the three decisions behind a sensible retry (how many attempts, how long to wait, what to wrap), the mistake that hides in the wait settings, and the refinements that make retries safe.

1A two-second hiccup

Why an agent needs a plan for failed calls.

A typical AI support agent makes several calls to outside services for every question: one model call to classify the message, a search call to find the answer, and a second model call to write the reply. Any of them can fail for reasons that have nothing to do with your code: a dropped connection, a brief overload, a rate limit.

One question, three outside calls
Classifymodel call
→
Searchretrieval service
→
Replymodel call

Most of these failures clear up within seconds. Without a plan, though, one failed call ends the whole conversation. A retry is that plan: try again, but in a controlled way.

2Which failures to retry

Retry what waiting can fix. Fail fast on the rest.

Only some failures are worth a second try. The rule of thumb: retry what waiting can fix, and fail fast on everything else. The codes below are from Anthropic's API errors page; other providers use similar ones.

What happenedWhat it meansRetry?
Connection dropped or timed outA network or server hiccupYes
429 rate_limit_errorToo many requests for your current limitYes, after waiting. One exception: a 429 from hitting a monthly spend cap keeps failing until access resumes
500 api_errorAn unexpected error on the provider's sideYes, with backoff (the docs say so)
529 overloaded_errorThe API is temporarily overloadedYes, after waiting
400, 401, 403A malformed request, a bad key, or no permissionNo. It will fail the same way every time
Retrying the wrong error is not harmless. Three attempts at a request with an invalid API key just means three slow failures before the real error shows up.

3How many attempts

A ceiling of three, and what happens when all three fail.

Tenacity adds retries to a function with one decorator. The version below uses the settings from my agent: at most 3 attempts, with a growing wait between them. The fake model call fails twice, then succeeds.

Python
from tenacity import retry, stop_after_attempt, wait_exponential
calls = {"n": 0}

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def call_model(prompt):                      # stand-in for a real model call
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError("connection dropped")
    return "Billing"

waits = []
call_model.retry.sleep = waits.append        # record each wait instead of sleeping, so the demo runs instantly

print("result:", call_model("Can I get a refund?"))
print("attempts:", calls["n"], "| waits (seconds):", waits)
Output (run to check)
result: Billing
attempts: 3 | waits (seconds): [2.0, 2.0]

Three attempts is a sensible ceiling for a live conversation. Most brief failures clear on the second or third try, and a customer will not wait much longer than that. When all three fail, something is really wrong, and the error should come through rather than loop forever.

One detail surprised me: by default, Tenacity does not raise your original error after the last attempt. It raises its own RetryError with the original tucked inside:

Python
from tenacity import retry, stop_after_attempt, wait_exponential, RetryError

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def call_model(prompt):
    raise ConnectionError("service down")    # fails every time

call_model.retry.sleep = lambda s: None
try:
    call_model("hello")
except RetryError as e:
    print("caught:", type(e).__name__)
    print("the real error inside:", repr(e.last_attempt.exception()))
Output (run to check)
caught: RetryError
the real error inside: ConnectionError('service down')

Any code above it that catches ConnectionError will miss this. Card 6 shows the one-word fix.

4How long to wait

Exponential backoff, and the mistake in the settings.

Waiting longer after each failure is called exponential backoff. An overloaded service needs room to recover, and hitting it again instantly makes the overload worse. Tenacity's wait_exponential doubles the wait each time, then clamps it between min and max.

Here is the mistake I made. I believed my settings meant "wait 2, then 4, then 8 seconds". Running it shows otherwise:

Python
from tenacity import wait_exponential

class Attempt:                               # the one field wait_exponential reads
    def __init__(self, n): self.attempt_number = n

for label, w in [("multiplier=1, min=2, max=10", wait_exponential(multiplier=1, min=2, max=10)),
                 ("multiplier=2, min=2, max=10", wait_exponential(multiplier=2, min=2, max=10))]:
    print(label, "->", [float(w(Attempt(n))) for n in range(1, 5)])
Output (run to check)
multiplier=1, min=2, max=10 -> [2.0, 2.0, 4.0, 8.0]
multiplier=2, min=2, max=10 -> [2.0, 4.0, 8.0, 10.0]
SettingWhat it doesWaits actually used with 3 attempts
multiplier=1, min=2The first two waits are 1 and 2 seconds, and min=2 raises the first to 22s, 2s
multiplier=2, min=2Starts at 2 and doubles2s, 4s
Two things to check. With 3 attempts there are only 2 waits, because there is no wait after the final failure. And a min can flatten the start of the curve. To actually get 2, 4 and 8 seconds, you need multiplier=2 and 4 attempts.

Many systems also add a small random amount to each wait, called jitter, so that many clients that failed together do not all retry at the same moment. Tenacity offers wait_random_exponential for this.

5What to wrap

Only the risky call, never the logic around it.

The third decision is where the decorator goes. Put it only on the function that makes the network call, not on the whole step around it.

What gets retried, and what does not
_call_classifier()network call: retried
→
Clean and check the labellocal logic: runs once
→
Route the messageuses a known-good value
Python
from tenacity import retry, stop_after_attempt
ALLOWED = {"Billing", "Technical", "Sales", "General"}
calls = {"model": 0, "validate": 0}

@retry(stop=stop_after_attempt(3))
def _call_classifier(text):                  # only the risky network call is retried
    calls["model"] += 1
    if calls["model"] < 3:
        raise TimeoutError("timed out")
    return " billing\n"

def classify(text):                          # the step: one call, then local logic
    raw = _call_classifier(text)
    calls["validate"] += 1
    label = raw.strip().title()
    return label if label in ALLOWED else "General"

_call_classifier.retry.sleep = lambda s: None
print("label:", classify("Why was I charged twice?"))
print("model calls:", calls["model"], "| validation runs:", calls["validate"])
Output (run to check)
label: Billing
model calls: 3 | validation runs: 1

The model call ran three times. The validation ran once, on the answer that finally came back. If the decorator wrapped the whole step instead, every retry would also repeat the logic around the call, including anything that writes, logs or sends.

The same rule applies to tools. A tool that only reads local data has no network to fail on, so it gets no retry at all.

6Retry only what a wait can fix

Filter errors, and raise the real one.

My first version retried any error, so a bad API key got three slow, doomed attempts. Two more arguments fix that: retry= limits retries to errors a wait can fix, and reraise=True raises the real error at the end instead of RetryError.

Python
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type

calls = {"n": 0}

@retry(stop=stop_after_attempt(3),
       wait=wait_exponential(multiplier=1, min=2, max=10),
       retry=retry_if_exception_type((ConnectionError, TimeoutError)),   # only what a wait can fix
       reraise=True)                                                     # raise the real error, not RetryError
def call_model(prompt, error):
    calls["n"] += 1
    raise error

call_model.retry.sleep = lambda s: None
for err in [TimeoutError("timed out"), PermissionError("invalid API key")]:
    calls["n"] = 0
    try:
        call_model("hi", err)
    except Exception as e:
        print(f"{type(e).__name__:<16} attempts: {calls['n']}")
Output (run to check)
TimeoutError     attempts: 3
PermissionError  attempts: 1

The timeout was retried three times. The permission error failed on its first attempt, which is what you want. With a provider SDK, you would list that SDK's own exception classes for timeouts, connection errors, rate limits and overload, instead of Python's built-in ones used here.

7Check the layer below

Your retry and the SDK's retry can multiply.

Before adding your own retries, check what the layer below already does. Anthropic's errors page says its official SDK already retries connection errors, rate limits and 5xx errors twice by default, with exponential backoff, and it respects the retry-after header the API sends.

Retries can multiply
Your Tenacity retryup to 3 attempts
×
SDK's built-in retryup to 3 requests each
=
Up to 9 requestsfor one failing call
Pick one layer to own retries. Either lower the SDK's max_retries and let your code decide, or rely on the SDK and keep your own retries for the services that do not have them. Agent frameworks often add a third layer, such as a retry setting on a graph node, so check there too.

8Make retries safe

Repeatable side effects, and a log line per retry.

Two habits make retries safe:

  • Make side effects safe to repeat first. If a call sends an email or charges a card, a retry after a lost response can do it twice. Give the action a unique key that the receiving side can recognise, a pattern called idempotency, before you put a retry on it.
  • Log every retry. A call that succeeds on its third attempt looks exactly like one that worked first time unless you record it. Tenacity's before_sleep hook runs before each wait and is a natural place for a log line. (See Logging for AI apps.)

9Check yourself

Short questions, a try-it and one line to remember.

What are the three decisions behind a retry?

How many attempts to allow, how long to wait between them, and which code to wrap.

With stop_after_attempt(3), how many waits happen?

Two. There is no wait after the last failure.

Why do wait_exponential(multiplier=1, min=2) waits start 2s, 2s?

The raw waits are 1s then 2s, and min=2 raises the first one to 2s.

Why wrap only the network call, not the whole step?

So the logic around the call, such as validation or writing data, runs once on the final answer, not once per attempt.

Which errors should you not retry?

Ones a wait cannot fix: a malformed request, a bad key, missing permission, or a spend cap that has been reached.

Try it: in the first snippet, change the settings to multiplier=2 and stop_after_attempt(4), make the fake call fail three times, and confirm the waits come out as 2, 4 and 8. Then add reraise=True to the "gives up" snippet and see which error it raises now.
One line to remember: "Retry only what a wait can fix, run your settings to see the real waits, and wrap only the call that can fail."
Sources: Tenacity on GitHub (version 9.2.1; behaviour on this page confirmed by running it, as the official docs could not be fetched this session); Anthropic API errors for error codes and the SDK's built-in retries (checked 28 October 2026). Libraries and defaults change, so check the current docs. Independent notes, not affiliated with or endorsed by any company or course named here. Examples and wording are my own.