How to Handle LLM Failures Gracefully

Model APIs go down, slow to a crawl, hit limits and return nonsense. An AI feature that users can rely on is built on the assumption that all of this will happen, regularly.

How to Handle LLM Failures Gracefully — Troiana insight cover

In short

To handle LLM failures well, set timeouts, retry only temporary errors with exponential backoff and jitter, and fall back to another model or a non-AI path. Validate output against a schema, and treat refusals and truncation as distinct cases. Show honest messages, keep the user's input, never let a failure block a core task, and log every failure, with alerts on spikes.

How they fail

FailureSignUsual response
Rate limitHTTP 429Wait and retry; respect Retry-After
Server or overload errorHTTP 5xx, or a provider's overloaded errorRetry, then fall back
TimeoutNo response in timeRetry once or fall back
Bad requestHTTP 400Fix your code; don't retry
Auth or billingHTTP 401, 402, 403Alert a person; don't retry
Context too longA 400 error, specifying lengthTrim and resend
Truncated outputStop reason shows max tokensContinue or raise the limit
RefusalModel declinesHandle separately; don't simply retry
Malformed outputFails your schemaRepair or regenerate once
Confidently wrongLooks normalEvaluations, sources, human review

That last one matters most, and it's discussed in how to log and debug AI features and how to evaluate an LLM feature. This article mainly focuses on the others.

Set timeouts

Without a timeout, a stuck request can hang until a user gives up. Decide what's acceptable for each feature:

  • Interactive, streaming: a limit on time to first token, perhaps 10–15 seconds, plus a total limit
  • Interactive, non-streaming: keep it as short as you can, and show progress
  • Background jobs: longer, using a queue

Those figures are starting points to adjust using your own measurements. Streaming helps, as it makes long responses feel responsive, and can reveal stalls sooner.

Retry only what can succeed

Retrying a 400 error wastes money. Retrying a 429 without a delay makes things worse.

const RETRYABLE = new Set([408, 429, 500, 502, 503, 504, 529]);

async function callWithRetry(fn, maxAttempts = 3) {
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (err) {
      const canRetry = RETRYABLE.has(err.status);
      if (!canRetry || attempt === maxAttempts) throw err;

      const retryAfter = Number(err.headers?.["retry-after"]) * 1000;
      const backoff = 2 ** attempt * 500;
      const jitter = Math.random() * 500;
      await sleep(retryAfter || backoff + jitter);
    }
  }
}

Key points:

  • Exponential backoff: wait longer each time.
  • Jitter: random delay, so that thousands of clients don't retry simultaneously.
  • Respect Retry-After, if it's sent.
  • Set a limit, and a total time budget, so that retries don't hold up the user for a minute.
  • Check your SDK, as official ones often retry already. Don't stack your own on top, or a few attempts may turn into many.

Be careful with actions as well. If an agent's tool sends an email, then retrying after a timeout might send it twice. Use idempotency keys for anything with side effects.

Example wait before each retry, with exponential backoff
Retry 11 s
Retry 22 s
Retry 34 s
Retry 48 s
0 s2 s4 s6 s8 s10 s
Example values, doubling each time. Jitter adds a random delay to each, so thousands of clients don't retry at the same moment.

Fall back

A fallback is what happens when retries aren't enough. In rough order of preference:

  1. Another model from the same provider
  2. The same or a similar model from another provider or cloud
  3. A cached answer, for common questions
  4. A simpler non-AI path, such as keyword search or a rules-based result
  5. Graceful degradation: the feature is temporarily unavailable, but everything else works
async function generate(prompt) {
  for (const model of ["primary-model", "backup-model"]) {
    try {
      return await callWithRetry(() => client.create({ model, prompt }));
    } catch (err) {
      log.warn("model failed", { model, status: err.status });
    }
  }
  return { fallback: true, text: null };
}

Test your fallback with your evaluation set before you rely on it. Different models behave differently, particularly in tool use and structured outputs. See how to choose an LLM for your product and open-source or hosted models?

