Square CloudSquare Cloud

429 errors from an AI API: rate limits, quota and how to handle them

A 429 from an AI API means you hit a rate limit (requests or tokens per minute) or ran out of quota or credit. The first clears with waiting and backoff; the second needs action on the account.

Updated 8 min read

Learning objectives

After reading this article you will be able to:

  • Tell a rate limit from exhausted quota or credit by reading the error body
  • Read the rate limit headers and Retry-After before trying again
  • Retry with exponential backoff and jitter, and cap concurrency with a queue
On this page

Your bot handled every test fine, and then the first traffic spike brings a wave of 429 Too Many Requests. Or it fails on the very first call from a brand-new account. The status code is the same in both cases, but the cause is not, and the fix for one does nothing for the other.

The 429 comes from HTTP: RFC 6585 defines it for a client that sends too many requests in a given amount of time. AI APIs use it for two different problems: a rate limit, which clears on its own, and exhausted quota or credit, which stays until someone changes something on the account. Working out which one you got is step one.

What does a 429 look like?#

Each provider words its 429 differently, but all of them put the cause in the response body. OpenAI's error code list uses these titles for the common cases:

text
429 - Rate limit reached for requests
429 - Slow down
429 - Credit balance exhausted
429 - Organization spend limit reached
429 - Project spend limit reached

The first two are rate limits: you sent requests too fast, or your traffic jumped suddenly. The rest are billing: prepaid credit ran out or a spend limit was reached. In those cases error.type can be insufficient_quota, and error.code names the exact cause, such as credit_balance_exhausted. Some of OpenAI's own retry examples check for insufficient_quota precisely so they can stop retrying.

Anthropic uses the rate_limit_error type for both and puts the cause in a code. When an organization reaches its usage tier's monthly spend cap, the response looks like this:

json
{
  "type": "error",
  "error": {
    "type": "rate_limit_error",
    "message": "You have reached your API usage limits: your organization has crossed its monthly API usage threshold, set based on your organization's API tier. You will regain access on 2026-09-01 at 00:00 UTC.",
    "details": { "error_code": "enforced_spend_limit_reached" }
  },
  "request_id": "req_018EeWyXxfu5pfWkrYcMdjWG"
}

That 429 has no retry-after header, and retrying, the SDK's automatic retries included, keeps failing until access resumes. A sharp jump in traffic also triggers a 429 on Anthropic even while you are under your per-minute limits: that is the ramp limit, with the ramp_limit_exceeded code. For Google's Gemini, the documentation treats 429 RESOURCE_EXHAUSTED as a transient error to retry with backoff, and the error reference separates per-minute limits from daily quota; depleted prepaid credit comes back as a 402.

Whatever the provider, read the status, the type and the code before you decide. Never match on the message text in code, because it changes without notice.

Rate limit or exhausted quota: which one is yours?#

A rate limit measures how much you use in a short window. OpenAI counts requests and tokens per minute and per day (RPM, RPD, TPM, TPD); Anthropic counts requests, input tokens and output tokens per minute for each model class. Whichever runs out first wins. The numbers depend on your usage tier, which goes up with the account's usage and payment history.

The limit is not always applied per whole minute. Anthropic uses a token bucket that refills continuously and warns that 60 requests per minute may be enforced as one per second. A burst of 20 calls in the same second can get a 429 even when the minute's average is under the cap.

Quota is something else: the money or the period's allowance is gone. Waiting a few seconds changes nothing.

Rate limit Exhausted quota or credit
What happened Too many requests or tokens in a short window Credit, spend limit or period quota ran out
Typical signals rate_limit_error, slow_down, Retry-After header insufficient_quota, credit_balance_exhausted, enforced_spend_limit_reached
Does waiting fix it? Yes, in seconds or minutes No, not until a top-up or a new period
What to do Backoff, less concurrency, fewer tokens per call Add credit, raise the spend limit, move up a tier

On OpenAI, failed requests also count toward the per-minute limit. A loop that retries without waiting burns the very limit it is waiting on.

How do you read the rate limit headers and Retry-After?#

Successful responses already tell you how much is left. OpenAI sends x-ratelimit-limit-requests, x-ratelimit-remaining-requests, x-ratelimit-remaining-tokens and the time until each resets, such as x-ratelimit-reset-requests: 1s and x-ratelimit-reset-tokens: 6m0s. Anthropic sends anthropic-ratelimit-requests-remaining, anthropic-ratelimit-tokens-remaining and the reset times in RFC 3339 format.

