🚀 One API for every frontier model on FastInfra

Browse models

Transparent per-token pricing → compare providers on FastInfra

View pricing

OpenAI-compatible chat completions → start in minutes

Read the docs

⚡ Server Auction → Enterprise bare metal from $78.15/mo (173 in stock)

Browse deals

API Rate Limits and Retry Logic for OpenAI-Compatible Inference

Rate limits cause silent failures in production inference pipelines. You need deterministic retry logic to handle 429 errors without exhausting your budget or blocking users. FastInfra routes requests across models to minimize congestion, but your client must still respect concurrency limits. This guide covers exponential backoff, circuit breakers, and request queuing patterns to ensure stable integration with any OpenAI-compatible API.

Understanding Rate Limit Responses

OpenAI-compatible APIs enforce throughput constraints using HTTP 429 (Too Many Requests) status codes. When a client exceeds the allowed request rate or concurrent connection limit, the server rejects the request immediately. This prevents resource starvation and ensures stable latency for other users sharing the same model instance. The response body typically contains a JSON error object detailing the specific limit violation.

The Retry-After header is the primary mechanism for determining when to resume sending requests. It specifies the number of seconds the client must wait before issuing the next request. Ignoring this header and retrying immediately increases the probability of repeated 429 errors, wasting compute resources and delaying application response times. Clients should parse this header value and pause execution accordingly.

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 5

{
  "error": {
    "message": "Rate limit exceeded for model gpt-4",
    "type": "rate_limit_error",
    "param": null,
    "code": "rate_limit_exceeded"
  }
}

Some providers include additional metadata in the response headers, such as X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset. These headers provide visibility into the current quota state, allowing clients to adjust their sending rate proactively before hitting the hard limit. FastInfra’s routing layer respects these signals across its catalog of 723 models, ensuring consistent behavior regardless of the underlying provider.

Understanding these responses is critical for building resilient inference pipelines. A robust client must distinguish between transient rate limits and permanent errors. For detailed configuration options, review the API documentation to see how headers are structured for different model families.

Implementing Exponential Backoff with Jitter

Exponential backoff> Exponential backoff increases the wait time between retry attempts, reducing server load during outages. Adding jitter prevents the "thundering herd" problem, where multiple clients retry simultaneously and overwhelm the endpoint. This combination is essential for stable integration with high-throughput inference APIs.

Without jitter, synchronized retries create traffic spikes that trigger additional rate limits. Jitter introduces randomness to the delay, spreading requests across a time window. This approach improves success rates for transient errors like 429 Too Many Requests or 5xx server errors.

Implementation Steps

  1. Calculate the base delay using an exponential formula: delay = min(max_delay, base_delay * (2 ** attempt)).
  2. Add random jitter: final_delay = delay + random.uniform(0, jitter_range).
  3. Sleep for final_delay seconds before the next request.
  4. Retry only on retriable status codes (429, 500, 502, 503, 504).

A typical configuration uses a base delay of 1 second, a maximum delay of 30 seconds, and a jitter range of 0–1 second. This keeps retries aggressive initially but caps them to avoid long queues.

import time
import random

def retry_with_backoff(func, max_retries=5):
    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            delay = min(30, 1 * (2 ** attempt))
            jitter = random.uniform(0, 1)
            time.sleep(delay + jitter)

FastInfra’s OpenAI-compatible API handles concurrent requests efficiently, but proper retry logic ensures you stay within fair usage guidelines. Incorrect retry patterns can lead to unnecessary costs and degraded performance. Review the API documentation for specific error codes and recommended retry intervals.

Managing Concurrency Limits Effectively

Uncontrolled concurrency causes request collisions that trigger 429 Too Many Requests errors. Hard limits exist on API keys and specific model endpoints to protect infrastructure stability. You must enforce client-side caps before sending traffic to the server.

Implement a semaphore or token bucket pattern to restrict active requests. This approach prevents burst spikes from overwhelming the rate limiter. Set the maximum concurrent connections slightly below the documented limit to account for network latency and processing variance.

  • Define a strict maximum number of parallel requests per API key.
  • Queue excess requests locally instead of dropping them immediately.
  • Monitor active connection counts to detect leaks or stuck requests.

