Every production application that calls the OpenAI API will eventually see errors: a rate limit during a traffic spike, a network blip, a request that is too long, an expired key, or a temporary outage on OpenAI’s side. How your code responds decides whether users see a brief delay or a broken feature. This guide explains the error types you will meet, which ones are worth retrying, how the official Python SDK helps, and the reliability patterns that keep an AI feature working when the API misbehaves.
What an API Error Looks Like
When a request fails, the API returns an HTTP status code and a JSON error body containing a human-readable message, a broad error type, and a more specific error code. The code is the field to inspect when you need to know exactly what went wrong, because the same status can have several causes. Every response also carries a request ID in the response headers. Log it with every failure, since OpenAI support will ask for it when you report a problem. Build your error handling around status codes and error codes, never around matching message text, which can change.
Figure 1 — Common errors and what to do
The SDK Exception Hierarchy
The official Python library turns failures into typed exceptions. The base class covers all API errors. Beneath it, connection problems, including timeouts, are separate from errors that come back with an HTTP status, and the status errors have a subclass for each common code: bad request, authentication, permission denied, not found, conflict, unprocessable entity, rate limit, and internal server error. Catch the most specific classes first and the general ones last, because a rate limit error is also a status error, and a timeout is also a connection error. Each status exception exposes the status code, the error code, and the request ID, which gives you everything you need for logging and decisions.
What the SDK Retries for You
You do not have to write retry logic for the basics. The official SDKs retry connection errors and responses with status 408, 409, 429, and 5xx automatically, twice by default, with a short exponential backoff, and they honour the Retry-After header when the API sends one. You can change the count when creating the client, or per call with the with_options helper. When the retries run out, the SDK raises the exception, so your code still needs a plan for what happens next. Timeouts are also configurable, and the default request timeout is long, on the order of minutes, which is rarely what an interactive application wants. Set a timeout that matches your user experience, and a shorter one for requests you will retry.
The Two Kinds of 429
A 429 status is the error people meet most, and it hides two very different situations. The first is a genuine rate limit, where you have exceeded your requests per minute or tokens per minute. Waiting and retrying usually works. The second is a billing or quota problem, such as an exhausted credit balance or a spending limit, reported with an insufficient quota style error code. Waiting never fixes that, because the cause is your account rather than your request rate, so retrying only wastes time. Always check the error code before deciding. Treat the billing codes as an alert-and-stop condition that notifies a human, and treat the rate limit codes as retryable with backoff.
Backoff Done Properly
When you do retry, wait before each attempt and increase the wait each time. Respect the Retry-After header if present. If it is absent, use exponential backoff, doubling the delay after each failure, and add random jitter so that many clients do not retry at the same instant and cause a second spike. Cap both the delay and the number of attempts. Two warnings apply. First, if you write your own retry loop, set the client’s max_retries to zero, otherwise each of your attempts silently becomes several requests, which makes throttling worse. Second, retrying without waiting does not help: failed requests can count toward your limits, so aggressive retries keep you throttled.
A Practical Wrapper
import openai
from openai import OpenAI
client = OpenAI(max_retries=3, timeout=30.0)
BILLING_CODES = {"insufficient_quota", "credit_balance_exhausted"}
def ask(prompt):
try:
response = client.responses.create(model="gpt-5.4-mini", input=prompt)
return response.output_text
except openai.RateLimitError as error:
if error.code in BILLING_CODES:
raise # retrying will not help: alert a human
return None # still throttled after retries: show a busy message
except openai.APITimeoutError:
return None # the request took too long
except openai.APIConnectionError:
return None # network problem
except openai.APIStatusError as error:
print(error.status_code, error.request_id)
raise
The model name is only an example, so use your current model. The pattern matters more than the details: specific exceptions first, billing separated from rate limits, request IDs logged, and a defined fallback result for the cases you can survive.
Handling 400 Errors
A 400 means the request itself is invalid, and retrying the identical request will fail again. The most common cause in AI applications is a prompt that exceeds the model’s context window, reported with a context-length error code. Fix it by counting tokens before sending, trimming or summarising old conversation turns, chunking long documents, or using retrieval to send only the relevant passages. Other 400s come from invalid or unsupported parameters, such as a setting that a particular model does not accept, or malformed schemas for structured outputs. Log the full message in development, and treat a spike of 400s in production as a bug in your code or a model change rather than a transient fault.
When the Request Succeeds but the Answer Is Incomplete
Some failures return a 200 status. A response can stop because it reached the maximum output length, which shows up as a finish reason of length in Chat Completions or an incomplete status in the Responses API. It can also stop because of a content filter. A structured output request can end in a refusal rather than parsed content. If your code assumes every 200 response contains a complete, valid answer, it will eventually break. Check the finish reason or status, handle truncation by raising the output limit or asking for a shorter answer, handle refusals with a clear message, and validate parsed data before using it.
Streaming Failures
Streams can fail midway. The connection may drop after half the answer has been shown, or an error event may arrive in the middle of the stream. Decide in advance what your user interface does: keep the partial text and offer a retry button, or discard it and retry automatically. If the operation has side effects, such as a tool call that updates a record, make those actions idempotent so a retry cannot apply them twice. Track what was received, and avoid retrying silently in a way that duplicates visible text.
Reliability Patterns Beyond Retries
Retries handle brief faults, but production systems need more. Use a client-side rate limiter or queue so your application stays under its limits instead of bouncing off them, and cap concurrency. Add a circuit breaker that stops sending requests for a short period after repeated failures, so you recover faster and fail quickly instead of piling up timeouts. Define fallbacks: a smaller model, a cached answer, a simpler non-AI path, or a second provider for critical features. Use queues and asynchronous processing for anything that is not interactive, so spikes are absorbed rather than failed. For large offline jobs, the Batch API avoids real-time rate limits altogether.
Logging, Metrics, and Alerts
You cannot fix what you cannot see. For every failed call, log the timestamp, status, error code, model, request ID, latency, and the retry count. Track error rates by code, latency percentiles, and the share of requests that needed a retry. Alert immediately on authentication and billing errors, because they will not resolve themselves, and alert on sustained increases in rate limits or server errors. Keep the content of prompts out of logs, or redact it, if they may contain personal data.
Testing Your Error Paths
Error handling code is rarely exercised, so test it deliberately. Mock the API to return each error type, including a 429 with and without a Retry-After header, a billing error, a timeout, a 500, and a truncated response, and confirm your application behaves correctly in every case. Run a small load test to see how your system behaves when it is throttled. The first time your retry logic runs should not be during a real outage.
Common Mistakes
- Retrying every error. Authentication, bad request, and billing errors will not fix themselves.
- Stacking retries. A custom loop on top of SDK retries multiplies your request count.
- No jitter. Synchronised retries create repeated spikes.
- Ignoring the finish reason. A 200 response can still be truncated or refused.
- Relying on the default timeout. It is usually far longer than a user will wait.
- Not logging request IDs. Support cannot investigate without them.
Frequently Asked Questions
- Why do I get a 429 when I am well below my limits?
- Check the error code. It may be a billing or quota problem rather than a rate limit, or a limit on tokens rather than requests. Rate limits can also apply per project, per model, and over short windows.
- How many times should I retry?
- A small number, typically three to five, with exponential backoff and jitter. More retries mostly add latency and load without improving success.
- Does the SDK retry automatically?
- Yes. It retries connection errors and 408, 409, 429, and 5xx responses twice by default. You can raise or lower the count, or set it to zero if you manage retries yourself.
- What should I do during an OpenAI outage?
- Fail gracefully: show a clear message, serve cached or simplified results where possible, and consider a fallback model or provider for critical paths. Check OpenAI’s status page for confirmation.
Last updated: November 2026. Error codes and SDK behaviour change over time, so confirm details in OpenAI’s error codes guide and the SDK documentation.