Lesson 3.4: Errors, retries and rate limits
Model API calls fail, slow down and get refused. Learn which errors to retry, how backoff with jitter works, and how to plan around rate limits.
A demo works the first time because nothing has gone wrong yet. A real product runs thousands of calls a day, and some of them will fail for reasons that have nothing to do with your code: a network blip, a busy server, a limit you did not know you were close to. By the end of this lesson you will be able to sort a failed model call into "retry it", "wait and retry it" or "never retry it", write a retry schedule with exponential backoff and jitter, estimate how long a large batch job will take under a provider's rate limits, and set timeouts that fit inside the time a user is willing to wait. You should have read the earlier lessons in this module, especially the one on streaming, latency and cost, because the same request-size numbers drive everything below. No programming beyond reading a short Python function is needed.
Why calls fail, and why it is normal
When your application asks a model to do something, a long chain of machines has to cooperate: your server, the network between you and the provider, the provider's gateway that checks your key and your limits, and finally the machines that actually run the model. Any link can fail, and most of the failures are brief. A server is restarted, a data centre link drops a few packets, a burst of traffic from other customers makes the queue long. None of these is a bug in your product, and none of them will go away if you write better prompts.
It helps to think like a person who runs a courier service. Most parcels arrive. Some are delayed by rain, some are refused because the address is wrong, and some are turned back because the building only accepts deliveries between ten and noon. A good courier does not treat all three the same. Rain means try again later. A wrong address means fix the address, because trying again will never work. A delivery window means wait until the window opens. Your model calls need exactly the same three-way thinking.
Model calls have two features that make failure handling matter more than it does for an ordinary web request.
They are slow. A request that takes ten seconds and then fails wastes ten seconds of your user's time and holds a connection open the whole while.
They are metered. Many failures cost nothing, but some do: a call that produced a long answer and then dropped the connection may still be billed for the tokens it generated. Retry carelessly and you pay twice for one answer.
Here is a rough picture of where failures come from in a typical month for a busy application. The numbers are a made-up example, but the order, with limits and timeouts at the top and your own bugs near the bottom, is what many teams report.
Notice that the biggest slices are the ones a well-behaved client can recover from by waiting, and the smallest ones are the ones that need a human to fix something. Good error handling is mostly the work of recovering from the first group quietly and reporting the second group loudly.
Three kinds of failure: retry, wait, or stop
Web services report what happened with a numeric status code on every response. You do not need to memorise them, but you should know the families, because the family tells you what to do. The exact codes and wording differ between providers, so always check your provider's documentation. The families below are standard across the web.
Family · Typical meaning · What to do400 range, such as 400 or 422 · The request itself is wrong: bad field, too many tokens, invalid format · Stop. Fix the request. Retrying sends the same mistake again
401 or 403 · The key is missing, expired or not allowed to do this · Stop and alert someone. Retrying cannot help
408 or a client-side timeout · The request took too long · Retry, with care about duplicates
429 · You are sending too many requests or tokens · Wait, then retry, ideally for as long as the provider says
500 range, such as 500, 502, 503 or 504 · Something broke or is overloaded on the provider's side · Retry with backoff
200 but a bad answer · The call worked, but the output is cut off or not in your format · Handle in your own code: validate, then retry or repair
The last row catches many beginners. A response with a success status is not the same as a usable answer. In the previous lesson on structured outputs you saw that a model can return text that does not match your schema, or stop in the middle because it hit an output limit. That is an application-level failure, and your code has to detect it by checking the result, since no status code will announce it.
The first rule of retrying is simple: retry only what could succeed the second time. A request that is malformed fails identically on every attempt, so retrying it only burns time and, in a loop, can hammer the provider with hundreds of identical bad calls. A server that is briefly overloaded may well accept the same request a few seconds later.
Predict first: your service sends a request to a model and gets back a 401 error saying the key is not valid. Your code is set to retry every error up to five times with a short wait. How many of the five attempts will succeed, and what is the cost of letting them run? Decide before reading on.
None will succeed. An invalid key stays invalid, so each retry fails the same way. The cost is not only the wasted seconds. If the failure is caused by an expired key and you have a few hundred requests per minute, you create hundreds of useless extra calls per minute, and the real problem, the key, goes unreported until someone notices the pile of errors. A good retry policy has an explicit list of retryable errors and fails fast on everything else.
Retrying safely: the duplicate problem
There is a second question before you retry: is it safe to do the same thing twice? Generating a summary of a document is idempotent in the everyday sense, meaning that asking twice gives you the same kind of thing and nothing bad happens. The only cost is a few extra tokens. But suppose a model call is part of a chain where the model decides to send an email or create a refund through a tool. If the first attempt actually reached the tool and only the response was lost, a blind retry could send two emails or issue two refunds.
Two habits protect you. First, keep the model call itself separate from actions with side effects, so a retry repeats only the harmless part. Second, give each real action a unique identifier, often called an idempotency key, so that the system performing the action can recognise a repeat and ignore it. Many payment and messaging systems support such a key. We will return to tools and agents in a later module, but the habit starts here: before you add a retry, ask what happens if the first attempt secretly worked.
Backoff, jitter and the thundering herd
Suppose a call fails with a temporary error. How long should you wait before the next attempt? The tempting answer is "retry straight away", and it is almost always wrong. A server that is struggling is not helped by being asked again instantly. The better answer is exponential backoff: wait a short time before the first retry, then double the wait each time. If the first wait is 1 second, the waits are 1, 2, 4, 8, 16 seconds and so on. Early retries catch brief blips quickly, while later ones give a genuinely troubled server time to recover.
Doubling forever would soon mean waiting minutes, so you also set a cap, a longest single wait, such as 20 or 30 seconds, and a maximum number of retries, after which you give up and tell the caller. The chart shows three schedules side by side: a fixed two-second wait, doubling with no cap, and doubling with a 20-second cap.
Look at the uncapped line. By the seventh retry you would be waiting more than a minute, which is far beyond what most users, or most calling services, will tolerate. The capped line flattens out. The fixed line never gives a struggling server any extra breathing room. The capped, doubling line is the usual starting point.
Why you also need jitter
Imagine 500 users of your app each hit a brief provider outage at the same moment. All 500 calls fail together. With plain backoff, all 500 wait exactly 1 second and retry at the same instant, so the provider sees a spike of 500 requests, most of which fail again. All 500 then wait exactly 2 seconds and arrive together again. Your clients have synchronised themselves into a repeating stampede, often called a thundering herd, and the stampede can keep a recovering server down.
The cure is jitter: add randomness to each wait so the retries spread out. A common recipe, sometimes called full jitter, picks the actual wait at random between zero and the backoff value. With the first wait at up to 1 second, 500 clients now retry spread across that second, which is roughly 500 requests per second on average but with no single instant carrying them all. By the third retry, with waits drawn from 0 to 4 seconds, the same 500 clients arrive at about 125 per second. The herd has become a stream.
Here is a short Python function that puts these ideas together. You do not need to run it to follow the lesson, but read it line by line, since the structure is the same in every language.
python
import random
import time
RETRYABLE = {408, 429, 500, 502, 503, 504}
def callwithretries(send, maxretries=4, base=1.0, cap=20.0):
for attempt in range(maxretries + 1):
response = send() # one real call
if response.status < 400:
return response # success
if response.status not in RETRYABLE:
raise RuntimeError(f"Do not retry: {response.status}")
if attempt == maxretries:
raise RuntimeError("Out of retries")
wait = min(cap, base 2 attempt) # 1, 2, 4, 8 ... up to the cap
wait = random.uniform(0, wait) # full jitter
time.sleep(wait)
Four things to notice. The retryable list is explicit. The loop has a hard upper limit. The wait doubles but is capped. And the wait is randomised after the cap is applied. Most official software libraries for model providers already include something like this; if you use one, find out what its default retry count and waits are, so you know what your application is doing behind the scenes.
A worked example: how many retries are worth it
Suppose, in a quiet hour, one attempt in ten fails with a temporary error, and failures are independent, meaning one failure does not make the next more likely. That is optimistic, but it makes the arithmetic clean. The chance that a call and all of its retries fail is the failure chance multiplied by itself once per attempt. With 3 retries there are 4 attempts, so the chance that everything fails is 0.1 multiplied by itself four times, which is 0.0001, or 0.01 percent. So 99.99 percent of calls eventually succeed. With no retries, only 90 percent do. One more retry would take you to 99.999 percent, but the gain from the fourth is a hundredfold smaller than the gain from the first. That diminishing return is why a handful of retries is plenty.
The catch is the word "independent". During a real outage the failure chance may be close to 100 percent for minutes at a time, and then retrying with short waits cannot help, no matter how many you allow. The simulator lets you test both worlds. Try the failure chance at 10 percent, then at 60 percent, and see how the number of retries and the cap change the worst-case wait.
Two lessons fall out of playing with it. Without any change to your prompts, three retries lift a call that succeeds 90 percent of the time to well above 99.9 percent, which is why retries are the cheapest reliability upgrade you have. And the price is time: the worst-case wait grows quickly, so the number of retries has to be chosen together with how long the user is willing to wait. We come back to that in the section on timeouts.
Rate limits: the rule you cannot retry your way around
A rate limit is a ceiling a provider puts on how much you can use the service in a given period. It protects the provider's machines and keeps one customer from crowding out the rest. Limits are usually measured in two ways, and you must watch both.
Requests per minute: how many separate calls you may start in a minute.
Tokens per minute: how many tokens, counting both what you send and what comes back, you may use in a minute.
Whichever you hit first is the one that slows you down. If you send many small requests, the request limit usually bites. If you send fewer, larger requests such as whole documents, the token limit bites first. Providers may add daily limits, limits per model and limits that rise as your account is used for longer, so the real numbers are on your provider's pages and in your account, never in a lesson like this one. Everything below uses invented numbers for the arithmetic.
When you cross a limit the provider answers with a 429 status. Many providers also tell you how long to wait, in a header named Retry-After or in extra fields of the response, and some report how much of your allowance is left. When a provider tells you how long to wait, believe it: it knows its own queue, and it is better than any guess your backoff schedule can make. Treat your own backoff as the fallback for when no guidance arrives.
Predict first: your service must process 12,000 customer notes overnight. Each call uses about 3,000 tokens in total. Your plan allows 300 requests per minute and 400,000 tokens per minute. Which limit will slow you down, and roughly how fast can you go? Work it out before reading on.
Divide the token limit by the size of one call: 400,000 divided by 3,000 is about 133 calls per minute. The request limit allows 300. So the token limit is the binding one, and about 133 calls per minute is your ceiling. If you stay near that ceiling you will be bumping into 429 errors constantly, so a sensible team runs at about 80 percent of it, roughly 107 calls a minute. Twelve thousand calls then take about 112 minutes, a little under two hours. That is entirely workable overnight, but it would be a shock if someone had promised the whole batch in twenty minutes.
Staying under the limit instead of bouncing off it
Hitting a limit and retrying works, but it is wasteful and noisy. A better pattern is to avoid exceeding the limit in the first place.
Pace your own sends. Use a simple counter or token bucket that releases about as many requests per second as your budget allows. This keeps you under the ceiling without errors.
Use a queue. Put work on a queue and let a fixed number of workers pull from it. The number of workers, not the number of users, then controls your pressure on the provider.
Shrink the requests. Fewer tokens per call raises the number of calls the token limit allows. Shorter prompts, trimmed documents and a lower maximum output length all help. The cost lesson in this module shows how much of a bill sits in the input.
Separate urgent from patient work. A user waiting on a screen needs an answer in seconds. An overnight report can wait. Many providers also offer a cheaper batch mode for work that can wait, which we cover in the caching and batching lesson at the end of this track.
Ask for more. If your real traffic needs a higher ceiling, request one from the provider ahead of time. Doing so on the morning of a launch is too late.
The next simulator is the batch calculation from the example. Set your own document count and call size, then see which limit is the bottleneck and how many hours the job takes. The second chart shows how the time depends on request size, which is the lever you control most easily.
Slide the tokens-per-call value from 3,000 down to 1,500. Because the token limit is the one that bites, halving the size of each call halves the time until the request limit takes over. That is a far cheaper fix than most teams expect, and it also lowers the bill.
Timeouts: deciding when to stop waiting
A request that never returns is worse than one that fails. A timeout is a limit you set on how long you will wait before treating a call as failed. Without one, a stuck connection can hold a worker, a user's screen and a database transaction hostage for minutes.
Model calls need a more careful timeout than ordinary web calls, because their duration varies so much. A short answer may take two seconds and a long one forty. Two practical ideas help.
Measure, then set. Look at how long your real calls take. The 95th percentile, meaning the time within which 95 of every 100 calls finish, is a good guide. Set the timeout somewhat above it, so only the unusually slow calls are cut off.
Treat streaming differently. When you stream tokens as they are produced, two separate waits matter: the time until the first token arrives, and the gap between tokens. A streaming call can legitimately run a long time in total while still being healthy. Many teams set a short timeout on the first token and a looser one on the gap between tokens, instead of one rule for the whole reply.
The trap is that timeouts and retries multiply. If each attempt can take up to 30 seconds and you allow three attempts, a failing call can occupy 90 seconds, plus the waits between attempts. The user, meanwhile, gave up after about 20. So you work backwards from the time the user will tolerate: that total budget is divided among the attempts and the waits. If the user will wait 20 seconds, and you want three attempts with about 2 seconds between them, you have roughly 16 seconds left for the attempts, about 5 seconds each. A 30-second timeout on a screen that someone is staring at simply cannot work.
If the numbers refuse to fit, change the design, not only the settings. An interactive screen can show a friendly "still working" message, switch to a faster or cheaper model on the final attempt, or move the work to the background and notify the user when it is done.
Beyond retries: fallbacks, circuit breakers and visibility
Retries handle brief trouble. For longer trouble you need a second layer, so the whole product does not freeze when a provider is struggling.
A fallback. If the first choice keeps failing, try something else: a second model from the same provider, a model from another provider, a cached earlier answer, or a plain non-AI path such as showing the raw document. The fallback does not have to be as good. It has to be better than an error page.
A circuit breaker. If a large share of recent calls have failed, stop sending new calls for a short time, usually tens of seconds, and answer from the fallback straight away. The name comes from the electrical device that cuts power to prevent damage. It protects the provider, which stops being hammered, and your users, who stop waiting on calls that are almost certain to fail. After the pause, the breaker lets a few test calls through. If they succeed, normal service resumes.
A queue for patient work. Anything the user is not watching should go through a queue, so a bad hour on the provider's side delays results rather than losing them.
Logging that tells you why. Record for each failure the status code, the attempt number, the wait, the size of the request and a request ID if the provider returns one. Without it, "it sometimes fails" is all you will ever know. With it, you can answer "is this our bug, the provider's, or our limit?".
Alerts on the right things. A single failed call is noise. A rising share of failures, a stream of 401 errors, or a daily total creeping towards the limit are signals worth waking someone for.
Three worked examples
1. A support chat inside a lending app. A borrower asks, "When is my next EMI due?" and a model drafts the reply using the loan record. The screen can wait about eight seconds. The team sets a 4-second timeout on the first token, allows one retry with a short, jittered wait of up to a second, and then falls back to a plain template that reads the due date straight from the database: "Your next instalment of Rs 8,450 is due on 5 December." The fallback is not conversational, but the borrower gets the right answer almost every time, whether or not the model is healthy. Total worst case: about nine seconds, which the team accepts for a rare event.
2. An overnight batch for a collections team. A lender wants a short summary of 12,000 account notes ready before the 9 a.m. shift. The team uses the calculation above: a ceiling of about 133 calls a minute, and they run at 80 percent, which finishes in about two hours. They put the notes in a queue with eight workers that each respect a shared pace limit. When a 429 arrives, workers pause for the time the provider reports and then continue. A report at 7 a.m. lists notes that failed after all retries, so a person can handle them. Nothing the batch does is shown to a user in real time, so patience is cheap.
3. A document pipeline that duplicated work. A team's code retried every error up to five times. One day the provider reported 400 errors because a new field in the team's request was invalid. Every document was retried five times with no wait. A job of 2,000 documents produced 10,000 failing calls in a few minutes, tripped the rate limit for the whole account and blocked a second team sharing the same key. The fix took five lines: a list of retryable codes, fail-fast on the rest, a backoff with jitter, and an alert when the same non-retryable error appeared more than twenty times in a minute.
Common mistakes
Retrying everything. Retrying a malformed request or a bad key wastes time and can trigger limits. Keep an explicit list of retryable errors.
Retrying instantly. An immediate second attempt hits the same busy server. Wait first, and double the wait.
Backoff without jitter. Clients that retry in lockstep produce repeating spikes. Add randomness.
No cap and no maximum. Unlimited doubling and unlimited attempts produce waits no one tolerates and loops that never finish.
Ignoring the wait the provider tells you. If a 429 response says how long to wait, use that number.
Treating a 200 as a good answer. Check that the output is complete and matches your format before you use it.
Stacking timeouts and retries without doing the sum. Attempts times timeout plus waits must fit inside what the user will tolerate.
Retrying actions with side effects. A repeated email or refund is worse than a repeated summary. Use idempotency keys or separate the action from the model call.
Silent failure. Swallowing errors means you find out from angry users. Log them with enough detail to diagnose, and alert on trends.
Key takeaways
Failures are normal at scale. Design for them from the first release, not after the first outage.
Sort errors into three groups: fix the request and stop, wait and retry, or retry with backoff. Never retry what cannot succeed.
Use exponential backoff with a cap, a maximum number of retries and jitter, so recovering servers are not stampeded.
Rate limits come in requests and tokens per minute. The tighter one is your ceiling, and shrinking each call raises it.
Pace your own traffic with a queue or a counter, and leave some headroom, instead of bouncing off the limit.
Work backwards from the time a user will wait to choose timeouts and the number of attempts.
Add a fallback, a circuit breaker and good logs so a bad hour on the provider's side does not become a bad hour for your users.
Check yourself
1. Why is it a mistake to retry a request that returned a 400-range error such as "invalid field"?
The request itself is wrong, so every retry fails identically; fix the request instead.
2. What problem does jitter solve?
It spreads retries over time so many clients do not all retry at the same instant and overload a recovering server.
3. Your plan allows 200 requests per minute and 100,000 tokens per minute, and each call uses 1,000 tokens. Which limit binds, and what is the ceiling?
The token limit: 100,000 divided by 1,000 is 100 calls a minute, below the 200 allowed by the request limit.
4. A user will wait 15 seconds. You allow three attempts with 1 second between them. About how long can each attempt's timeout be?
About 4 seconds: (15 minus 2) divided by 3 is a little over 4.
5. A call returns a success status but the answer is cut off mid-sentence. Which layer should catch this?
Your own application, by validating the output, since the status code reports success.
6. What is an idempotency key for?
It lets a system recognise a repeated action and perform it only once, so a retry cannot send a second email or payment.
Try this
Set aside 30 to 45 minutes. You need a computer with Python, or a notebook and a calculator if you prefer to do it by hand.
1. Write down a model feature you know, real or imagined, such as summarising a customer complaint. Note how long a user would realistically wait for it, and how many calls you expect per day.
2. Create a small fake function that "calls a model": it returns success most of the time, and otherwise returns a failure chosen at random from 429, 503, 400 and 401. Make the failure chance 30 percent.
3. Wrap it in the retry function from this lesson. Run 200 calls and count how many ended in success, how many failed after all retries, and how many failed immediately because the error was not retryable.
4. Remove the jitter and change the wait to a fixed one second. Run 200 calls from five parallel workers and notice how clustered the retries look when you print a timestamp for each.
5. Using the batch simulator, enter limits from your own provider's account pages and your own document count. Write down the bottleneck and the expected hours.
6. Using the timeout simulator, enter your user's patience from step 1 and choose a timeout and number of attempts that fit.
7. Write a short list of the three alerts you would set up, such as "more than 20 non-retryable errors in a minute".
A good result has three parts: a working retry wrapper that fails fast on 400 and 401 errors, two numbers you computed yourself (the batch time and the per-attempt timeout) and a one-paragraph note saying what the user sees when everything fails. If you can write that last paragraph without the word "error" in it, because the product shows something useful instead, you have done the job well.
Tags: AI Engineering LLM APIs Reliability Rate limits Retries