cd /news/ai-tools/how-to-make-your-python-api-and-llm-… · home › topics › ai-tools › article
[ARTICLE · art-182848] src=pub.towardsai.net ↗ pub= topic=ai-tools verified=true sentiment=· neutral

How to Make Your Python API and Llm Calls Survive Failure

A developer guide published on the pyresilience project's GitHub repository shows how to wrap Python API and LLM calls in a single resilience pipeline — retry, timeout, circuit breaker, fallback, cache and rate limiting — using the open-source pyresilience library, version 0.5.0 or later, which relies only on the Python standard library. The author, who maintains the library and discloses the bias, argues a plain three-attempt retry loop fails in three ways: it has no time limit, keeps hammering a downed API, and ignores LLM providers' per-minute request and token limits. The guide's example configuration retries up to 3 times with a 1.0-second delay, caps each attempt at 10 seconds and the whole call at 30 seconds, and opens a circuit breaker after 5 consecutive failures for a 30-second recovery window.

recommendation

Wrap outbound API and LLM calls in a single ordered pipeline with retry, per-attempt and total timeouts, and a circuit breaker that opens after 5 failures for 30 seconds, so retries never hit a known-down service.

more in playbook: Running AI in production
by read6 min views1 publishedDec 6, 2026

Your code calls things you don’t control. An API. A database. An LLM. Most days they answer. Some days they’re slow, or down, or they tell you to slow down.

Here’s a common story. A job runs fine for a week. Then one night the model API answers “429 Too Many Requests,” and the whole run fails at row 8,000 of 10,000.

This guide shows how to make such calls survive. It covers what a safe call looks like, why a plain retry loop isn’t enough, and how to build the fix step by step in Python. The examples use pyresilience, an open-source library I created and maintain, so treat my choice of tool as biased. The ideas work with any tool. I used an AI assistant to fix the grammer and make the diagrams.

A safe call has a plan for bad days. There are seven well-known plans. The names sound technical, but each idea fits in one line:

You don’t need all seven everywhere. A good start is a retry, a timeout, and a circuit breaker on every call that leaves your process.

So why not write these yourself?

Most of us start with something like this:

import time def call_with_retry():    for attempt in range(3):        try:            return call_api()        except Exception:            time.sleep(1)

It looks fine. It has three problems.

First, it has no time limit. If the API hangs, your code hangs with it.

Second, it doesn’t know when to stop. When the API is down for ten minutes, every worker keeps knocking, three times per request. That extra load can keep the API from coming back.

Third, it knows nothing about limits. LLM providers count your requests and your tokens per minute. A loop that retries blindly runs into the same limit again and again.

You can fix each problem with its own tool. Many teams use tenacity for retries, pybreaker for circuit breakers, and their own code for the rest. Then a new problem shows up: the parts don't know about each other. If the circuit breaker is open, should the retry still run? If the answer comes from the cache, should it count against your rate limit?

That’s why I prefer one tool that sends every call through the same steps, in the same order.

If the cache has the answer, nothing else runs. If the circuit breaker is open, the call is turned away before it uses any of your rate limit. The breaker is also checked again before every retry, so retries never keep hitting a service that’s known to be down.

Now let’s build it.

Install the library first. It uses only the Python standard library, so it pulls in no other packages. The examples need version 0.5.0 or later.

pip install pyresilience

Put the @resilient decorator on the function that makes the call.

import requestsfrom pyresilience import resilient, RetryConfig, TimeoutConfig @resilient(    retry=RetryConfig(max_attempts=3, delay=1.0),    timeout=TimeoutConfig(seconds=10, total_seconds=30),)def call_api(endpoint: str) -> dict:    return requests.get(endpoint).json()

Read it from top to bottom. Try up to three times, and wait longer after each failure. Give each try ten seconds, and the whole call 30 seconds. If there isn’t enough time left for the next wait, the call stops at once.

The same decorator works on async functions. Nothing else changes.

Add a circuit breaker, and a fallback for the time it’s open.

