openapi-python-sdk
openapi-python-sdk copied to clipboard
feat: implement built-in retry mechanism with exponential backoff and jitter
Ref issue #20
This PR resolves the lack of a built-in retry mechanism in the SDK client and OAuth client interfaces. Previously, any temporary network dropout, gateway timeout (502/503/504), or rate limit hit (429) would cause immediate request failures and require custom retry handling in the consumer's application.
This change introduces a robust, configurable retry mechanism using exponential backoff and randomized jitter to retry failed requests automatically.
The Problem
- Low-level HTTP primitives (via
httpx) had no automatic retry loop. - Transient exceptions (like connection dropouts or request timeouts) crashed consumer applications instantly.
- Rate-limiting (HTTP 429) was not handled automatically, ignoring
Retry-Afterheaders.
The Solution
I implemented an optional, fully backward-compatible retry mechanism across all client classes:
- Added Retry Parameters to:
ClientAsyncClientOauthClientAsyncOauthClient- Parameters:
max_retries(defaults to0for backward compatibility),backoff_factor, andretry_on_status.
- Created Retry Loops:
_request_with_retrymethod (both sync and async versions) executes the network calls.- Retries trigger on connection/timeout errors (
httpx.RequestError) and configured status codes (defaults to[429, 502, 503, 504]). - If an HTTP 429 response contains a
Retry-Afterheader, the wait time is dynamically overridden to respect the header.
- Randomized Jitter: Added random noise to backoff calculations to avoid thundering herd issues on the Openapi gateway.
Key File Changes
openapi_python_sdk/client.py: Updates to synchronousClientwith sync retry loop.openapi_python_sdk/async_client.py: Updates to asynchronousAsyncClientusingasyncio.sleepretry loop.openapi_python_sdk/oauth_client.py: Updates to syncOauthClientwrapping credentials and token operations.openapi_python_sdk/async_oauth_client.py: Updates to asyncAsyncOauthClientwrapping credentials and token operations.tests/test_retry.py(New): Full unit test coverage for sync retries (testing backoff delays, rate-limit headers, and failures).tests/test_async_retry.py(New): Full unit test coverage for async retries.
How I tested it
- Unit Tests:
- Ran
poetry run pytestand verified all 35 tests passed successfully (including existing mocks).
- Ran
- Linter Check:
- Ran
poetry run ruff check .to verify code format styling.
- Ran
- Integration Verification:
- Tested live connections against
httpbin.orgtesting endpoints to verify that the client retries over multiple attempts and waits exponentially.
- Tested live connections against