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. 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 https://github.com/AhsanSheraz/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: python 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. python 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. python 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. python 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. python 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. python 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. python 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 https://github.com/AhsanSheraz/pyresilience/tree/main/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 https://github.com/AhsanSheraz/pyresilience . How to Make Your Python API and Llm Calls Survive Failure https://pub.towardsai.net/how-to-make-your-python-api-and-llm-calls-survive-failure-b1706c3b88a7 was originally published in Towards AI https://pub.towardsai.net on Medium, where people are continuing the conversation by highlighting and responding to this story.