← All news

News / Learn / Working with model APIs

How do you handle rate limits and API errors?

You'll be able to keep your app running when an LLM API slows down, refuses a request, or returns a rate limit error.

Model APIs limit how many requests and tokens you can send in a given time. When you go over, the server says no and sends back an error. Good code expects these errors, waits a little, and tries again instead of crashing or failing the user.

Every product that calls a model API will hit limits and errors sooner or later. Traffic spikes, a shared key, or a long job can all trigger them. How your app responds decides whether users see a short delay or a broken screen, and whether you pay for work that never finished.

Most providers limit requests per minute and tokens per minute, often per key or per organization. When you go over, the API usually returns HTTP status 429, which means too many requests. Other errors matter too. A 5xx status means the server failed on its side. A timeout means no answer arrived in time. A 400 error means your request itself is wrong, and retrying it will not help.

The standard fix is retry with exponential backoff and jitter. After each failed attempt, wait longer than before, such as 1 second, then 2, then 4. Add a small random amount to each wait so many clients do not retry at the same moment. Cap the number of attempts and the total wait time. Only retry errors that might pass, such as 429, 500, 502, 503, 504, and timeouts.

If the API sends a Retry-After header, use that value rather than your own guess. Some SDKs already retry for you. Check what your SDK does by default before you add your own loop, so you do not stack retries and multiply the load.

Reduce the chance of hitting limits in the first place. Cap concurrency with a queue or semaphore. Keep prompts short. Set a sensible max output length. Cache answers when the same input repeats. For work that does not need an instant reply, a batch interface may be a better fit.

Finally, decide what the user sees. Show a clear message and a retry option, or fall back to a smaller model or a cached answer. Log the status code, request ID, and attempt count so you can see patterns later.

A generic retry wrapper with exponential backoff and jitter. Replace call_model with your SDK call.

import random
import time

RETRYABLE = {429, 500, 502, 503, 504}

class APIError(Exception):
    def __init__(self, status, message=""):
        super().__init__(message)
        self.status = status

def call_with_retries(call_model, max_attempts=5, base_delay=1.0, max_delay=30.0):
    for attempt in range(1, max_attempts + 1):
        try:
            return call_model()
        except APIError as err:
            if err.status not in RETRYABLE or attempt == max_attempts:
                raise
            # Exponential backoff with full jitter
            delay = min(max_delay, base_delay * (2 ** (attempt - 1)))
            time.sleep(random.uniform(0, delay))

A short sketch to show the idea. Check the official docs of the tool you use.

  • Retrying every error Retry only errors that can succeed later, such as 429, 5xx, and timeouts. A 400 or 401 will fail again, so fix the request or the key instead.
  • Stacking retries Many SDKs retry automatically. Check the defaults and set one retry layer, or you can multiply attempts and worsen the rate limit.
  • Retries without a cap Set a maximum attempt count and a total time budget. Unbounded retries tie up workers and can run up cost.
  • Ignoring Retry-After When the server gives a wait time, honor it. Guessing a shorter delay causes repeated 429 errors.
  • Hiding failures from users Show a clear message with a retry or fallback path. Log the status and request ID so you can diagnose problems.

Read your provider's rate limit and error documentation for the current numbers and header names. Then learn about queues, circuit breakers, and request idempotency, which matter when a retried call might run twice.

What does a 429 error mean?

It means you sent too many requests or too many tokens in a time window. The server is asking you to slow down and try again after a short wait.

Why add jitter to backoff?

If many clients wait the same amount, they all retry at once and overload the server again. Random jitter spreads the retries out over time.

Should I retry a 500 error?

Often yes, because the server may recover. Use a limited number of attempts with backoff, and log the failure if it keeps happening.

Can retries cost money?

Yes. A request that fails after the model has started generating may still be billed. Keep retries limited and watch your usage.

Written with AI by CapyLaunch. Spotted a mistake? Email hello@capylaunch.com.