Fix OpenAI API 429 Errors in Python Agents Safely
If the OpenAI API returns a temporary 429, use bounded backoff to retry only the model call, not the whole job. If the error code is insufficient_quota, check API billing or available quota instead. Save the ticket before calling the model so the agent can resume from the saved note.

Your support agent creates a review ticket, then the OpenAI API returns a 429 while it’s drafting the handoff. Don’t rerun the whole job: retry the model call if it’s throttled, and save the ticket before that call so you can resume. This setup is for Python agents with side effects; if yours only generates text, use the retry wrapper and skip the database.
Illustrative traceback (plain text):
openai.RateLimitError: Error code: 429 — Rate limit reachedRead the 429 before you retry

The current Python SDK raises openai.RateLimitError for HTTP 429 responses. Inspect the error code: insufficient_quota means you need to check API billing or available quota, not wait and try again. Temporary throttling is the case where bounded backoff helps.
RPM is a request-rate limit; TPM is a token-rate limit. Five local tools can run in parallel without making five OpenAI requests. What counts toward RPM is the OpenAI traffic your code sends, such as a follow-up model call that submits those tool results together.
TPM isn’t simply actual input plus output in a rolling minute. The OpenAI rate-limit guide describes accounting based on the larger of a request-size token estimate and the configured output allowance. Repeatedly appending raw tool results makes later requests bigger, but growth depends on what you retain. Keep the fields the model needs and cap output to suit the task.
Check what limits and billing actually apply

Open the API Limits page for the organization and project tied to your key. Check the model’s limits and any shared model pool; use the response headers for remaining requests, tokens, and reset timing. Traffic can be throttled in short bursts, and failed attempts can consume rate-limit capacity. Queue work across workers rather than adding a fixed sleep, and confirm any tier change in the dashboard before raising concurrency.
The API Pricing page lists model-specific input and output token rates and separate charges for some hosted tools. Illustrative Scenario: At 1,000 drafts with 2,000 billable input and 200 output tokens each, no cached input, and no paid hosted tools, budget twice the published per-million input rate plus one-fifth of the output rate. Extra model turns can quietly raise that bill.
Set up one retry budget and one checkpoint
- Install the current SDK with
pip install -U openai. SetOPENAI_API_KEYandOPENAI_MODELto a Responses API model your project can access. - Pick one retry owner. This script sets
max_retries=0so the SDK’s defaults don’t stack with its three attempts. Runpython recover.py CASE-42; reuse that ID only for the same job. - Commit the local ticket before calling OpenAI. Here the ticket row doubles as the checkpoint. For an external ticketing API, use a stable idempotency key if supported; otherwise reconcile uncertain writes before retrying them.
# recover.py
import os, random, sqlite3, sys, time
from openai import OpenAI, RateLimitError
client = OpenAI(max_retries=0, timeout=20)
run_id = sys.argv[1]
def draft_handoff(note):
for attempt in range(3):
try:
result = client.responses.create(
model=os.environ['OPENAI_MODEL'], store=False,
max_output_tokens=200,
input=f'Draft a one-sentence internal support handoff. '
f'Use only these facts; do not promise a refund: {note}',
)
if result.status != 'completed' or not result.output_text.strip():
raise RuntimeError('No complete draft; ticket is saved')
return result.output_text
except RateLimitError as exc:
if exc.code in {'insufficient_quota', 'billing_hard_limit_reached'} or attempt == 2:
raise
hint = exc.response.headers.get('retry-after')
delay = random.uniform(0.5, 1) * 2**attempt
if hint is not None:
try:
delay = max(delay, float(hint)) # Numeric seconds only.
except ValueError:
raise exc # Leave other formats to the caller.
if delay > 10:
raise
time.sleep(delay)
db = sqlite3.connect('agent.db')
with db:
db.execute('CREATE TABLE IF NOT EXISTS tickets '
'(id TEXT PRIMARY KEY, note TEXT NOT NULL, draft TEXT)')
db.execute('BEGIN IMMEDIATE')
row = db.execute('SELECT note, draft FROM tickets WHERE id=?', (run_id,)).fetchone()
if row is None:
note = 'Duplicate charge reported; billing review pending.'
db.execute('INSERT INTO tickets VALUES (?, ?, NULL)', (run_id, note))
else:
note = row[0]
if row is not None and row[1] is not None:
print(row[1])
else:
draft = draft_handoff(note)
with db:
db.execute('UPDATE tickets SET draft=? WHERE id=?', (draft, run_id))
print(draft)Walk through a throttled run

In an illustrative run, CASE-42 creates the local ticket, then the first model call hits a temporary 429. The wrapper waits with jitter and retries just that call. If the budget runs out, rerun the same command after throttling clears: it loads the existing ticket and drafts from the saved note. A good result reads, “Please review the reported duplicate charge; billing review is pending.” Check that there’s one ticket and no invented refund approval.
A crash after the model returns but before the draft is saved can still repeat the model call. Use one worker per run ID to avoid concurrent drafts. Keep sensitive data out of prompts and checkpoints where possible: store=False doesn’t disable all retention, and API data controls distinguish retention from training.
Pick the recovery layer that fits
| Setup | What to configure | Where recovery stops |
|---|---|---|
| LangGraph | Durable checkpointer, stable thread ID, and a retry policy that distinguishes throttling from quota | Resume a failed run with None and the same thread configuration; unfinished work can replay, so make side effects idempotent. |
| CrewAI agents | The documented max_rpm and max_retry_limit settings | Pacing and agent retries aren’t a checkpoint. Check what the provider client retries too. |
| AutoGen AgentChat 0.4-style API | Save and load team state explicitly; configure retries on the OpenAI model client | A saved team snapshot doesn’t record external writes made after it. |
Choose the plain SDK for a short workflow with a few explicit steps. Pick LangGraph if you need checkpointed branching; if you already use CrewAI or AutoGen, keep the framework and make tool writes safe to resume. Today, force one temporary 429 in a development run and verify that resuming leaves exactly one ticket.
Related resources
Frequently Asked Questions
Will backoff fix exhausted quota?
No. If the error code is insufficient_quota, check API billing or available quota. Use bounded backoff for temporary throttling.
Do parallel tools each count as an OpenAI request?
No. Only the OpenAI requests your workflow sends count toward RPM.
How do I resume after the retry budget runs out?
Wait for throttling to clear, then rerun the same command with the same run ID. The script loads the existing ticket and drafts from the saved note.
Does a text-only agent need a database checkpoint?
No. If the agent only generates text, use the retry wrapper and skip the database.
Get the Weekly SMB AI & SaaS Brief
Practical software benchmarks, prompt templates, and ROI breakdowns delivered every Tuesday. No fluff, unsubscribe anytime.