Timeouts and Retries in LLM APIs: How to Avoid Losing Requests
When integrating LLM APIs into production systems, network errors, server overloads, and long responses are inevitable. Without handling timeouts and implementing retries, users will see errors, and data will be lost. Below is how to configure timeouts, implement retries with exponential backoff, and ensure idempotency of requests.
Why Timeouts Are Critical
LLM APIs operate under unstable load conditions. The model may take longer than usual to respond due to peak load, and network failures can occur even with large providers. Without a timeout, a request can hang indefinitely, consuming resources and degrading the user experience.
A timeout is a time limit for waiting for a response. There are two types:
- connect timeout — time to establish a connection;
- read timeout — time to wait for data after establishing a connection.
For LLM APIs, the read timeout should be longer, as token generation takes time. Typically, the connect timeout is set to 10 seconds and the read timeout to 60–120 seconds, depending on the model and complexity of the request.
Configuring Timeouts in Clients
Most SDKs allow setting timeouts when creating a client. Example for OpenAI Python SDK:
from openai import OpenAI
client = OpenAI(
api_key="sk-...",
timeout=60.0, # overall timeout
max_retries=0 # disable built-in retries, implement our own
)
Built-in retries in SDKs often do not account for the specifics of LLM: they repeat the request immediately, which can exacerbate overload. It is better to disable them and implement custom logic.
Retry Strategy
Retries should be limited in number and time. A classical scheme is exponential backoff with jitter:
import time
import random
def retry_with_backoff(func, max_retries=3, base_delay=1.0):
for attempt in range(max_retries + 1):
try:
return func()
except Exception as e:
if attempt == max_retries:
raise
delay = base_delay * (2 ** attempt) + random.uniform(0, 0.5)
print(f"Error: {e}. Retrying in {delay:.2f} sec")
time.sleep(delay)
Usage:
def call_llm(prompt):
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
result = retry_with_backoff(lambda: call_llm("Hello"))
Which Errors to Retry
Not all errors require a retry. They are categorized into three groups:
| Error Type | HTTP Code | Retry? |
|---|---|---|
| Server overload | 429, 503 | Yes, with delay |
| Temporary network failure | 502, 504 | Yes, with delay |
| Request error | 400, 401, 403, 422 | No, fix the request |
Retrying 4xx errors is pointless — the problem is with the request, not the server. 5xx and 429 errors should be retried, but with respect to the Retry-After header, if present.
Idempotency of Requests
When retrying requests, it is important that they do not lead to duplicate operations. For example, if you use LLM for content generation and save the result in a database, a retry request may create a duplicate.
Solution — pass a unique request identifier and check it on the server side. Some APIs support the Idempotency-Key header:
import uuid
headers = {
"Idempotency-Key": str(uuid.uuid4())
}
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Generate an article"}],
extra_headers=headers
)
If the API does not support idempotency, the result is saved by key (e.g., prompt hash), and checked before a retry to see if it has already been processed.
Monitoring and Alerts
Retries hide problems but do not solve them. The number of retry attempts and response time are always logged. If the percentage of requests with retries exceeds a threshold, it is a signal for action: perhaps the timeout needs to be increased, the provider changed, or a provider fallback added.
Example metric:
import logging
logger = logging.getLogger(__name__)
def call_with_metrics(prompt):
start = time.time()
retries = 0
try:
result = retry_with_backoff(lambda: call_llm(prompt))
except Exception:
logger.error("LLM call failed after retries", exc_info=True)
raise
finally:
duration = time.time() - start
logger.info(f"LLM call: duration={duration:.2f}s, retries={retries}")
return result
Conclusion
Timeouts and retries are an essential part of integrating with LLM APIs. Proper timeout configuration prevents hangs, while retries with exponential backoff increase reliability without overloading servers. Idempotency protects against data duplication, and monitoring helps to spot issues in time. Additionally, consider API abuse protection and rate limit budgeting.
