Howwise RSS
AI & Automation8 min read

OpenAI API 429 Error: Rate Limit vs Quota and How to Fix

Short answer

An OpenAI API 429 error means either rate_limit_exceeded, a temporary speed limit you fix with backoff and throttling, or insufficient_quota, which means no credit or a budget cap and retrying never fixes it. Read error.code first.

Key takeaways
  • Read error.code in the JSON body: rate_limit_exceeded is temporary and retryable, insufficient_quota is a billing problem that retries cannot fix.
  • Honor Retry-After or the x-ratelimit-reset-* headers, and otherwise use exponential backoff with full jitter, a retry cap and a total deadline.
  • max_tokens or max_completion_tokens counts toward your TPM estimate, so an oversized value causes 429s even when the real output is short.
  • Cap concurrency with a semaphore or token bucket at about 80% of your limit, and share that limiter through Redis when you run several workers.
  • Use the Batch API for non-urgent work, because it has separate, higher limits and costs 50% less.

How do I tell which OpenAI 429 error I have?

HTTP 429 is shared by two unrelated failures. One means you are sending too fast. The other means the account cannot pay for any request. The status code is identical, so the decision comes from the JSON body, specifically error.code and error.message.

Decision flow: read error.code. If it is insufficient_quota, stop retrying and fix billing. If it is rate_limit_exceeded, retry with backoff and then reduce your load. The message text also names the limit that was hit (requests or tokens per minute, per day) and the model.

error.code / messageCauseRetry?Fix
rate_limit_exceeded, 'Rate limit reached for ... requests per min (RPM)'Too many requests in the current minuteYes, after a delayBackoff, throttle concurrency, queue
rate_limit_exceeded, '... tokens per min (TPM)'Prompt tokens plus requested max output tokens exceed the minute budgetYes, after a delayCut tokens, lower max_tokens, pace requests
rate_limit_exceeded, '... requests per day (RPD)' or '... tokens per day (TPD)'Daily cap reached, common on low tiersOnly after the daily window resetsSpread load, move to Batch API, raise tier
insufficient_quota, 'You exceeded your current quota, please check your plan and billing details'No credit, billing not set up, prepaid balance at zero, or monthly budget cap hitNeverAdd credit, set up billing, raise the budget limit
Plain 429 with 'Too Many Requests' and no JSON codeProxy, gateway or upstream overload in front of the APIYes, with backoffCheck your own proxy limits, then retry
{
  "error": {
    "message": "You exceeded your current quota, please check your plan and billing details.",
    "type": "insufficient_quota",
    "param": null,
    "code": "insufficient_quota"
  }
}
Tip: To confirm a quota problem, open the billing page in the platform dashboard and check the credit balance, the payment method and any monthly budget limit. A balance of zero or a hit budget cap explains insufficient_quota even when your usage looks small.

Why does OpenAI rate limit me when my traffic is low?

Limits are set per project and per model, within your organization's usage tier. They are not per API key or per server. Every key, script and environment inside one project shares that project's pool, so a nightly job can starve your production app if both run in the same project.

Limits also rise with usage tier, which depends on spend and account age. A new account, or one whose prepaid balance has not been paid, sits on a low tier with small RPM, TPM and sometimes daily caps. The Limits page in the dashboard shows the exact numbers for each model in the selected project, so check it before tuning anything.

The most overlooked cause is token estimation. The TPM check counts your prompt tokens plus the max_tokens or max_completion_tokens value you request, before the model generates anything. A request with a 500 token prompt and max_tokens of 8000 reserves roughly 8500 tokens of your minute budget, even if the answer is 40 tokens. Ten such requests can trip a 60,000 TPM limit while real usage is tiny.

Set the output cap to a realistic ceiling, such as the longest answer you would accept plus a margin.

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

Successful and failed responses carry headers that describe your budget. They let you slow down before you hit a 429, instead of reacting afterward.

The reset headers are durations such as 1s, 250ms or 6m0s, not timestamps. Retry-After, when present, is in seconds. Always prefer it over your own guess.

