Your batch script or app runs fine for a few minutes, then hits a wall of 429 Too Many Requests. Usually the API had been warning you for a while: each response carries headers that say how many requests and tokens are left in the current window. This post shows how to see those headers, read them from Python, and use them to slow down before you hit the limit.
The headers you get
| Header | OpenAI | Azure OpenAI | Meaning |
|---|---|---|---|
x-ratelimit-limit-requests | Yes | Not always | Request limit for the window |
x-ratelimit-limit-tokens | Yes | Not always | Token limit for the window |
x-ratelimit-remaining-requests | Yes | Yes | Requests left in the current window |
x-ratelimit-remaining-tokens | Yes | Yes | Tokens left in the current window |
x-ratelimit-reset-requests | Yes | Not always | Time until the request counter resets, for example 1s |
x-ratelimit-reset-tokens | Yes | Not always | Time until the token counter resets, for example 6m0s |
retry-after | On 429 | On 429 | Seconds to wait before retrying |
retry-after-ms | Sometimes | On 429 | Milliseconds to wait before retrying |
Which headers you get depends on the provider, the API (Chat Completions or Responses) and the deployment type. Check what your own endpoint returns before you depend on one of them. Some users have reported -1 or 0 in these headers on certain models and APIs. Treat any negative value as "unknown", not "no capacity".
Tip
On Azure OpenAI, the remaining-tokens figure is an estimate made when the request arrives. It counts your prompt plus the
max_tokens(ormax_completion_tokens) you asked for, not the tokens actually generated. A highmax_tokensuses up the token window faster than your real usage would.
See the headers with curl
Start with a single call so you know what your endpoint actually returns.
OpenAI:
curl -sS -i https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"ping"}],"max_tokens":5}' \
| grep -iE '^(x-ratelimit|retry-after|x-request-id)'
Azure OpenAI (use your resource and deployment name):
RES=my-aoai-resource
DEP=gpt-4o-mini-prod
curl -sS -i "https://$RES.openai.azure.com/openai/deployments/$DEP/chat/completions?api-version=2024-10-21" \
-H "api-key: $AZURE_OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"ping"}],"max_tokens":5}' \
| grep -iE '^(x-ratelimit|retry-after|apim-request-id|x-ms-region)'
If you use Entra ID, replace the api-key header with -H "Authorization: Bearer $(az account get-access-token --resource https://cognitiveservices.azure.com --query accessToken -o tsv)".
Run it twice in a row. x-ratelimit-remaining-tokens should drop between the two calls. If it doesn't change at all, a gateway in front of the model may be replacing or removing the headers. See the gateway section below.
Read the headers from Python
By default the openai SDK returns only the parsed body. Use with_raw_response to get the headers as well:
from openai import OpenAI
client = OpenAI() # for Azure, use your existing AzureOpenAI or v1 base_url client
raw = client.chat.completions.with_raw_response.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Summarise: disk full on /var"}],
max_tokens=200,
)
completion = raw.parse() # the normal ChatCompletion object
h = raw.headers
print("remaining requests:", h.get("x-ratelimit-remaining-requests"))
print("remaining tokens: ", h.get("x-ratelimit-remaining-tokens"))
print("reset tokens: ", h.get("x-ratelimit-reset-tokens"))
print("usage: ", completion.usage.total_tokens)
On a 429 the SDK raises openai.RateLimitError. Its response attribute has the headers:
import openai
try:
client.chat.completions.create(model="gpt-4o-mini",
messages=[{"role": "user", "content": "hi"}])
except openai.RateLimitError as e:
print("retry-after: ", e.response.headers.get("retry-after"))
print("retry-after-ms:", e.response.headers.get("retry-after-ms"))
print("body:", e.body)
The SDK retries 429s on its own (max_retries, default 2) and uses retry-after-ms or retry-after when they're there. You only see the exception after those retries run out. If your own code already paces requests, set max_retries lower so the same request isn't retried at two layers.
Pace requests before the 429
The simplest useful pattern: after each response, check how many tokens are left. If the next request might not fit, wait until the window resets.
import re
import time
_UNIT = {"ms": 0.001, "s": 1, "m": 60, "h": 3600}
def parse_reset(value: str | None, default: float = 1.0) -> float:
"""Turn '6m0s', '1s' or '250ms' into seconds."""
if not value:
return default
parts = re.findall(r"(\d+(?:\.\d+)?)(ms|h|m|s)", value)
return sum(float(n) * _UNIT[u] for n, u in parts) or default
def to_int(value: str | None) -> int | None:
try:
n = int(value)
return n if n >= 0 else None # -1 means unknown
except (TypeError, ValueError):
return None
def call_paced(client, messages, model="gpt-4o-mini", max_tokens=300,
est_prompt_tokens=1000, safety=1.2):
raw = client.chat.completions.with_raw_response.create(
model=model, messages=messages, max_tokens=max_tokens)
h = raw.headers
left_tokens = to_int(h.get("x-ratelimit-remaining-tokens"))
left_reqs = to_int(h.get("x-ratelimit-remaining-requests"))
need = (est_prompt_tokens + max_tokens) * safety
if (left_tokens is not None and left_tokens < need) or left_reqs == 0:
wait = parse_reset(h.get("x-ratelimit-reset-tokens"))
print(f"low quota (tokens={left_tokens}, requests={left_reqs}); sleeping {wait:.1f}s")
time.sleep(wait)
return raw.parse()
Notes on this sketch:
- On Azure, when
x-ratelimit-reset-tokensis missing,parse_resetfalls back to one second. Azure limits are enforced over short intervals within each minute, so a short wait is usually enough. - Headers describe one deployment or one key as seen at that moment. With many workers, each one sees the same falling number and they all slow down together, which is fine. For strict control across replicas, use a shared token bucket rather than headers alone.
- Log
left_tokenswith each call. A chart of remaining tokens over time shows how close you run to the limit, long before any 429 appears.
When a gateway sits in front
Azure API Management, LiteLLM and other gateways may apply their own limits and may not pass the backend's headers through. Two things to check:
- Which limit sent the 429? A 429 from an APIM
llm-token-limitorazure-openai-token-limitpolicy comes from the gateway, not the model. The backend headers say nothing about that limit. These policies can write their own headers throughremaining-tokens-header-nameandtokens-consumed-header-name. Set those so clients can see the gateway's remaining count. - Which backend answered? With load-balanced backend pools, two calls in a row can land on different deployments, each with its own counter. Remaining values that jump up and down usually mean you're seeing several backends.
Warning
Don't build a "wait until the window resets" loop that has no upper bound. A misread header (
6m0sparsed as 6 hours, or a gateway sending a hugeretry-after) can park every worker for hours. Cap the sleep, for example at 60 seconds, and log whenever the cap is applied.
Prevent it next time
- Log
x-ratelimit-remaining-tokens,retry-afterand the request ID on every call. They cost nothing and make 429 incidents much quicker to explain. - Set
max_tokensclose to what you actually need. On Azure this directly frees up token quota. - Alert when remaining tokens stay below about 10% of the limit for several minutes. That warns you before users see errors.
- Check the headers again after you change provider, API version or gateway policy. Header sets differ, and pacing code that quietly gets
Nonestops pacing.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get