Retry-After is the standard HTTP header for when to try again. RFC 9110 allows two formats: a number of seconds or a date. OpenAI asks you to treat the value as a minimum: wait at least that long and add a small random delay.

With OpenAI's Python SDK, with_raw_response exposes the headers. Set the environment variables first (the model ID comes from the provider's models page):

bash
# .env
OPENAI_API_KEY=your-key
OPENAI_MODEL=model-id
python
import os

from openai import OpenAI

client = OpenAI()

raw = client.chat.completions.with_raw_response.create(
    model=os.environ["OPENAI_MODEL"],
    messages=[{"role": "user", "content": "Say hi in one sentence."}],
    max_completion_tokens=200,
)
for name in (
    "x-ratelimit-remaining-requests",
    "x-ratelimit-remaining-tokens",
    "x-ratelimit-reset-requests",
    "x-ratelimit-reset-tokens",
):
    print(name, raw.headers.get(name))

response = raw.parse()
print(response.choices[0].message.content)

With those numbers your code can slow down before the 429: if fewer tokens remain than the next call will use, wait for the reset.

How do you retry with exponential backoff and jitter?#

Exponential backoff means doubling the wait on each attempt: 1, 2, 4, 8 seconds, up to a cap. Jitter means randomizing the wait inside that range, so many clients that failed together do not all come back at the same instant. OpenAI's documentation recommends both, with a cap on attempts and on total time, and says not to retry quota or billing errors.

The official Python SDK already retries a 429 twice by default with a short backoff. If you write your own logic, turn the SDK's retries off with max_retries=0; otherwise the two loops multiply:

python
import os
import random
import time

from openai import OpenAI, RateLimitError

client = OpenAI(max_retries=0)  # the function below owns the retries
MODEL = os.environ["OPENAI_MODEL"]

# Billing errors: waiting does not fix them
PERMANENT = {
    "insufficient_quota",
    "credit_balance_exhausted",
    "organization_spend_limit_exceeded",
    "project_spend_limit_exceeded",
    "organization_usage_limit_exceeded",
}


def retry_after(err: RateLimitError) -> float | None:
    value = err.response.headers.get("retry-after")
    try:
        return float(value)
    except (TypeError, ValueError):
        return None  # missing, or in date format


def ask(messages, attempts=6, base=1.0, cap=60.0):
    for attempt in range(attempts):
        try:
            return client.chat.completions.create(model=MODEL, messages=messages)
        except RateLimitError as err:
            if err.type in PERMANENT or err.code in PERMANENT:
                raise  # alert whoever runs the account instead of insisting
            if attempt == attempts - 1:
                raise
            wait = random.uniform(0, min(cap, base * 2**attempt))  # jitter
            hint = retry_after(err)
            if hint is not None:
                if hint > cap:
                    raise  # too long to keep a user waiting
                wait = max(wait, hint + random.uniform(0, 1))  # the server's minimum, plus jitter
            time.sleep(wait)


response = ask([{"role": "user", "content": "Explain the 429 error in one sentence."}])
print(response.choices[0].message.content)

The same pattern works for server overload errors (503 on OpenAI, 529 on Anthropic); in the OpenAI SDK, a 503 arrives as InternalServerError. In async code, swap time.sleep for asyncio.sleep so you do not block the whole process.

How do you cap concurrency with a queue?#

Backoff treats the symptom. If your code fires 50 calls at once, say to summarize a list of tickets with asyncio.gather, the burst blows past the limit before any retry kicks in. The fix is to control the flow on the way out: a maximum number of calls in flight and a minimum gap between starts.

python
import asyncio
import os
import time

from openai import AsyncOpenAI

client = AsyncOpenAI()
MODEL = os.environ["OPENAI_MODEL"]

in_flight = asyncio.Semaphore(4)  # at most 4 calls running
INTERVAL = 1.0  # seconds between the start of two calls
clock = asyncio.Lock()
next_start = 0.0


async def wait_turn():
    global next_start
    async with clock:
        now = time.monotonic()
        if next_start > now:
            await asyncio.sleep(next_start - now)
        next_start = max(now, next_start) + INTERVAL


