# Timeouts, Retries and Backoff

> Setting timeouts, retrying only what is safe and backing off without flooding a model API or the service behind it, explained simply for your AI interview.

**In short:** A timeout is the longest a call may wait. A retry sends a failed call again, and backoff spaces the tries further apart. Set a timeout on every call, retry only what is safe to repeat, and cap the attempts, so a struggling service is not buried.

AI and LLM interview question Q337, Inference, performance and cost. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/timeouts-retries-and-backoff

## Say it in 30 seconds

A timeout is the longest I'll wait for an answer. If a call fails in a way that's safe to repeat, I retry it, waiting a little longer each time and adding a random part, so many jobs don't retry together. I cap the tries and the total time. I check that a repeat is safe, because a retry can send a second refund email. And I don't let every layer of the stack retry on its own, because the attempts multiply.

## Say it in 2 minutes

Every call to a model or another service needs a timeout. Without one, a hung request keeps its connection and its worker busy until something gives up. That matters for AI apps, because one long generation can run for minutes. I pick the timeout from the measured latency of the service I call. I start from its slow end, the 99.9th percentile, and add room for the network. Too high and resources sit idle. Too low and healthy slow answers get cut off and sent again, which adds load.

Some failures clear up on their own: a timeout, a rate-limit 429, or a server error. A spend-cap 429 does not, so I stop there. For the rest I retry, but only when repeating is safe. A read is safe. A refund or a sent email may not be, unless the service supports idempotency, a key that makes a repeat do nothing new. Then I back off, with each wait longer than the last, a cap on the wait, and random jitter so that clients don't all retry at the same moment. I also set one total budget for the whole request, so retries can't keep a user waiting for minutes.

Retries multiply. If five layers each try three times, one user request becomes 243 attempts at the database, which is how a small blip turns into an outage. So I retry at one layer and let the others fail fast.

Anthropic's SDK retries by default up to two times, and waits as long as the retry-after header asks. Its docs also say the SDK doesn't retry an error inside a stream, so I handle those in my own code. For long generations I use streaming or the batch API, not one long wait.

## What are timeouts, retries and backoff, in plain words?

A model call goes over a network to a server you don't control. It can be slow, fail for a moment, or hang without answering. Three tools keep your app safe. A timeout is how long you wait. A retry sends the same call again. Backoff makes each new try wait a little longer than the one before.

Picture a hospital pharmacist waiting on the lab for a result. She waits ten minutes, then calls again. If the lab is swamped, she waits longer before each call, and she doesn't ring every minute with all her colleagues at once. After a few tries she stops and reports the delay to the ward.

Here is a real case. An insurer's claims agent sends a 40-page policy to a model. Usually the summary comes back in about 20 seconds. Sometimes the connection drops, and sometimes the model is busy. The team has to decide how long to wait, when to try again, and when to stop.

- **Timeout:** The longest a call may wait before you stop and treat it as failed.
- **Retry:** Sending a failed call again, in the hope that it now works.
- **Backoff:** Making each new try wait longer than the one before.
- **Jitter:** A random part added to each wait, so many clients don't retry together.
- **Idempotent:** An action that has the same effect however many times you run it, so a repeat is safe.

## How do you set a timeout, and how do you pick its number?

A hung call holds its connection, its memory and its worker until something gives up. If many calls hang at once, the app runs out of those and stops serving everyone, including the calls that were fine.

Amazon's best practice is to set a timeout on every call to another service, with two limits: one for connecting, and one for the whole request. The connect limit catches a server that never answers. The request limit catches a model that is still generating long after it should have finished.

- **Too long: Resources sit idle.** The caller waits, the connection stays open, and stuck calls pile up.
- **Too short: Good calls get cut off.** Slow but correct answers fail, so the retries add load to a busy service.
- **Right: Set from real timings.** Start from the slow end of the service's own latency, then add room for the network.

Measure the timeout instead of guessing it. Amazon starts from the downstream service's own latency at a high percentile, then picks the point that matches an acceptable rate of false timeouts.

1. **Read the slow end:** Look at the service's latency at a high percentile, such as the 99.9th. That means only about one call in a thousand is slower.
2. **Allow for the network:** Calls that cross the internet are slower than calls inside one data centre. Add the worst delay you expect from your users' side.
3. **Keep the whole run in budget:** Give the user's request one total time limit, and share what is left with each try. Then the retries can't stretch the wait for minutes.
4. **Stream long answers:** Anthropic advises the streaming API or batches for long-running requests, especially those over 10 minutes. Streaming sends the answer in pieces, so the user is not left facing one long wait.