HeaderMeaning
x-ratelimit-limit-requestsYour RPM cap for this model
x-ratelimit-remaining-requestsRequests left in the current window
x-ratelimit-reset-requestsTime until the request budget resets
x-ratelimit-limit-tokensYour TPM cap for this model
x-ratelimit-remaining-tokensTokens left in the current window
x-ratelimit-reset-tokensTime until the token budget resets
Retry-AfterSeconds to wait before the next attempt, when sent

How do I retry with exponential backoff and jitter?

Use full jitter: sleep = random(0, min(cap, base * 2^attempt)). With base 1 second and cap 60 seconds, the upper bound grows 1, 2, 4, 8, 16, 32, 60 across seven attempts, and each actual sleep is a random value below that bound.

Jitter matters because without it every client that failed together retries together at 1s, 2s, 4s, which recreates the spike each time (a thundering herd). Randomizing spreads them across the window. Also set a maximum attempt count (5 to 8) and a total deadline (for example 120 seconds) so a stuck request cannot hang a user forever.

The official Python SDK already retries 429, 408, 409 and 5xx errors and connection failures, with max_retries defaulting to 2. Raise it for light use, or set it to 0 and own the logic yourself, as below. Never stack SDK retries and your own retries, because attempts multiply.

import random, time
from openai import OpenAI, RateLimitError, APITimeoutError, APIConnectionError, InternalServerError

# Option 1: SDK-only, simplest
client = OpenAI(max_retries=5, timeout=60)

# Option 2: manual loop that honors Retry-After and a deadline
client = OpenAI(max_retries=0, timeout=60)

def chat(messages, model="gpt-4o-mini", max_attempts=7, deadline_s=120, base=1, cap=60):
    start = time.monotonic()
    for attempt in range(max_attempts):
        try:
            return client.chat.completions.create(
                model=model, messages=messages, max_tokens=500)
        except RateLimitError as e:
            if e.code == "insufficient_quota":
                raise  # billing problem, retrying is pointless and may cost money
            retry_after = e.response.headers.get("retry-after")
            delay = float(retry_after) if retry_after else random.uniform(0, min(cap, base * 2 ** attempt))
        except (APITimeoutError, APIConnectionError, InternalServerError):
            delay = random.uniform(0, min(cap, base * 2 ** attempt))
        if attempt == max_attempts - 1 or time.monotonic() - start + delay > deadline_s:
            raise
        time.sleep(delay)

# Option 3: tenacity
from tenacity import retry, wait_random_exponential, stop_after_attempt, retry_if_exception

def retryable(e):
    if isinstance(e, RateLimitError):
        return e.code != "insufficient_quota"
    return isinstance(e, (APITimeoutError, APIConnectionError, InternalServerError))

@retry(retry=retry_if_exception(retryable),
       wait=wait_random_exponential(multiplier=1, max=60),
       stop=stop_after_attempt(7), reraise=True)
def chat_tenacity(**kw):
    return client.chat.completions.create(**kw)
Warning: Only retry 429 (not insufficient_quota), 500, 502, 503, 504 and timeouts. Never retry 400, 401 or 403, because they will fail identically. A timed-out request may still have been processed, so attach your own idempotency key or dedupe record before triggering side effects such as sending an email or charging a card.

How do I throttle and queue requests to avoid 429s?

Retries recover from 429s, but throttling prevents them. Cap concurrency with a semaphore, feed work through a queue with a fixed worker pool, and pace yourself at about 80% of the limit. If your RPM is 500, target roughly 400, which leaves room for bursts and for other workloads in the same project.

Each worker process only sees its own traffic. With 8 workers each pacing to the full limit, you send 8 times too much. Share the budget through Redis, using a token bucket in a Lua script or a library built on it, so that all processes draw from one counter. Alternatively, divide the limit by the worker count as a simple static split.

  1. Measure your limit for the model on the Limits page and multiply by 0.8 to get a target.
  2. Create a queue and start N workers, where N is the concurrency your target supports (target RPM times average latency in minutes).
  3. Before each call, estimate tokens with tiktoken and wait until the token bucket has enough capacity.
  4. On a 429, re-queue the job with a delay from Retry-After rather than sleeping inside a worker slot for long periods.
  5. Update the bucket from x-ratelimit-remaining-* headers so it corrects drift.