async def summarize(ticket: str) -> str:
    async with in_flight:
        await wait_turn()
        r = await client.chat.completions.create(
            model=MODEL,
            max_completion_tokens=200,
            messages=[{"role": "user", "content": f"Summarize in one sentence: {ticket}"}],
        )
        return r.choices[0].message.content


async def main():
    tickets = [f"Ticket {i}: the customer never got the confirmation email." for i in range(20)]
    for summary in await asyncio.gather(*(summarize(t) for t in tickets)):
        print(summary)


asyncio.run(main())

That covers one process. With several processes or servers, the control has to be shared: a real queue with workers that take one item at a time, as described in cron jobs vs background workers vs queues and background jobs with BullMQ and Celery. For work that is not urgent, like classifying thousands of messages overnight, batch APIs are another way out: on OpenAI they do not affect your synchronous rate limits.

How do you prevent 429s?#

  • Right-size the output limit. OpenAI computes tokens-per-minute usage from the larger of the max_tokens you request and the request's estimated size. An output cap set too high eats the limit even when the answer is short. On Anthropic, max_tokens does not count toward the output tokens limit.
  • Send fewer tokens per call. A trimmed history and a lean prompt fit more requests into the same per-minute limit. See how in context_length_exceeded.
  • Use prompt caching. On Anthropic, tokens read from the cache do not count toward the input tokens per minute limit, so a long, repeated system prompt weighs less. More ways to trim are in how to reduce LLM token costs.
  • Limit each user. In a public bot, a per-user cooldown stops one person from using up everyone's limit. It is the same idea as API rate limiting, applied on your side.
  • Ramp traffic up gradually. Both providers limit sudden growth. Start bulk jobs slowly and spread requests out over time.
  • Log the code of every 429. An alert on quota errors reaches the right person before users notice. The math on what you spend is in how much an LLM API costs.

Discord has a 429 of its own with different rules; if your bot gets both, read Discord 429 Too Many Requests so you do not mix up the causes.

How to do this on Square Cloud#

On Square Cloud, from the Standard plan (R$44.99 a month), the AI Gateway is an OpenAI-compatible API for using the cubic model in your own products. The retry function and the queue in this article work with three changes: the base URL https://api.squarecloud.app/v2/ai on the client, an account API key with the ai:chat scope and OPENAI_MODEL=cubic. Errors arrive in the OpenAI format, so the decision comes from the code field, as in the examples above. The x-ratelimit-* headers from the previous section are OpenAI's; on the gateway, go by the error code and your plan's limits.

Three codes matter here:

  • rate_limit_exceeded: requests came in too fast. On Standard, the plan calls for 1 second between requests, and the queue's INTERVAL = 1.0 spaces out the start of each call at that pace.
  • concurrent_limit_reached: more simultaneous requests than the plan allows, which is up to 4 on Standard, 8 on Pro and 16 on Enterprise. Set the Semaphore to your plan's number.
  • daily_limit_reached: the daily token limit is used up. It resets at 00:00 UTC, and the weekly one on Monday. Treat it as a quota error: add the code to the PERMANENT set and stop retrying.

The gateway's limits are its own, separate from the Cubic's in the dashboard: up to 2.5 million tokens a day on Standard, up to 5 million on Pro and 10 to 20 million on Enterprise. There is no extra charge within them; above them, AI credit packs keep it running, and Enterprise can use post-paid billing with a cap, all billed in Brazilian reais. See the limits per plan and the examples on the AI Gateway page.

AI

Host AI apps in always-on containers

OpenAI-compatible API

FAQs

What is the difference between a rate limit and insufficient_quota?

A rate limit is temporary: you sent too many requests or tokens in a short window, and waiting fixes it. insufficient_quota means credit, quota or a spend limit ran out, and no retry helps until you act on the account.

How long should I wait after a 429?

If the response has a Retry-After header, wait at least that long. Without it, use exponential backoff with jitter: waits that double on each attempt, each one randomized, with a cap on attempts.

Do failed requests count toward the rate limit?

On OpenAI, yes: the documentation says unsuccessful requests count toward your per-minute limit. That is why retrying without waiting only drags the error out.

Does the OpenAI SDK retry on its own?

Yes. The official Python SDK retries some errors, 429 included, twice by default with a short backoff. Tune it with max_retries, or turn it off with max_retries=0 if you handle retries yourself.

Next articlecontext_length_exceeded: when the conversation no longer fits the context windowcontext_length_exceeded means prompt, history, tools and output went past the model's context window. Learn how to count tokens and fix it for good.