跳到正文

第 18 课 · Reliability and Cost

Errors, Retries and Rate Limits

Handle OpenAI API errors, understand rate limits and 429 or 503 responses, configure SDK retries and timeouts, and add backoff without duplicate work.

In a real application, some requests fail. The network drops, a key expires, you send too much too fast, or the service is busy. A reliable program expects this. It knows which failures are worth retrying, how long to wait, and when to give up and tell the user.

Error families

Status Typical meaning Retry?
400 Invalid request No: fix the request
401 Bad or missing authentication No: fix the key
403 Not allowed, for example region or permission No
404 Resource or model not found No
429 Rate limit, rate spike, or a credit or spend limit It depends
500 Server error Yes, with backoff
503 Service temporarily overloaded Yes, with backoff

The Python SDK raises typed exceptions such as AuthenticationError, BadRequestError, RateLimitError, InternalServerError, APITimeoutError and APIConnectionError. APIStatusError covers responses with an error status.

A 429 is not always temporary. If you have run out of credit or hit a spend or usage limit, waiting and retrying will not help. A person must act. Check the error code and message, not only the status.

Built-in retries and timeouts

According to the official Python library's documentation, the SDK retries some failures twice by default with short exponential backoff: connection errors, 408, 409, 429 and 500 or higher. The default timeout is 10 minutes. Both can be changed.

Python
# Read-only
from openai import OpenAI

client = OpenAI(max_retries=3, timeout=60.0)

quick = client.with_options(timeout=15.0, max_retries=0)

A ten minute timeout is far too long for most web requests, so choose values that match your user experience. Note that a timed-out request can also be retried, so the total wait may be longer than one timeout. Long reasoning tasks may need longer limits or background mode.

Do not add your own retry loop on top of the SDK's retries without thinking. Three outer attempts times three inner attempts is nine calls. Choose one layer to own retries.

Handle errors by type

Python
# Read-only
import openai

try:
    response = client.responses.create(model="gpt-6.2-sol", input=question)
except openai.AuthenticationError:
    alert_operators("API key problem")
    raise
except openai.RateLimitError as error:
    queue_for_later(question, reason=str(error))
except openai.APIConnectionError:
    show_user("We could not reach the service. Try again.")
except openai.APIStatusError as error:
    log.error("status=%s request_id=%s", error.status_code, error.request_id)
    raise

Log the request ID. The SDK also exposes it as _request_id on successful responses. It helps support staff find a specific call. Do not log keys, and avoid logging private prompt content.

Rate limits

Limits are measured in several ways, such as requests per minute (RPM), requests per day, tokens per minute (TPM) and images per minute. Whichever you hit first applies. They are set per organization and project, differ by model, and grow with your usage tier. Your account's limits page shows your real numbers.

Responses can include headers like these:

  • x-ratelimit-limit-*, x-ratelimit-remaining-* and x-ratelimit-reset-*
  • Retry-After: the minimum number of seconds to wait for a temporary error

As of December 2026, the docs also describe two specific codes. A 429 with the code slow_down means your request rate rose too quickly, even if you are below your limits: reduce traffic and increase it gradually. A 503 with server_is_overloaded means the model is busy: wait and retry with growing delays.

Backoff with jitter

Exponential backoff doubles the delay after each failure. Jitter adds randomness so many clients do not retry at the same moment. Respect Retry-After as a minimum, and cap both the attempts and the total time.

Python Stand-in: retry with backoff and a budget

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The demo only prints the delays. A real program would sleep, ideally without blocking other work.

Retries and side effects

A retry may repeat work. If the first call succeeded but the reply was lost, running the whole step again might send a second email or create a second ticket. Protect actions with your own action ID: before you act, check whether that ID was already done. This matters most with function calling.

Reduce the pressure

  • Add a queue and limit how many calls run at once.
  • Spread bursts over time and ramp up traffic gradually.
  • Cache repeated results where it is safe.
  • Set max_output_tokens to a sensible level.
  • Use batch or background processing for work that can wait.

Degrade gracefully

When the model is unavailable, offer a fallback: show saved help articles, queue the request, or let the user continue manually. A circuit breaker that stops calling for a short time after many failures prevents a pile of waiting requests. If you fall back to another model, test it too, because quality and behavior can differ.

Test the failure paths

Error handling that never runs in testing usually breaks in production. Give your code a fake client that raises each kind of error: authentication, rate limit, timeout, connection and server error. Check what the user sees, what is logged and how many calls are made. Confirm that an action is not repeated after a timeout.

Do the same with a response that has an incomplete status and one that holds a refusal. These are not exceptions, so a try block alone will not catch them.

Do not try to cause real rate limit errors by flooding the service. A fake is cheaper, repeatable and polite.

Common mistakes

  • Catching every exception and returning an empty string, which hides authentication and billing problems.
  • Retrying at once, in a tight loop, which makes a rate limit problem worse.
  • Keeping the default timeout for a request that a person is waiting for.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which error should you usually not retry?

    Authentication errors need a fix, and retrying will fail again.
  2. 2. Is every 429 solved by waiting?

    Check the error code to tell a rate limit from a billing or spend limit.
  3. 3. Why add jitter to backoff?

    Randomness spreads out retries and reduces synchronized load.
  4. 4. What is the risk of stacking your retry loop on the SDK's retries?

    Inner and outer retries multiply each other.

Summary

  • Sort errors into fix-it errors and temporary ones, and check error codes.
  • The SDK retries some errors and has a long default timeout; set your own values.
  • Respect rate limit headers and Retry-After; use backoff with jitter and a budget.
  • Protect side effects with action IDs.
  • Log request IDs and plan a fallback.

Next: Tokens, Costs and Prompt Caching

你的学习进度保存在此浏览器中,无需账号。