import requestsfrom pyresilience import (    resilient, RetryConfig, CircuitBreakerConfig, FallbackConfig,) @resilient(    retry=RetryConfig(max_attempts=3, delay=1.0),    circuit_breaker=CircuitBreakerConfig(        failure_threshold=5, recovery_timeout=30    ),    fallback=FallbackConfig(handler=lambda e: {"status": "degraded"}),)def get_prices() -> dict:    return requests.get("https://api.example.com/prices").json()

After five failures in a row, the breaker opens. For the next 30 seconds, calls don’t reach the API at all. They return the backup answer right away. After that, a few test calls are let through. When two in a row succeed, the breaker closes and normal work continues.

LLM providers count two things at once: requests per minute and tokens per minute. The llm_policy preset holds both limits together.

from pyresilience import resilient, llm_policy @resilient(**llm_policy(    max_calls=60,                # requests per minute    tokens_per_minute=90_000,    # tokens per minute    # a guess before the call, and the real number after it    token_cost=lambda prompt: len(prompt) // 4 + 256,    token_usage=lambda reply: reply.usage.total_tokens,    adaptive_rate_limit=True,    # follow the server's headers))def complete(prompt: str):    return llm_client.complete(prompt)

Before the call, it sets aside a guess of the token cost. After the call, it corrects the guess with the real number. With adaptive_rate_limit, it also reads the rate-limit headers in the provider's reply and slows down when the server asks. A 429 reply is retried after the wait the server names.

A fallback can be a list of other functions that take the same input. If your main model is down, the same prompt goes to the backup model.

from pyresilience import resilient, FallbackConfig @resilient(fallback=FallbackConfig(    alternatives=[ask_backup_model, ask_small_model],    handler="No model available right now.",    cooldown=30.0,            # skip a failing provider for 30s    cooldown_threshold=3,     # after 3 failures in a row))def ask(prompt: str) -> str:    return primary_client.complete(prompt)

A provider that keeps failing is skipped for a short time, so you don’t waste a try on it.

This one is easy to miss. By default, each process keeps its own count. Say you set a limit of 100 calls per minute and run five copies of your service. Each copy allows 100, so the API gets up to 500. A circuit breaker has the same problem. Set to open after five failures, it really takes 25.

The fix is shared state. All copies use one count, kept in a store like Redis.

import redisfrom redis.backoff import NoBackofffrom redis.retry import Retryfrom pyresilience import (    resilient, CircuitBreakerConfig, RateLimiterConfig, SharedStateConfig,)from pyresilience.contrib.redis import RedisBackend # Rate-limited calls wait for this client:# short timeouts, no retries of its ownclient = redis.Redis(    socket_connect_timeout=0.5,    socket_timeout=0.5,    retry=Retry(NoBackoff(), 0),) @resilient(    circuit_breaker=CircuitBreakerConfig(failure_threshold=5),    rate_limiter=RateLimiterConfig(max_calls=100, period=60.0),    shared_state=SharedStateConfig(        backend=RedisBackend(client), key="payment-api"    ),)def charge(amount: float) -> dict: ...

Rate limits are counted in the store on every call. The circuit breaker syncs in the background, so it adds no waiting to your calls.

Failures you can’t see are the worst kind. Every retry, timeout, and open circuit sends out an event. Add a listener to collect them.

from pyresilience import resilient, RetryConfig, MetricsCollector metrics = MetricsCollector() @resilient(retry=RetryConfig(max_attempts=3), listeners=[metrics])def my_func(): ... print(metrics.summary())   # events and success rate per function

The same events can go to your logs, to OpenTelemetry, or to Prometheus.

A decorator that sits on every call has to be cheap. In the project’s benchmarks, a decorated call takes about 0.64 microseconds. An LLM call usually takes hundreds of milliseconds or more, so you won’t notice the difference.

Calls fail. You can’t change that. What you can change is what happens next: how long you wait, how often you try again, when you stop, and what you return instead.

Start small. Pick one function that calls something you don’t control. Give it a retry, a time limit, and a circuit breaker. Add the rest when you need it.

If you try pyresilience and something is missing, please open an issue on GitHub.

How to Make Your Python API and Llm Calls Survive Failure was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.

── more in #ai-tools 4 stories · sorted by recency
── more on @pyresilience 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-to-make-your-pyt…] indexed:0 read:6min 2026-12-06 · —