Retries, Timeouts, and Backoff

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 55 of 224

Building on Lesson 1's Distinction

Lesson 1 established that retryable errors (429, 500, 503) and connection-level failures (timeouts, network errors) are worth retrying, while client errors (400, 401, 403, 404) aren't — retrying them just reproduces the same failure. This lesson builds the actual retry logic that acts on that distinction: how long to wait between attempts, how many attempts to allow, and how the SDK's own built-in retry behavior relates to logic you might still want to write yourself.

The SDK Retries Some Failures Automatically

The base SDK client already retries a subset of failures — typically connection errors and certain retryable status codes — without any code on your part, following a built-in backoff strategy.

from openai import OpenAI

client = OpenAI(max_retries=3)

response = client.responses.create(model="gpt-5.6-terra", input="Hello")

Note: The exact default number of retries, which specific status codes and error types are retried automatically, and the backoff timing used can vary by SDK version. Confirm the current default retry behavior against your installed SDK version's documentation before assuming a specific number of automatic retries.

This means a meaningful amount of transient-failure handling already happens without you writing anything — a request that fails with a 503 and would have succeeded on a second attempt a moment later is often retried automatically, invisibly, before an exception ever reaches your code at all. Understanding this matters because it changes what additional retry logic is actually worth building on top: mostly, cases the default behavior doesn't cover, or cases where you want more control over the specific policy than the default provides.

Why Backoff Needs to Be Exponential, Not Fixed

A retry loop that waits the same fixed amount of time between every attempt tends to make a transient overload situation worse rather than better — if a service is struggling under load and every failed client retries again after exactly one second, the retries themselves add to the load in a synchronized burst. Exponential backoff — waiting progressively longer between each successive retry — spreads retry attempts out over time instead, giving the underlying condition more room to recover.

import time
import random

def call_with_backoff(client, max_attempts: int = 5, base_delay: float = 1.0):
    for attempt in range(max_attempts):
        try:
            return client.responses.create(model="gpt-5.6-terra", input="Hello")
        except Exception as e:
            if attempt == max_attempts - 1:
                raise
            delay = base_delay * (2 ** attempt) + random.uniform(0, 0.5)
            print(f"Attempt {attempt + 1} failed, retrying in {delay:.1f}s")
            time.sleep(delay)

base_delay * (2 ** attempt) is what produces the exponential growth — 1 second, then 2, then 4, then 8 — and the small random amount added on top (random.uniform(0, 0.5)), known as jitter, prevents many separate clients from retrying at exactly synchronized intervals, which would otherwise recreate the same synchronized-burst problem exponential backoff alone doesn't fully solve.

Only Retrying What's Actually Retryable

This loop, as written so far, retries every exception indiscriminately — exactly the mistake Lesson 1 warned against. A correct version checks Lesson 1's retryable-versus-client-error distinction before deciding to retry at all.

from openai import APIStatusError, APIConnectionError, APITimeoutError

def is_retryable_error(exception) -> bool:
    if isinstance(exception, (APIConnectionError, APITimeoutError)):
        return True
    if isinstance(exception, APIStatusError):
        return exception.status_code in (429, 500, 503)
    return False

def call_with_smart_backoff(client, max_attempts: int = 5, base_delay: float = 1.0):
    for attempt in range(max_attempts):
        try:
            return client.responses.create(model="gpt-5.6-terra", input="Hello")
        except Exception as e:
            if not is_retryable_error(e) or attempt == max_attempts - 1:
                raise
            delay = base_delay * (2 ** attempt) + random.uniform(0, 0.5)
            time.sleep(delay)

This is the meaningful improvement over the naive version: a 400 error from a malformed request now fails immediately, on the first attempt, rather than being retried four more times with no chance of succeeding — exactly the wasted cost and time Lesson 1 flagged as the consequence of not making this distinction.

Setting Explicit Timeouts

Beyond retrying a failed request, it's worth explicitly bounding how long any single attempt is allowed to wait for a response, since a request that hangs indefinitely is a different failure mode than one that fails quickly and can be retried promptly.

client = OpenAI(timeout=30.0)

response = client.responses.create(
    model="gpt-5.6-terra",
    input="Hello",
    timeout=10.0,  # overrides the client-level default for this specific call
)

Note: The exact default timeout, and whether it's a single overall timeout or separate connect/read timeouts, can vary by SDK version. Confirm the current default and configuration options against your installed SDK version's documentation.

Setting an explicit timeout matters especially for a request with a longer expected processing time — Unit 3's higher reasoning-effort settings, or Unit 9's built-in tools performing real work (Code Interpreter execution, a multi-step MCP interaction) — where the appropriate timeout is meaningfully longer than for a simple, fast request, and a single fixed timeout across every kind of request in an application risks being either too short for the slow cases or unnecessarily long for the fast ones.

Retrying an Entire Multi-Step Loop, Not Just One Call

Unit 8, Lesson 3's tool-calling loop and Unit 11's agent runs involve multiple internal calls to the model, not just one — retry logic applied naively at the level of the whole loop can end up repeating steps that already succeeded, which is wasteful and, for a tool with a real side effect, potentially harmful (retrying an entire loop that already successfully issued a refund, for instance, risking issuing it twice).

def run_single_step_with_retry(client, input_messages, tools):
    return call_with_smart_backoff_for_response(client, input_messages, tools)

def call_with_smart_backoff_for_response(client, input_messages, tools, max_attempts=3, base_delay=1.0):
    for attempt in range(max_attempts):
        try:
            return client.responses.create(model="gpt-5.6-terra", input=input_messages, tools=tools)
        except Exception as e:
            if not is_retryable_error(e) or attempt == max_attempts - 1:
                raise
            time.sleep(base_delay * (2 ** attempt))

Applying retry logic at the level of a single model call within the loop, rather than around the entire multi-step loop, means a transient failure on step three of a five-step interaction only retries step three, not steps one and two that already completed successfully — a meaningfully safer and less wasteful granularity for retry logic in any multi-step system.

Common Mistakes

Retrying every exception indiscriminately, rather than checking Lesson 1's retryable-versus-client-error distinction first, wasting time and cost on requests that will never succeed no matter how many times they're retried.

Using a fixed delay between retries instead of exponential backoff, risking a synchronized retry burst that makes an already-overloaded service worse rather than better.

Omitting jitter from an exponential backoff implementation, allowing many clients to retry at exactly synchronized intervals even with growing delays.

Wrapping retry logic around an entire multi-step loop or agent run, risking repeated execution of steps — including consequential tool calls — that already succeeded on an earlier attempt.

Relying entirely on the SDK's default automatic retry behavior without setting an explicit timeout, leaving a request that hangs indefinitely with no bound on how long a single attempt is allowed to take.

Best Practices

Check whether a failure is actually retryable before retrying it, using Lesson 1's status-code distinction to avoid wasting attempts on client errors.

Use exponential backoff with jitter for any custom retry logic, spreading retry attempts out over time rather than risking a synchronized burst.

Set explicit timeouts appropriate to the expected duration of a specific kind of request, rather than relying on one fixed timeout across requests with very different expected processing times.

Apply retry logic at the granularity of a single model call within a multi-step loop, rather than around the entire loop, to avoid re-executing steps — especially consequential tool calls — that already succeeded.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Retries, Timeouts, and Backoff and get answers drawn from it.

Signed-in readers only.