Blog / Build with AI /

Why AI APIs fail sometimes, and how to retry

Your tool worked perfectly all afternoon. Then, with a real user watching, the AI feature returned an error. You refresh, and it works again. Nothing changed.

Welcome to the nature of calling someone else’s computer over the internet. AI API calls fail sometimes, for ordinary reasons, and a tool that does not expect it looks broken even when your code is fine.

This post explains why failures happen, which ones are worth retrying, and a retry pattern that is safe. You do not need to be a developer to follow the logic, and AI can write the code if you describe the behaviour clearly.

Why requests fail

Think of an API call as sending a letter to a very busy office and waiting for a reply. Several things can go wrong.

1. Your request was wrong

You sent something the service cannot accept: a missing field, a model name that does not exist, an expired or mistyped key, a prompt too long for the model’s limit. These are your errors. They usually come back as a “client error” in the 400 range.

Retrying will not help. The same wrong request gets the same answer. Fix the request.

2. You are being limited

You sent too many requests too quickly, or used up a quota. The service tells you to slow down. This is typically the error code 429. See rate limits and quotas: protecting your tool and your wallet for the builder’s side of it.

Retrying can help, after a wait. Often the response says how long to wait.

3. The service is busy or having trouble

The provider’s servers are overloaded, or a deployment is going on, or a part of their system is down. These come back in the 500 range, or as timeouts. It is not your fault and nothing in your code changes it.

Retrying often helps, because the problem is temporary.

4. The network between you and them hiccuped

A dropped connection, a slow mobile link, a DNS blip. If your tool runs on a phone, a laptop on patchy Wi-Fi or a small server, this is more common than you would think.

Retrying usually works.

5. The answer took too long

Long outputs and heavy models can take a while. If your code gives up waiting before the answer arrives, you see a timeout even though the service is working. Setting a sensible timeout, and streaming the answer, helps. Streaming AI responses explained covers the second.

6. The content was blocked

Safety filters can refuse a request or cut a response. This is a decision, not a glitch. Retrying the same text will get the same refusal. Handle it with a clear message. Moderation and safety filters in AI apps explains what’s happening.

Which errors to retry

A simple rule:

Situation Retry?
Your request was invalid (400-range, except 429) No. Fix it.
Key is wrong or missing No. Fix it.
Rate limited (429) Yes, after waiting
Server error (500-range) Yes, a few times
Timeout or network error Yes, a few times
Content blocked No. Tell the user

Always check your provider’s documentation for their exact error codes and recommended behaviour, since details vary.

The retry pattern: wait longer each time

If a service is struggling, hammering it with instant retries makes things worse for everyone, including you. The standard approach is exponential backoff: wait a little, then longer, then longer still.

Imagine you knock on a door. No answer. You wait one second and knock again. Then two. Then four. You do not stand there pounding.

Add jitter: a small random amount to each wait. If a thousand users all retry at exactly the same moments, they create a wave. Random variation spreads it out.

A short sketch:

import random
import time

def call_with_retries(make_request, max_tries=4):
    wait = 1
    for attempt in range(1, max_tries + 1):
        try:
            return make_request()
        except TemporaryError:
            if attempt == max_tries:
                raise
            time.sleep(wait + random.uniform(0, 0.5))
            wait *= 2

TemporaryError stands for whichever errors you decided are worth retrying. The point is the shape: a limit on tries, a growing wait, a random nudge, and a clear failure at the end.

You can prompt for it directly:

Wrap my API call in a retry function. Retry up to 4 times on timeouts, network errors, 429 and 5xx responses. Do not retry other 4xx errors. Wait 1 second, then 2, then 4, with a small random addition. If the response has a Retry-After header, use that instead. After the last attempt, raise a clear error. Log each retry.

Some provider libraries have retries built in. Read the documentation before adding your own, or you may end up with retries on top of retries.

Things that make retrying dangerous

Charging twice

If a call costs money and you retry after a timeout, the first request may have succeeded in the background. You could pay for both. Cap the number of retries, and watch your usage. Cost control: how not to burn money on AI APIs goes through limits.

Repeating actions with side effects

If the AI call triggers something real, such as sending an email or creating an order, a retry might do it twice. Keep the AI step separate from the action, and make sure actions can only happen once. This is the same reasoning as keeping a human in the loop with AI agents.

Retrying forever

Always set a maximum. After that, fail gracefully and tell the user.

Retrying a bad prompt

If every attempt fails the same way, the problem is not temporary. Look at the error message rather than clicking retry again.

What the user sees

Retries are for your code. The user needs honest messages:

  • While retrying: “Still working…” rather than silence
  • After failing: “The AI service isn’t responding right now. Your text is saved, please try again in a minute.”
  • On a refusal: a clear note that the request could not be processed, without blaming them

And never lose their input. If someone has typed three paragraphs and the call fails, keep the text. Making AI features fail gracefully and error handling: making tools fail gracefully cover this.

Other protections

  • Timeouts. Decide how long you’ll wait, and stop after that.
  • Fallbacks. Some tools can switch to a different, simpler model when the first is unavailable. Keep this modest.
  • Caching. If the same question comes up again, reuse the answer instead of asking again. Caching AI answers to save money explains.
  • Logging. Record the error code, time and attempt number, but not users’ private text. Logging: knowing what your tool did gives the idea.
  • A status check. Providers publish status pages. If many calls fail at once, look there before you debug your own code.

A quick debugging order

  1. Read the exact error message and code.
  2. Decide: is it my request, a limit, or their side?
  3. If it’s mine, fix it.
  4. If it’s a limit, slow down and add backoff.
  5. If it’s theirs, retry a few times, then fail politely.

Key takeaways

  • Failures are normal. Plan for them.
  • Retry timeouts, network errors, rate limits and server errors; do not retry bad requests.
  • Use exponential backoff with a little jitter, and a hard cap.
  • Beware duplicate costs and duplicate actions.
  • Keep the user informed and keep their input.

What does your tool do right now when the API says no? Try it by turning off your internet connection and clicking the button.