For high-throughput applications, use an async queue with a bounded concurrency limit. This ensures that only a fixed number of tasks execute simultaneously. The queue holds remaining tasks until a slot opens.

import asyncio
from asyncio import Semaphore

sem = Semaphore(10)

async def controlled_request(payload):
    async with sem:
        # Send request to FastInfra API
        response = await client.chat.completions.create(**payload)
    return response

Adjust the semaphore size based on your specific workload. Chat completion endpoints may require lower concurrency due to higher latency, while embedding endpoints can handle higher parallelism. Test your configuration under load to find the optimal balance between throughput and error rates.

FastInfra provides automatic routing across 723 models, which can help distribute load. However, client-side control remains essential for predictable performance. Review your current setup at /docs to ensure your integration handles concurrency correctly.

Request Queuing for Burst Traffic

Burst traffic overwhelms inference endpoints when concurrent requests exceed the provider’s rate limits. Queuing absorbs the spike, holding requests in memory until the system can process them within safe thresholds. This approach prevents immediate 429 errors and smooths the request flow. Implement a bounded queue with a maximum size to protect against memory exhaustion. Define a processing loop that drains the queue at a fixed rate, measured in requests per second (RPS). Use a semaphore or token bucket to control concurrency, ensuring the outbound stream never exceeds the limit.
  1. Initialize a queue with a defined capacity.
  2. Submit incoming requests to the queue, rejecting or delaying if full.
  3. Run a worker thread that pulls items and sends them to the API.
  4. Enforce a delay between sends to match the allowed RPS.
The worker should handle failures by retrying individual items without blocking the entire queue. This isolation prevents a single failed request from stalling the pipeline.
async def process_queue(queue, client, max_rps):
    while not queue.empty():
        prompt = await queue.get()
        response = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": prompt}]
        )
        await asyncio.sleep(1.0 / max_rps)
FastInfra’s API handles high throughput automatically, but client-side queuing remains necessary when you aggregate traffic from multiple sources or use strict concurrency controls. The platform routes requests to the lowest-cost models, reducing the financial impact of retries caused by rate limits. You can view current model availability and pricing on the pricing page. Monitor queue depth and latency to detect bottlenecks. If the queue consistently fills, increase the concurrency limit or scale your infrastructure. For sustained high-volume workloads, consider using GPU Cloud pods to host your own inference service, bypassing shared API limits entirely.

Circuit Breaker Pattern for Failures

Retrying failed requests indefinitely consumes thread pools, exhausts connection limits, and increases latency for healthy users. A circuit breaker stops this cycle by tracking failure rates and switching to a fail-fast state when errors exceed a defined threshold. This pattern protects your application from cascading failures caused by upstream instability or temporary outages or sustained high load. Implement the circuit breaker with three distinct states:
  • Closed: Requests flow normally. The breaker counts consecutive failures or calculates an error rate over a time window.
  • Open: Requests fail immediately without hitting the API. This preserves your application’s resources and gives the upstream service time to recover. The breaker waits for a cooldown period before allowing a test request.
  • Half-Open: A limited number of requests are allowed through. If they succeed, the circuit closes. If they fail, it reopens.
Configure thresholds based on your tolerance for latency versus availability. For latency-sensitive applications, set a low failure count (e.g., 5 consecutive errors) to trip the breaker quickly. For batch processing jobs, you might tolerate a higher error rate before opening the circuit. Here is a conceptual implementation of the retry logic with a circuit breaker:
if circuit_breaker.is_open():
    raise CircuitOpenError("Service unavailable")

try:
    response = client.chat.completions.create(...)
    circuit_breaker.record_success()
except APIError as e:
    circuit_breaker.record_failure()
    if not circuit_breaker.is_open():
        raise RetryableError(e)
    raise CircuitOpenError("Service unavailable")
Integrate this pattern with your retry logic. Do not retry requests when the circuit is open. Instead, return a clear error to the user or queue the request for later processing. This approach prevents your application from wasting resources on requests that are likely to fail. When using FastInfra, the automatic routing across 723 models often provides inherent redundancy. However, specific model endpoints or GPU clusters can still experience transient issues. A circuit breaker ensures your application remains responsive even when a specific inference path is degraded. See the API documentation for error codes and status details.

