
Tenacity is a Python library for retrying an operation under rules you choose. A useful policy answers four questions: which failures can justify another attempt, how long to wait, when to stop, and what the caller receives after the final failure.
This guide builds a bounded retry policy for read-only HTTP requests. A private server deliberately returns two temporary failures before succeeding. You can inspect the request count, repeat the same call asynchronously, and see where retries stop helping. The examples use Tenacity 9.2.1, HTTPX 0.28.1, and Python 3.12.14.
A timeout tells the caller that it did not receive the expected response in time. It does not prove that the remote operation never happened. Retrying a payment, message send, or database write needs an application-level decision about duplicate effects. A retry decorator does not provide that guarantee.
The example issues only GET requests against a disposable loopback server. For a real API, confirm that the selected read can be repeated, identify the failures that might be temporary, and decide what should happen when the request cannot recover. Fixing credentials or malformed input usually requires a different action from repeating an unchanged request.
If you are still choosing the HTTP library, start with HTTPX vs Requests. Here, HTTPX makes the request and Tenacity controls the application-level repetition.
Install the pinned libraries in a dedicated virtual environment:
python -m pip install tenacity==9.2.1 httpx==0.28.1
Save the following as retry_client.py. The policy selects connection errors, connection timeouts, read timeouts, and a custom exception for particular HTTP responses. The Tenacity documentation describes the decorator and its configurable conditions; this example deliberately supplies each one.
import logging
import httpx
from tenacity import retry, retry_if_exception_type, stop_after_attempt, stop_after_delay, wait_random_exponential
log = logging.getLogger("example.retry")
class TemporaryResponse(Exception):
"""An explicitly selected response that this read operation may retry."""
def log_wait(state):
# Do not record the URL, request arguments, headers, or exception message.
log.warning("retry attempt=%d wait_s=%.3f error=%s",
state.attempt_number, state.next_action.sleep,
type(state.outcome.exception()).__name__)
policy = dict(
retry=retry_if_exception_type((TemporaryResponse, httpx.ConnectError,
httpx.ConnectTimeout, httpx.ReadTimeout)),
stop=stop_after_attempt(3) | stop_after_delay(2),
wait=wait_random_exponential(multiplier=0.1, max=0.5),
before_sleep=log_wait,
reraise=True,
)
def decode_response(response):
# Defer Retry-After responses to the caller's scheduling policy.
if response.status_code in {502, 503, 504} and "Retry-After" not in response.headers:
raise TemporaryResponse("Selected temporary HTTP failure")
response.raise_for_status()
return response.json()
@retry(**policy)
def get_json(client, url):
return decode_response(client.get(url))
@retry(**policy)
async def aget_json(client, url):
return decode_response(await client.get(url))
stop_after_attempt(3) permits three total calls, including the first. If the third call still fails with a selected exception, reraise=True raises that exception to the caller. Our exhaustion check received TemporaryResponse, rather than Tenacity's default RetryError wrapper. Exceptions outside the selected group pass through without repetition.
The response policy is deliberately narrow. It selects 502, 503, and 504 only when no Retry-After header is present. A 401, 404, 429, malformed JSON response, or response carrying Retry-After leaves the retry loop. The caller must then handle the failure or schedule later work according to the API's contract. This example does not parse Retry-After or implement a rate-limit scheduler.
Random exponential waiting avoids giving every retry the same scheduled delay. With these settings, the first two waits fall between zero and 0.1 seconds, then zero and 0.2 seconds. The policy's 0.5-second cap is not reached under a three-attempt limit. These short intervals suit the local demonstration; they are not recommended values for every provider.
The second stop condition, stop_after_delay(2), participates in Tenacity's decision to stop retrying. It does not interrupt a call already in progress. Combining it with an attempt limit also does not turn it into a strict two-second deadline.
We checked this distinction with a controlled clock. A failing operation with a 0.05-second stop threshold and fixed 0.04-second waits made its third call at 0.08 seconds. A separate successful operation returned after advancing the clock by ten seconds, despite a two-second retry threshold. These are deterministic policy checks, not measured network response times.
The client below uses timeout=0.5. HTTPX documents separate connect, read, write, and pool timeouts. In particular, a read timeout limits waiting for incoming data; it is not a total deadline for the entire response. Choose transport timeouts, retry limits, and any overall application deadline together. If the caller has already abandoned the work, another attempt may have no value.
Save this as demo_server.py. It starts a private server on an available loopback port and stops that server when the context ends. The counters are test observations; the fixture has no business writes or external dependencies.
"""Disposable loopback GET fixture. No business writes or external services."""
import json
import threading
import time
from collections import Counter
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
@contextmanager
def demo_server():
counts = Counter()
lock = threading.Lock()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
path = urlsplit(self.path).path
with lock:
counts[path] += 1
attempt = counts[path]
status, headers = 200, {}
if path.startswith("/flaky") and attempt < 3:
status = 503
elif path == "/always":
status = 503
elif path == "/missing":
status = 404
elif path == "/unauthorized":
status = 401
elif path == "/limited":
status, headers = 429, {"Retry-After": "10"}
elif path == "/maintenance":
status, headers = 503, {"Retry-After": "10"}
elif path == "/slow":
time.sleep(0.15)
body = b"invalid json" if path == "/invalid" else json.dumps({"attempt": attempt, "ok": status == 200}).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
for key, value in headers.items():
self.send_header(key, value)
self.end_headers()
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
pass # Expected when the timeout test closes its connection.
def log_message(self, *args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True)
thread.start()
try:
yield f"http://127.0.0.1:{server.server_port}", counts
finally:
server.shutdown()
server.server_close()
thread.join(timeout=2)
Save the following as demo.py beside the other two files, then run python demo.py:
import asyncio
import logging
import httpx
from demo_server import demo_server
from retry_client import aget_json, get_json
async def run_async(base):
async with httpx.AsyncClient(timeout=0.5, trust_env=False,
transport=httpx.AsyncHTTPTransport(retries=0)) as client:
return await aget_json(client, base + "/flaky-async")
if __name__ == "__main__":
logging.basicConfig(level=logging.WARNING, format="%(message)s")
with demo_server() as (base, counts):
with httpx.Client(timeout=0.5, trust_env=False,
transport=httpx.HTTPTransport(retries=0)) as client:
print("sync:", get_json(client, base + "/flaky-sync"))
print("async:", asyncio.run(run_async(base)))
print("server request counts:", dict(counts))
Both the synchronous and asynchronous demonstrations should return {'attempt': 3, 'ok': True}. Each has its own fixture path, so each encounters two 503 responses before succeeding. The printed server counts let you distinguish three total attempts from three retries after an initial call. The waits vary between runs.
The clients reuse one connection pool for the entire logical operation and close it when their context ends. They explicitly disable HTTP transport retries, leaving one visible retry layer in this demonstration. The code does not stream responses or retry part of a partially consumed stream.
The asynchronous function uses the same policy and awaits HTTPX. Our tests canceled it both during a pending request and during a retry wait. Cancellation propagated, no additional request followed, and the client's context closed. Keep cancellation out of the retryable exception set and allow cleanup to run.
Python's task-cancellation documentation explains cancellation and cleanup. For a broader example of bounded concurrent work, see our Python asyncio guide. Adding async support does not make an unlimited number of concurrent retry loops affordable.
The retry callback logs the failed attempt number, the planned wait, and the exception's class name. It leaves out the URL, arguments, headers, and exception message. Synthetic secrets in a query string and exception message stayed out of this logger's output during the checks. That result does not establish redaction across HTTPX, application logs, or a monitoring system.
A before-sleep message records a planned retry, not final success or exhaustion. Record the logical operation's final outcome at the calling layer, with a safe correlation identifier. Our Python logging guide covers handlers, structured fields, and exception reporting.
On November 19, 2026, 33 checks passed on Windows. Real loopback HTTP requests established response counts, recovery, selected permanent failures, read timeouts, and actual waiting. Separate simulated transports and controlled-clock checks isolated exception selection, cancellation, jitter bounds, and stopping semantics.
| Case | Observed result |
|---|---|
| Two temporary 503 responses, then success | Three calls; two waits; both sync and async examples succeed |
| Selected failure on every attempt | Three calls; original TemporaryResponse raised |
| 401, 404, 429, and a 503 carrying Retry-After | One call each; HTTPStatusError reaches the caller |
| Invalid JSON | One call; parsing error reaches the caller |
| Real delayed local response | Three calls; final ReadTimeout |
| Retry logs with synthetic query/error secrets | Secrets absent from the policy logger |
| Controlled-clock stopping checks | Waits can pass a time threshold; an in-flight success is not interrupted |
| Cancellation during an async call or wait | Cancellation propagated; no next request; client closed |
The Tenacity API reference provides the policy hooks used by the test runner to substitute deterministic waits. Those substitutions do not measure network behavior. The checks used no paid API, external write, cloud deployment, or capacity benchmark. The connection-error cases were simulated; the read-timeout case used a real delayed local response.
Before applying this policy to an SDK or service, check whether another layer already retries. HTTPX exposes transport-level connection retries; an SDK, reverse proxy, or routing service can add its own attempts. Three application attempts, each permitted three downstream attempts, can produce nine downstream calls in the worst case.
Choose which layer owns which failure, then account for the combined time and request budget. For model-serving systems, our LLM fallback and retries guide covers a separate routing decision. Tenacity does not configure Hivenet Router, choose an alternate model, or make repeated writes safe.
Once the calling application behaves as intended, use the API-hosting guide to compare operating responsibilities. CPU instances with Hivenet can host your integration service or background worker. You manage its dependencies, process supervision, retry policy, and monitoring. Size it from the workload's measured behavior, including the extra work created during failures.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.