import asyncio, tiktoken
from openai import AsyncOpenAI

client = AsyncOpenAI(max_retries=0)
sem = asyncio.Semaphore(8)           # max in-flight requests
enc = tiktoken.get_encoding("o200k_base")

def estimate(messages, max_tokens):
    prompt = sum(len(enc.encode(m["content"])) + 4 for m in messages)
    return prompt + max_tokens       # TPM counts the output cap too

async def worker(queue):
    while True:
        messages = await queue.get()
        async with sem:
            await chat_async(messages)   # your backoff wrapper
        queue.task_done()

How do I reduce token use and batch non-urgent work?

Token reduction attacks TPM directly, which is the limit most apps hit first. Work through these in order of effort: shorten system prompts, trim chat history to the last few turns or a running summary, set a realistic max_tokens, ask for compact output (for example structured JSON with short fields), and route easy tasks to a smaller model, which usually has higher limits and lower cost.

Cache identical requests in your own store, keyed by a hash of model plus messages. Also put static content, such as instructions and examples, at the start of the prompt so OpenAI's automatic prompt caching can reuse it. Prompt caching lowers cost and latency, so do not assume it removes tokens from your rate limit accounting.

Batching has two meanings. The Batch API takes a file of requests, finishes within 24 hours, costs 50% less and uses a separate, higher pool of limits, so it is ideal for evaluations, backfills and bulk classification. Packing several small tasks into one request, or sending an array of inputs to the embeddings endpoint, cuts request count and helps RPM. It does not cut tokens, so it will not fix a TPM problem.

import OpenAI from "openai";
const client = new OpenAI({ maxRetries: 5, timeout: 60000 });

async function chat(messages) {
  try {
    return await client.chat.completions.create({ model: "gpt-4o-mini", messages, max_tokens: 500 });
  } catch (err) {
    if (err instanceof OpenAI.RateLimitError && err.code === "insufficient_quota") {
      throw new Error("Out of quota: fix billing, do not retry");
    }
    console.warn(err.status, err.headers?.["retry-after"]);
    throw err;
  }
}

What mistakes keep causing 429s, and how do I monitor them?

The usual mistakes are retrying in a tight loop with no delay, retrying insufficient_quota forever, letting every worker retry at the same moment, ignoring that failed retries still burn time and sometimes tokens, running production and experiments in the same project so they share one pool, and treating the 429 as an app bug instead of a capacity signal.

Log every 429 with its error.code, model, estimated tokens and the remaining-limit headers. Alert when the 429 rate stays above a small percentage (for example 1% of requests over 5 minutes), and alert separately and immediately on any insufficient_quota, since that means a hard outage.

Add a fallback: a second model with its own limits, or a second provider, used when retries are exhausted. If sustained load still exceeds your limits after throttling and token cuts, request a tier or limit increase from the dashboard, or spend enough to move up a tier.

Common questions

Why do I get 'You exceeded your current quota' with credit left?

The most common causes are a monthly budget limit set lower than your spend, credit that expired, or a key belonging to a different organization or project than the one you funded. Check the billing page and the organization and project attached to the key.

Does a failed 429 request cost money?

A request rejected with 429 before processing is not billed for generation. Timeouts are different, because the model may have produced output you never received, so avoid blind retries on long generations without a dedupe record.

How long should I wait after a rate_limit_exceeded error?

Use Retry-After if present, or the x-ratelimit-reset-requests and x-ratelimit-reset-tokens durations. If neither is available, use full jitter backoff starting from about 1 second and capped at 60 seconds.

Will adding more API keys raise my limit?

No. Limits are set per project and per model, so extra keys inside the same project all share that project's pool. Putting workloads in separate projects gives each its own limits, which isolates production from experiments, but it does not lift your organization's usage tier. To get more capacity overall, move up a tier or request a limit increase.

Can I stop 429s completely?

Not entirely, since other workloads sharing your project and provider-side load can still trigger them. Throttling, token reduction and retries make them rare and invisible to users.

Related topics:openairate limits429 errorpythonapi reliability