Error Handling Patterns for Transients

Transient errors fall into three distinct categories: network timeouts, server-side failures, and explicit rate limits. Treating them identically wastes resources and degrades user experience. Your error handler must inspect the HTTP status code and response headers to determine the correct recovery path.

Network timeouts (often HTTP 408 or socket errors) indicate the client failed to send or receive data within the expected window. These require immediate retries with exponential backoff, as the server state is likely unchanged. Server errors (HTTP 5xx) suggest backend instability. Retry these, but cap the attempts to avoid amplifying load on a failing service.

Rate limits (HTTP 429) are contractual constraints. Retrying immediately violates the limit and triggers further blocks. You must parse the `Retry-After` header if present, or apply a calculated delay based on your observed quota consumption. FastInfra routes requests to the lowest-cost available model among its 723 options, but every retry consumes tokens and incurs cost.

Implement a structured error classification in your catch block. This logic ensures that only retryable errors trigger the backoff mechanism, while client errors (4xx, excluding 429) fail fast.

try {
  response = await client.chat.completions.create(...);
} catch (error) {
  if (error.status === 429) {
    const retryAfter = error.headers['retry-after'] || 5;
    await sleep(retryAfter * 1000);
    retry();
  } else if (error.status >= 500 || isTimeout(error)) {
    await exponentialBackoff();
    retry();
  } else {
    throw error; // Fail fast for 400, 401, 403, etc.
  }
}

For production systems, log the error category separately. This data reveals whether your issues stem from infrastructure instability or quota exhaustion. Review the API documentation for specific error codes returned by the inference layer. Proper classification reduces wasted compute and stabilizes latency for end-users.

Routing and Cost Impact of Retries

Retries directly increase inference costs because every failed attempt consumes tokens before the client receives an error or timeout. On FastInfra, you pay per token regardless of whether the request succeeds or fails. With median input pricing at 0.2794 and output pricing at 0.918, uncontrolled retry loops can multiply expenses quickly. A single request retried three times costs four times the original amount, even if the final response is never used by your application.

Automatic routing mitigates specific model outages by shifting traffic away from overloaded or failing endpoints. When a provider returns a rate limit error, the system attempts the request on an alternative model with compatible performance characteristics. This reduces the need for client-side retries that consume tokens on the original endpoint. The routing logic evaluates availability and latency in real time, ensuring that only successful completions are billed at the optimal rate.

Implementing smart retry logic requires distinguishing between transient errors and permanent failures. Use exponential backoff for rate limit responses (HTTP 429) to avoid overwhelming the API during congestion. Avoid retrying on validation errors (HTTP 400) or authentication failures, as these will not succeed on subsequent attempts. Here is a basic pattern for handling rate limits:

if response.status == 429:
    wait_time = min(base_delay * (2 ** attempt), max_delay)
    time.sleep(wait_time + random_jitter())
    return retry_request()

Monitor your retry rates to identify systemic issues. High retry percentages often indicate that your concurrency limits exceed what the backend can handle. Adjust your queue sizes or implement circuit breakers to stop sending requests to failing endpoints. For detailed pricing structures and cost optimization strategies, review the pricing page. Properly configured retries protect your budget while maintaining availability during peak load periods.

Monitoring Retry Metrics in Production

Tracking retry behavior is essential for maintaining operational health and controlling costs. Without visibility into why requests are retried, teams cannot distinguish between transient network issues and systemic capacity constraints. You need to measure both the volume of retries and their success rate to identify bottlenecks early.

Focus on these four core metrics to maintain a clear view of your inference pipeline:

  • Retry Rate: The percentage of total requests that require at least one retry. A sustained rate above 5% usually indicates a configuration issue or upstream instability.
  • Retry Success Ratio: The proportion of retried requests that eventually succeed. If this drops, your backoff strategy may be too aggressive or the service may be degraded.
  • Average Latency with Retries: The end-to-end time including all retry attempts. This metric reveals the true cost of resilience on user experience.
  • Cost per Successful Token: Retries increase token consumption. Track the delta between input tokens sent and output tokens received to quantify waste.

Instrument your client library to emit these metrics to your observability stack. For example, log the HTTP status code and retry count for every request. When using FastInfra, you can monitor traffic patterns across the 723 available models to detect if specific models are triggering higher retry rates due to routing changes or load spikes.

