Wrap an HTTP API call with retry logic that automatically retries up to 5 times with exponential backoff when a connection error occurs.
Retry a database query that fails due to transient connection issues, with a fixed 2-second wait between attempts.
Retry a function only on specific exception types while immediately re-raising other errors, avoiding retries on validation failures.
Add logging to a retry loop so each failed attempt writes the attempt number and elapsed time to a log file.
Tenacity is a Python library that makes it easy to add retry logic to any function. When you call an external service, database, or API, requests sometimes fail due to network hiccups or temporary server problems. Rather than writing your own loop with sleep and error handling, you add the @retry decorator to your function and Tenacity handles the retrying automatically. The basic use is a one-liner: add @retry above the function and it will retry forever whenever an exception is raised. From there, you can tune the behavior. You can stop after a specific number of attempts, stop after a total elapsed time, or combine both conditions with the | operator. You can control how long to wait between attempts: a fixed delay, a random delay within a range, or exponential backoff, where each wait is longer than the last. Exponential backoff with random jitter is a common pattern for calling distributed services because it reduces the chance that many clients all retry at exactly the same time. You can also control which situations trigger a retry. By default, any exception restarts the call. But you can tell Tenacity to only retry on specific exception types, skip retries on certain errors like client-side validation failures, or even retry when a function returns a result you do not want, such as None or False. For logging and monitoring, Tenacity accepts callback functions that run before each attempt, after each failed attempt, or before each sleep period. These callbacks receive a retry_state object with details like the attempt number and elapsed time. Tenacity works with async functions on asyncio, Trio, and Tornado, and supports retrying a code block using a for loop and context manager instead of a decorator. It is Apache 2.0 licensed.
← jd on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.