Worked example. The claims agent's measured 99th percentile is 22 seconds on a normal day. A 10-second timeout would cut off far more than one good answer in a hundred. Each cut-off call gets sent again, so the model is hit hardest on its busiest day. I set the timeout at 40 seconds, and I count the timeouts in the logs after every release.

## Which failures are safe to retry, and how long do you wait?

Start with the status code. A 400 usually means the request itself is wrong, so sending it again gets the same 400. A 429 means too many requests, and a rate limit may clear up. A spend-cap 429 is different: it keeps failing until access resumes, so retrying it does no good. A 5xx means the server failed, and it may clear up on its own, as may a timeout.

> "Otherwise, the SDK retries connection errors, timeouts, and the statuses 408, 409, 429, and 500 and above." (Anthropic, API errors)
>
> "It indicates that client errors should not be retried with the same request because they aren't going to succeed later, while server errors may succeed on subsequent tries." (Amazon Builders' Library)

Anthropic's SDK mostly follows that split. By default it retries a failed request up to two times, so three attempts in all. If the reply has a retry-after header, it waits as long as the header says. Otherwise it uses exponential backoff from 0.5 to 8 seconds. It also retries 408, 409 and 429, which are 4xx client errors, so treat the split as a rule of thumb.

Azure's architecture guide adds the other half: if a failure is unlikely to succeed when repeated, cancel the call and report it. Streams are different. The SDK doesn't retry an error inside a stream, so your code has to catch it.

If every failed call retries after one second, they all come back together and hit the same wall. Backoff fixes the timing. The most common pattern is an exponential backoff, where the wait time is increased exponentially after every attempt, and it is capped so the wait never grows without limit.

A capped wait has a flaw. If many clients share it, they all retry at the same capped gap, again and again, and the spikes come back. Jitter adds randomness so the retries spread out in time. In AWS's example with 100 contending clients, that cut the total number of calls by more than half.

*Diagram, Deciding whether a failed call is retried: Every failed call goes through a safety check first. Safe calls wait, with growing random gaps, inside a budget. Unsafe calls go back to the caller, so nothing is repeated by accident.*
1. A failed call goes to a safety check first.
2. If repeating is safe, the retry waits, with growing and random gaps.
3. If repeating is not safe, the error goes back to the caller.
4. The retries stop at the budget, with an answer or a clear error.

> **Tip:** Name the three parts when you answer: a wait that grows, a random part, and a limit on the attempts.

## What goes wrong when every layer retries?

Retries multiply. Each layer that calls the next one may retry on its own, so the attempts stack up at the bottom. AWS's example is a stack five calls deep, where the database starts failing under load.

> "If each layer retries independently, the load on the database will increase 243x, making it unlikely to ever recover." (Amazon Builders' Library)

*Diagram, Retries at every layer versus one layer: This chart draws three layers, so it shows 9 database calls: two retrying layers with three tries each. Five such layers give the 243 calls in the example below. When only the top layer retries, the database sees a small, steady load it can recover from.*
1. Each layer retries its own calls, so the database gets every retry multiplied.
2. Only the top layer retries, so the database sees a small, steady load.

The sum is simple. Five layers, each trying three times, is three to the power of five, which is 243 attempts for one user request. Retrying at one layer keeps it to a few calls.

```python
# Made-up checkout service: a database that fails every call, behind five layers.
db_calls = 0

def database_call():
    global db_calls
    db_calls += 1
    raise ConnectionError("database overloaded")

def layer(level):
    if level == 0:
        return database_call()
    for _ in range(3):
        try:
            return layer(level - 1)
        except ConnectionError:
            pass
    raise ConnectionError("layer " + str(level) + " gave up")

try:
    layer(5)
except ConnectionError as error:
    print(error)
print("database calls for one user request:", db_calls)
```

Output:

```text
layer 5 gave up
database calls for one user request: 243
```

Azure's guide warns that a retry inside a retry adds long delays. For low-cost operations, Amazon's advice is to pick one point in the stack that retries. That choice has a cost, because retrying high up may waste work that lower layers already did.

## Can you retry a call that changes data?

Only when a repeat does no harm. Reads are usually safe to repeat. A call that refunds money, sends an email or books a slot may already have done its job when the reply times out, so a timeout doesn't tell you what happened.

Azure gives the classic case: a service may receive a request, process it, and then fail to send the reply, so the retry asks it to do the work a second time. Amazon's view is that a timeout or failure doesn't necessarily mean the side effects haven't happened.

Worked example. An agent sends a refund confirmation to a customer. The call times out, but the email already went out. A blind retry sends a second confirmation. The fix is to look up the message in the agent's own outbox first. Where the mail or payments service supports idempotency keys, the agent sends a key with the request, so a repeat does nothing new. If neither check is possible, the agent asks a person instead of guessing.

> **Tip:** Say it like this in the interview: I retry reads freely, and I retry writes only with a key or a check that makes a repeat harmless.

### How would you set timeouts and retries for an agent that calls three tools?

An agent may make several calls for one answer: a search, a database lookup and an email. Each needs its own limits, and the whole run needs one too.

1. **Give each tool its own timeout:** Use each tool's measured slow end. A search can be quick, while a report generator needs more room.
2. **Put one budget on the whole run:** For example, 60 seconds in total. When it runs out, the agent stops and tells the user what is still pending.
3. **Retry reads, not writes:** Reads get a retry or two with jittered backoff. Writes retry only with an idempotency key or a check of what already happened.
4. **Log every timeout and retry:** Then you can see which tool causes the trouble, and whether a limit is set too short.

The interviewer usually wants the order: limits first, then retries, then the budget that holds them together.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Every remote call gets a timeout, with separate connect and request limits.
- [ ] Timeouts come from measured latency, not a guess.
- [ ] Retry only what is safe to repeat: the status code first, then idempotency.
- [ ] Backoff grows each time and adds jitter, with a cap on the attempts.
- [ ] Retries happen at one layer, inside a total budget for the request.
- [ ] Long generations use streaming or batches, not one long wait.

**Common traps**

- Trap: "Set a 30-second timeout and retry five times." Better: Pick the timeout from measured latency, and cap the total time, not just the number of tries.
- Trap: "Retry everything, it will work eventually." Better: A retried write can repeat its side effect. Check idempotency before you retry a write.
- Trap: "Every layer should retry, to be safe." Better: Each extra layer multiplies the attempts. Pick one layer to retry and let the others fail fast.

## Can you spot the risk?

**Spot the risk:** Which setting could leave a claims agent waiting for minutes?

A. timeout=40, max_retries=2, backoff=jittered
B. timeout=None, max_retries=10, backoff=none
C. timeout=20, max_retries=0, for a read-only lookup
D. timeout=60 total, attempts=3, backoff cap=8 seconds

**Answer:** B. With no timeout, a hung call can wait forever, and ten retries with no spacing pile load on a struggling service. The other three set a limit, a spacing or a budget.

**Quick check:** A refund call times out. What should the agent do first?

A. Retry at once, three times
B. Check whether the refund happened, or repeat with the same idempotency key
C. Charge the card again to be safe
D. Turn off timeouts for payments

**Answer:** B. A timeout doesn't tell you whether the refund went through. Check first, or repeat with the same key, so one refund stays one refund.

## Can you answer these from memory?

**Flash cards**

- **What is a timeout?** The longest a call may wait before you stop and treat it as failed.
- **Which failures get a retry?** Ones that may clear up, like a timeout, a 5xx or a rate-limit 429. Not a bad request or a spend-cap 429.
- **Why add jitter?** A random part stops many clients retrying together at the same moment.
- **What is idempotency?** A repeat has the same effect as one call, so retrying a write is safe.
- **Why not retry at every layer?** Attempts multiply. Five layers of three tries reach the database 243 times.
- **What caps a retry loop?** A maximum number of attempts plus a total time budget for the whole request.

## Likely follow-up questions

- Q330 How do you handle rate limits and 429 errors? https://designervenkat.online/interview/ai/how-do-you-handle-rate-limits-and-429-errors
- Q343 Multi-provider fallback? https://designervenkat.online/interview/ai/multi-provider-fallback
- Q344 What is a p95/p99 latency budget? https://designervenkat.online/interview/ai/what-is-a-p95-p99-latency-budget
- Q365 Idempotency, queues and retries? https://designervenkat.online/interview/ai/idempotency-queues-and-retries
- Q317 The latency vs throughput trade-off? https://designervenkat.online/interview/ai/the-latency-vs-throughput-trade-off
- Q355 What is your fallback when a provider is down? https://designervenkat.online/interview/ai/what-is-your-fallback-when-a-provider-is-down