metrics.increment('api_retries_total', 1, {
  model: response.model,
  status_code: response.status_code
});

High retry rates directly impact your bottom line because you pay for every token processed, even if the final response is discarded. By monitoring these metrics, you can adjust your concurrency limits or switch to more stable routing paths. Review your usage patterns on the /pricing page to understand how retry overhead affects your per-token billing.

Comparing Retry Strategies by Use Case

Retry strategies must align with the latency tolerance of the specific workload. A background batch job can afford aggressive retries, while a real-time chat interface requires immediate feedback or graceful degradation.
Retry Strategy Selection by Use Case
Use Case Latency Budget Retry Strategy Concurrency Control Failure Action
Real-time Chat < 500ms Single attempt Fixed limit Show loading state
Search Summarization 2-5 seconds Exponential backoff (2 retries) Token bucket Partial result
Background Analysis Minutes Aggressive backoff Queue depth Retry indefinitely
Batch Processing Hours Checkpoint and resume Parallel workers Log and skip
For latency-sensitive applications, implement a circuit breaker that opens after a threshold of failures. This prevents cascading delays when the upstream API is degraded.
if (circuit.isOpen()) {
  return fallbackResponse();
}
try {
  return await api.call(prompt);
} catch (err) {
  circuit.recordFailure();
  throw err;
}
Cost impact varies by model tier. Retries on expensive models increase spend linearly. Use the cheapest available model for initial attempts if accuracy allows, then escalate. See
The 10 cheapest paid chat models on FastInfra by combined input and output price (USD per 1M tokens)
ModelInput $/1MOutput $/1MRoutes
Solar Mini 4.5
upstage/solar-mini-4-5
$0.0108$0.04321
Mistral Nemo
mistralai/mistral-nemo
$0.0313$0.03241
L3 Lunaris 8B
sao10k/l3-lunaris-8b
$0.04$0.051
Ling 3.0 Flash
inclusionai/ling-3.0-flash
$0.0227$0.0681
Llama 3.2 3B Instruct
meta-llama/llama-3.2-3b-instruct
$0.0648$0.06482
Mistral Small 24B Instruct 2501
mistralai/mistral-small-24b-instruct-2501
$0.054$0.08642
Command R7B 12.2024
cohere/command-r7b-12-2024
$0.0375$0.151
Nova Micro V1
amazon/nova-micro-v1
$0.0378$0.15121
Schematron V2 Turbo
inference-net/schematron-v2-turbo
$0.0324$0.1621
Trinity Mini
arcee-ai/trinity-mini
$0.0486$0.1621
for current options. Monitor retry rates per endpoint. High retry ratios indicate either poor network conditions or misconfigured concurrency limits. Adjust your token bucket settings in the FastInfra docs to match your traffic patterns. Passive retries (waiting for timeouts) waste compute resources. Active retries with immediate error detection reduce total latency. Always prefer active failure detection over passive timeouts in production systems.

Related FastInfra resources

Frequently asked questions

How do I handle 503 errors differently from 429s?

Treat 503 Service Unavailable as a transient error similar to 429s. Use exponential backoff, but consider a circuit breaker if 503s persist, as it may indicate a broader infrastructure outage rather than just rate limiting.

Should I retry on 400 Bad Request errors?

No. 400 errors indicate client-side issues like malformed JSON or invalid parameters. Retrying will produce the same error. Log the specific validation message and fix the input data before resending.

What is the ideal initial delay for backoff?

Start with a short delay, such as 100-500 milliseconds. This allows for quick recovery from brief network glitches without adding significant latency to the user experience. Increase the delay exponentially for subsequent retries.

How does automatic routing affect rate limits?

Automatic routing distributes load across multiple models and providers. This reduces the likelihood of hitting a single provider's rate limit, but your application must still handle global rate limits or specific model restrictions.

Can I disable retries for streaming responses?

It is complex. Streaming responses cannot be easily retried mid-stream. It is better to prevent rate limits via concurrency control. If a stream fails, you may need to restart the entire request with a new ID.

Last reviewed November 11, 2026 by FastInfra. Prices and counts on this page are refreshed from the live catalog on every load.