A circuit breaker can help as well: when a provider's failure rate crosses a threshold, stop calling it for a short while, go straight to the fallback, then try again later. This saves your users from waiting on requests that are likely to fail.

When retries aren't enough, in rough order
Another modelSame provider
Another providerSame or similar model
A cached answerFor common questions
A non-AI pathSuch as keyword search
DegradeSay the feature is unavailable
However far down you go, the core task should still work, and the user's input should still be there.

Validate the output

Never assume that the output is well formed.

  1. Use structured outputs, where your API supports them.
  2. Validate against a schema with something like Zod or Pydantic.
  3. Check business rules. Is the price within range? Does the ID exist?
  4. On failure, retry once, including the error. If it still fails, fall back.
const result = InvoiceSchema.safeParse(JSON.parse(text));
if (!result.success) {
  // Regenerate once, then use a fallback
}

Treat model output as untrusted. Don't execute it, or render it as raw HTML. Don't pass it into SQL. See how to prevent XSS and how to stop prompt injection.

Handle truncation and refusals

Truncation: check the stop reason. An answer that was cut off might look complete, or produce invalid JSON. Increase the limit, continue in a further request, or ask for something shorter.

Refusals: the model may decline a request. Retrying rarely helps, and it can cost money. Show a clear message that explains what you can help with, and log it. If legitimate requests are being refused, look at your prompt.

Context too long: count tokens before sending where you can, and trim your history or retrieved documents. See what a token is.

What users should see

PoorBetter
Something went wrong.The assistant is busy right now. Your question is saved. Try again in a minute.
Error 529We couldn't generate a summary. You can still read the full document below.
Infinite spinnerThis is taking longer than usual. [Keep waiting] [Cancel]

Good principles:

  • Keep the user's input. Never lose what they typed.
  • Offer a next step: retry, use the non-AI option, or contact a person.
  • Show partial results, if they're useful, and say that it was interrupted.
  • Don't let AI failure block the core task. If AI tagging fails, the document should still save.
  • Don't invent an answer to hide a failure.

See how to design error states users can recover from and how to design an AI product interface.

Protect yourself

  • Rate limit your users. See how to rate limit an API.
  • Cap agent loops: maximum steps, time and spend per task.
  • Set a provider spending limit. A retry bug could be expensive. See how to control AI API costs.
  • Use a queue for bulk work, so that spikes don't turn into rate-limit errors.
  • Pin model versions, where you can, and watch for retirement notices.

Test your failures

Don't wait for a real outage:

  1. Add a fault-injection mode that returns 429s, 500s, timeouts, empty text and malformed JSON.
  2. Use your feature flags to turn off a model, and check that the fallback works.
  3. Test the interface for each failure, not only the code.
  4. Check your alerts by triggering one.
  5. Run through an outage with your team, and record what you learn. See how to run an incident postmortem.

Monitor

Track failure rate by type and by model, retry and fallback rates, latency percentiles, refusal rate and cost. Alert on sudden changes. Subscribe to your providers' status pages as well, but don't rely on them. Your own monitoring will often see problems first. See how to set up error tracking.

If you'd like help making an AI feature reliable enough for real customers, book a call.

Common questions

How should I handle LLM API errors?

Separate temporary errors, such as 429 and 5xx, from permanent ones, such as a 400. Retry temporary ones with backoff and jitter, up to a limit. Then fall back to another model or a simpler path, and show users an honest message.

How do I handle rate limits from an LLM API?

Respect the Retry-After header if there is one, and otherwise use exponential backoff with jitter. Queue bulk work, limit requests per user, and consider asking your provider for a higher limit. A fallback model can also help with brief spikes.

What should happen when an AI feature fails?

Users should keep their input, get a clear message and have a next step, such as retrying or using a non-AI option. The core task should still work. Never invent an answer to hide the failure, and log what happened.

How do I handle invalid JSON from an LLM?

Use structured outputs where your API supports them, and validate results against a schema. If validation fails, retry once, including the error, and then fall back. Check whether the response was truncated, as that's a common cause of invalid JSON.

Have something worth building right?