{"slug": "how-to-make-your-python-api-and-llm-calls-survive-failure", "title": "How to Make Your Python API and Llm Calls Survive Failure", "summary": "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.", "body_md": "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.\n\nHere’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.\n\nThis 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.\n\nA 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:\n\nYou 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.\n\nSo why not write these yourself?\n\nMost of us start with something like this:\n\n``` python\nimport time def call_with_retry():    for attempt in range(3):        try:            return call_api()        except Exception:            time.sleep(1)\n```\n\nIt looks fine. It has three problems.\n\nFirst, it has no time limit. If the API hangs, your code hangs with it.\n\nSecond, 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.\n\nThird, 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.\n\nYou 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?\n\nThat’s why I prefer one tool that sends every call through the same steps, in the same order.\n\nIf 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.\n\nNow let’s build it.\n\nInstall 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.\n\n```\npip install pyresilience\n```\n\nPut the @resilient decorator on the function that makes the call.\n\n``` python\nimport 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()\n```\n\nRead 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.\n\nThe same decorator works on async functions. Nothing else changes.\n\nAdd a circuit breaker, and a fallback for the time it’s open.\n\n``` python\nimport 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()\n```\n\nAfter 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.\n\nLLM providers count two things at once: requests per minute and tokens per minute. The llm_policy preset holds both limits together.\n\n``` python\nfrom 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)\n```\n\nBefore 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.\n\nA 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.\n\n``` python\nfrom 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)\n```\n\nA provider that keeps failing is skipped for a short time, so you don’t waste a try on it.\n\nThis 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.\n\nThe fix is shared state. All copies use one count, kept in a store like Redis.\n\n``` python\nimport 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: ...\n```\n\nRate limits are counted in the store on every call. The circuit breaker syncs in the background, so it adds no waiting to your calls.\n\nFailures you can’t see are the worst kind. Every retry, timeout, and open circuit sends out an event. Add a listener to collect them.\n\n``` python\nfrom 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\n```\n\nThe same events can go to your logs, to OpenTelemetry, or to Prometheus.\n\nA 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.\n\nCalls 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.\n\nStart 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.\n\nIf you try pyresilience and something is missing, please open an issue on [GitHub](https://github.com/AhsanSheraz/pyresilience).\n\n[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.", "url": "https://wpnews.pro/news/how-to-make-your-python-api-and-llm-calls-survive-failure", "canonical_source": "https://pub.towardsai.net/how-to-make-your-python-api-and-llm-calls-survive-failure-b1706c3b88a7?source=rss----98111c9905da---4", "published_at": "2026-12-06 10:48:12+00:00", "updated_at": "2026-12-06 11:14:06.260154+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "large-language-models"], "entities": ["pyresilience", "Python", "AhsanSheraz", "tenacity", "pybreaker"], "also_reported_by": [], "takeaway": "Route every outbound API or LLM call through one ordered pipeline — cache, then circuit breaker, then rate limit, then retry with timeout — so an open breaker rejects calls before they consume rate limit and is re-checked before each retry; the guide's example uses 3 attempts, a 10-second per-attemp", "recommendation": {"advice": "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.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/how-to-make-your-python-api-and-llm-calls-survive-failure", "markdown": "https://wpnews.pro/news/how-to-make-your-python-api-and-llm-calls-survive-failure.md", "text": "https://wpnews.pro/news/how-to-make-your-python-api-and-llm-calls-survive-failure.txt", "jsonld": "https://wpnews.pro/news/how-to-make-your-python-api-and-llm-calls-survive-failure.jsonld"}}