Last reviewed: 24 Nov 2026
At the end of term, our school ERP writes a short draft comment for every report card, and teachers edit it before printing. Last term the job for one campus queued 1,800 students at 9 PM. Eight queue workers picked them up at the same moment, and within a minute the logs were full of 429 Too Many Requests. The SDK retried, the workers retried, and the morning report showed about a third of the comments missing. On a smaller campus the same job failed in a different way: every request returned 429 from the very first call, and retrying did nothing. That one was not a rate limit at all. The account had run out of credit.
An LLM API sends back HTTP 429 for two different problems, and they need opposite handling. A rate limit (too many requests or tokens in the current window) clears if you wait, so you slow down and retry. A quota error (no credit or a hard spending cap) never clears by itself, so you stop and alert someone. The response tells you which one you have, as long as you read it before you retry.
Quick diagnosis: read the error code and the headers
| What the 429 says | What it means | Go to |
|---|---|---|
"code": "rate_limit_exceeded", message mentions requests per min (RPM) | Too many calls in the window | Causes 1 and 2 |
"code": "rate_limit_exceeded", message mentions tokens per min (TPM) | Requests are too large, or too many large ones | Cause 3 |
"code": "insufficient_quota" / "You exceeded your current quota" | Billing or spending cap, not speed | Cause 4 |
OpenAI also documents rate limit headers on every response, and they show how close you are before you hit the wall: x-ratelimit-limit-requests, x-ratelimit-remaining-requests, x-ratelimit-reset-requests, and the matching -tokens headers. Other providers use their own names (Anthropic documents retry-after and anthropic-ratelimit-* headers), but the idea is the same. With the official Python SDK you can read them from the raw response:
raw = await client.chat.completions.with_raw_response.create(
model="gpt-4o-mini", messages=msgs, max_tokens=200)
print(raw.headers.get("x-ratelimit-remaining-requests"))
completion = raw.parse()
How I tested this
I did not want to burn a real API key to show 429s, so I built a small local mock of the chat completions endpoint and pointed the official OpenAI Python SDK (openai 3.58.0) at it with base_url. The mock uses the header names and error body format from OpenAI's documentation. Its limits are scaled down to a 10-second window (10 requests, 6,000 tokens) so each test runs in seconds. The SDK behaviour below (retries, exceptions, wait times) is real. The limit numbers come from my mock, not from any provider. The scripts are in my lab notes (mock.py, client.py).
Fixes by cause
1. A burst: you fire everything at once
This is what happened with the report-card job. Thirty requests in parallel against a limit of 10, with SDK retries turned off:
30 parallel, max_retries=0: 10 ok, 20 RateLimitError in 1.1s
first error: Error code: 429 - Rate limit reached for gpt-4o-mini in organization org-lab on requests per min (RPM): Limit 10, Used 10, Requested 1. Please try again in 8.984s.
code: rate_limit_exceeded | status: 429 | retry-after: 9With the SDK's default max_retries=2, the client honoured Retry-After. Its log shows it waited the 9 seconds the server asked for:
openai._base_client INFO Retrying request in 9.000000 seconds (retry 1 of 2)
openai._base_client INFO Retrying request in 9.000000 seconds (retry 2 of 2)
...
30 parallel, max_retries=2: 29 ok, 1 RateLimitError in 21.2sThat looks almost fixed, but it is not. Most of the retries all woke up at the same second, collided again, and one request still failed after its two retries. At 1,800 jobs this becomes the "a third are missing" morning. Built-in retries are a safety net, not a plan.
Fix: pace the requests below the limit. Spread your starts so you never go over the window, instead of reacting after a 429. Same 30 jobs, started at 9 per 10 seconds:
async def paced(n, per10):
gap = 10.0 / per10
async def job(i):
await asyncio.sleep(i * gap) # start i at i * gap seconds
await client.chat.completions.create(model="gpt-4o-mini",
messages=msgs, max_tokens=200)
await asyncio.gather(*[job(i) for i in range(n)])30 jobs paced at 9 per 10 s: 30 ok, 0 RateLimitError, 32.2sIt was slower on the clock and had zero failures and zero wasted calls. For a nightly batch, that is the trade you want. In production, put the pacing in a shared place, such as a Redis-backed limiter or a queue rate limit (Laravel example below), so eight workers share one budget instead of each assuming it has the whole limit.
2. You limited concurrency and still get 429s
This one catches many teams. A semaphore of 4 means at most four requests in flight. It says nothing about how many you send per minute. If each call is fast, four slots can still produce hundreds of requests a minute. My test with concurrency 4, plus retry on 429 using Retry-After and full jitter:
30 jobs, concurrency 4: 30 done, 31 retried 429s, failures 0, 22.2sEvery job finished because the retry logic was good, but it took 31 extra calls to get there. Concurrency limits protect your own server. Rate limits are about requests per time window. You usually need both. For the retry part, the pattern I use is in my guide to exponential backoff for API retries: honour Retry-After when present, add random jitter, cap the attempts, and give up loudly.
for attempt in range(6):
try:
return await client.chat.completions.create(...)
except RateLimitError as e:
if e.code == "insufficient_quota":
raise # never retry billing errors
wait = float(e.response.headers.get("retry-after", "1"))
await asyncio.sleep(wait + random.uniform(0, min(8, 2 ** attempt)))
raise RuntimeError("gave up after 6 attempts")3. Tokens per minute: the requests are too big
You can be well under the request limit and still get 429 because of tokens. In my mock (100 requests but only 3,000 tokens per window), 20 parallel calls with max_tokens=200:
20 parallel, max_retries=0: 12 ok, 8 RateLimitError in 1.1s
first error: Error code: 429 - Rate limit reached for gpt-4o-mini in organization org-lab on tokens per min (TPM): Limit 3000, Used 2940, Requested 245. Please try again in 8.976s.Notice Requested 245, although the prompt was about 45 tokens. OpenAI documents that the token limit is estimated from your prompt plus max_tokens, and my mock copies that rule. So a careless max_tokens: 4000 on a request that needs 150 words burns your budget without producing anything. Fixes:
- Set
max_tokens(ormax_output_tokens) to what the task really needs. A two-line report comment needs about 80. - Trim the prompt. Send the student's marks and attendance, not the whole history.
- Count tokens before sending (for example with
tiktokenfor OpenAI models) and pace by tokens, not only by requests.
Smaller requests also cost less. My notes on keeping LLM API costs under control cover the same levers from the billing side.
4. insufficient_quota: stop retrying
This is the small campus from the opening. The mock returned the documented quota error. The SDK still retried it, because it retries every 429:
openai._base_client INFO Retrying request in 0.484231 seconds (retry 1 of 2)
openai._base_client INFO Retrying request in 0.993278 seconds (retry 2 of 2)
after 1.5s: Error code: 429 - You exceeded your current quota, please check your plan and billing details.
code: insufficient_quotaTwo wasted retries per call are harmless once. Inside a queue that retries each job five times, with an SDK that retries each call twice, you get 15 calls per job, and none of them can succeed. Check e.code, fail the job straight away, and send an alert to whoever owns billing. Add credit or raise the spending limit in the provider dashboard, and only then re-queue the failed jobs.
5. Queue workers: rate-limit the job, not just the HTTP call
In our ERP the fix was a shared limiter on the queue. The Laravel version below is written from the Laravel documentation (I did not run it in this lab). RateLimitedWithRedis shares the limit across all workers and servers. Jobs over the limit are released back to the queue instead of hitting the API:
// AppServiceProvider::boot()
RateLimiter::for('llm-api', fn (object $job) => Limit::perMinute(300));
// app/Jobs/DraftReportComment.php
public function middleware(): array
{
return [new RateLimitedWithRedis('llm-api')];
}
public function retryUntil(): \DateTime
{
return now()->addHours(2); // count time, not attempts, while throttled
}
public function handle(): void
{
$response = Http::withToken(config('services.openai.key'))->timeout(60)
->post('https://api.openai.com/v1/responses', [
'model' => 'gpt-5.4-mini',
'input' => $this->prompt(),
'max_output_tokens' => 120,
]);
if ($response->status() === 429) {
if ($response->json('error.code') === 'insufficient_quota') {
$this->fail(new \RuntimeException('LLM quota exhausted'));
return;
}
$this->release((int) ($response->header('Retry-After') ?: 10) + random_int(1, 5));
return;
}
$response->throw();
// save the draft comment ...
}Set the limiter a little under your real limit so the interactive features of the app still have room. Queue workers, Supervisor and Horizon are covered in my Laravel queues with Redis guide.
Common mistakes
- Retrying every 429 the same way.
insufficient_quotaneeds a person, not a loop. - Stacking retries: SDK retries × HTTP client retries × queue attempts. Pick one layer to own retries and set the others to zero or one.
- Retrying without jitter, so all workers wake up together and hit the limit again at the same second.
- Treating a concurrency limit as a rate limit.
- Leaving
max_tokensat a huge default, which uses up the token budget even when answers are short. - Giving every worker or server the full limit. Eight workers each pacing to "300 per minute" send 2,400.
- Asking for a higher limit before fixing any of the above. A higher ceiling only delays the next burst.
Questions I get asked
How long should I wait after a 429?
If the response has Retry-After, wait at least that long, plus a little jitter. If it does not, start at about a second and back off exponentially with a cap. In my test the official Python SDK used the header value (9 s) when it was present.
Why do I get 429 when I have credit left?
Because the rate limit and the credit balance are separate. Read the message: requests per min or tokens per min means speed, while insufficient_quota means billing.
Does the OpenAI SDK retry automatically?
Yes. In openai-python 3.58.0 the default is 2 retries, and they apply to 429s, including quota errors. Pass max_retries on the client (or per request with with_options) to change it.
Will a bigger plan fix it?
It raises the limit. If the code still bursts, it will hit the new limit too. Pace first, then ask for more if steady usage really needs it. Before shipping, also test the failure paths. Force a 429 in staging (a mock like mine works) and check that jobs pause, retry and alert the way you expect.
About the author. Muhammad Wilayat Shah is a senior full-stack engineer and team lead based in Islamabad. He has 13+ years of experience shipping ERP, school ERP, HMS and SaaS products on Laravel, PHP, React, Next.js and PostgreSQL, and he is now adding LLM features to them. He wrote this after a term-end report-card job hit both kinds of 429 in the same week. More at wilayats.com/about.
Last reviewed: 24 Nov 2026




Comments
Join the discussion. Replies load on demand, up to 5 levels.
0 threads
No comments yet
Be the first to start the conversation.