Overview
The OpenAI Python SDK automatically retries certain failed requests using exponential backoff. This improves reliability by handling transient errors without manual intervention. Default retry behavior:- Max retries: 2 attempts (3 total requests including the initial attempt)
- Retry conditions: Connection errors, timeouts, rate limits, and server errors
- Backoff strategy: Exponential backoff with jitter
Automatic Retries
The SDK automatically retries these error conditions:- Connection errors - Network connectivity problems
- 408 Request Timeout - Request took too long
- 409 Conflict - Resource conflict (lock timeout)
- 429 Rate Limit - Too many requests
- 5xx Server Errors - Internal server errors
Configuring Retries
Client-Level Configuration
Set the default retry behavior for all requests:Per-Request Configuration
Override retry settings for individual requests:Backoff Strategy
The SDK uses exponential backoff with jitter to space out retry attempts:Algorithm
- Initial delay: 0.5 seconds
- Exponential increase: Delay doubles with each retry
- Maximum delay: 8 seconds
- Jitter: ±25% random variation
Calculation
Example Timeline
Retry-After Header
The SDK respects theRetry-After header from rate limit responses:
retry-after-ms header for millisecond precision.
Priority:
retry-after-msheader (milliseconds)Retry-Afterheader (seconds or HTTP date)- Exponential backoff algorithm
If the
Retry-After value is reasonable (≤60 seconds), it takes precedence over the exponential backoff calculation.Server-Controlled Retries
The API can explicitly control retry behavior using thex-should-retry header:
x-should-retry: true- Always retry, even if not normally retryablex-should-retry: false- Never retry, even if normally retryable
Idempotency
The SDK automatically adds idempotency headers to retried requests (except GET requests):Retry Headers
The SDK includes metadata headers with each request:x-stainless-retry-count- Number of retries taken (0 for first attempt)x-stainless-read-timeout- Read timeout in seconds
Async Retries
Retries work identically withAsyncOpenAI, using async sleep:
Custom Retry Logic
For custom retry logic, catch exceptions and implement your own strategy:Monitoring Retries
Enable logging to see retry attempts:Best Practices
Error Scenarios
Retried Automatically
Not Retried
Related
- Error Handling - Exception types and handling
- Timeouts - Configuring request timeouts
- Client Initialization - Client configuration options