Skip to main content

A production-grade, asynchronous HTTP client for Python engineered to tolerate downstream service outages, network instability, and latency spikes.

Project description

๐Ÿ›ก๏ธ Resilient HTTP Client

CI Status PyPI Version Supported Python Versions License Uv

A production-grade, asynchronous HTTP client for Python engineered to tolerate downstream service outages, network instability, and latency spikes. It implements proven resilience patterns including Circuit Breakers, Retry Policies, Fallback Mechanisms, and a Distributed Failure Store to enable reliable service-to-service communication.

Built on top of httpx, the library is designed for modern distributed systems where resilience is a first-class requirement.


๐Ÿš€ Features

  • Circuit Breaker Pattern โ€” Prevents cascading failures using a strict state machine (CLOSED, OPEN, HALF-OPEN).
  • Distributed Failure Store โ€” Share circuit state and failure metrics across workers and service instances.
  • Automatic Retries โ€” Configurable retry budgets with exponential backoff for transient failures.
  • Graceful Fallbacks โ€” Return degraded responses or execute alternative logic instead of surfacing raw exceptions.
  • Fully Asynchronous โ€” Built on httpx for high-concurrency, non-blocking I/O.
  • Pluggable Components โ€” Storage and resilience behavior can be customized to fit different deployment environments.
  • Production Ready โ€” Suitable for microservices, containerized workloads, and distributed deployments.

๐Ÿ“ System Architecture

The coordination of request delivery, state checking, retries, and fallback execution is modeled in our system architecture.

๐Ÿ“Š View System Architecture Diagram ๐Ÿ•’ View Request Sequence Flow Diagram


๐Ÿ”„ Circuit Breaker State Machine

The client implements a fully compliant circuit breaker state machine with lazy cooldown transitions and probe request gating.

๐Ÿ”„ View Circuit Breaker State Machine Diagram

State Behavior

CLOSED

Requests flow normally.

  • Successful requests reset failure counters.
  • Consecutive failures are tracked.
  • Reaching the configured threshold transitions the circuit to OPEN.

OPEN

Requests fail immediately without contacting the downstream service.

  • Prevents latency amplification and resource exhaustion.
  • Remains open for the configured cooldown period.
  • Automatically transitions to HALF-OPEN after cooldown expires.

HALF-OPEN

Allows a limited number of probe requests.

  • Successful probes close the circuit.
  • Any failed probe immediately reopens the circuit.
  • Prevents unstable services from causing repeated outages.

โš™๏ธ Installation

Install the package via pip or your favorite package manager:

pip install ad-tech-inc-resilient-http

Or using uv:

uv add ad-tech-inc-resilient-http

โšก Quick Start

import asyncio
import redis.asyncio as redis

from resilient_http_client import (
    FailureStore,
    ResilientHttpClient,
)

async def main():
    # Example using Redis-backed storage
    redis_client = redis.Redis(
        host="localhost",
        port=6379,
        decode_responses=True,
    )

    store = FailureStore(
        redis=redis_client,
        service="stripe_payment",
    )

    async with ResilientHttpClient(
        service="stripe_payment",
        store=store,
    ) as client:

        response = await client.request(
            method="POST",
            url="https://api.stripe.com/v1/charges",
            json={
                "amount": 2000,
                "currency": "usd",
            },
        )

        print(response)

if __name__ == "__main__":
    asyncio.run(main())

โš™๏ธ Configuration

Customize resilience behavior through ResilienceConfig.

from resilient_http_client import ResilienceConfig

config = ResilienceConfig(
    failure_threshold=5,
    cooldown=30,
    max_retries=3,
    timeout=5.0,
    half_open_max_calls=1,
    half_open_successes_needed=1,
)

client = ResilientHttpClient(
    service="my-api",
    store=store,
    config=config,
)

Configuration Reference

Parameter Type Default Description
failure_threshold int 5 Consecutive failures required to open the circuit
cooldown int 30 Seconds before an open circuit transitions to half-open
max_retries int 3 Number of retry attempts before failure
timeout float 5.0 Request timeout in seconds
half_open_max_calls int 1 Maximum probe requests allowed while half-open
half_open_successes_needed int 1 Successful probes required to close the circuit

๐Ÿงฉ Components

Circuit Breaker

Prevents repeated requests to unhealthy downstream services.

States:

  • Closed โ€” Requests flow normally.
  • Open โ€” Requests fail immediately.
  • Half-Open โ€” Limited recovery probes are allowed.

Retry Policy

Automatically retries transient failures using configurable exponential backoff.

Typical retry conditions include:

  • HTTP 5xx responses
  • Connection failures
  • Network timeouts

Fallback Handler

Fallbacks are executed when:

  • The circuit is open.
  • Retry attempts are exhausted.
  • A non-retryable failure occurs.

Failure Store

Persists resilience state used by the circuit breaker.

Responsibilities include:

  • Failure counters
  • Circuit state
  • Cooldown timestamps
  • Cross-worker coordination

The library includes a Redis-backed implementation and can be extended with custom storage backends.


๐Ÿ› ๏ธ Project Structure

src/
โ””โ”€โ”€ resilient_http_client/
    โ”œโ”€โ”€ __init__.py
    โ”œโ”€โ”€ client.py
    โ”œโ”€โ”€ circuit_breaker.py
    โ”œโ”€โ”€ config.py
    โ”œโ”€โ”€ failure_store.py
    โ”œโ”€โ”€ fallback.py
    โ”œโ”€โ”€ http.py
    โ”œโ”€โ”€ retry.py
    โ””โ”€โ”€ types.py

tests/
โ”œโ”€โ”€ test_circuit_breaker.py
โ”œโ”€โ”€ test_failure_store.py
โ”œโ”€โ”€ test_fallback.py
โ”œโ”€โ”€ test_flaky_resilience.py
โ”œโ”€โ”€ test_integration.py
โ””โ”€โ”€ test_retry_policy.py

Module Overview

  • ๐Ÿ›ฐ๏ธ client.py โ€” Main orchestration layer.
  • ๐Ÿ”Œ circuit_breaker.py โ€” Circuit breaker state machine.
  • ๐Ÿ—„๏ธ failure_store.py โ€” Distributed state management.
  • ๐Ÿ” retry.py โ€” Retry policy implementation.
  • ๐ŸŽญ fallback.py โ€” Fallback registration and execution.
  • โš™๏ธ config.py โ€” Configuration definitions.
  • ๐Ÿ“˜ types.py โ€” Shared enums and type definitions.
  • ๐ŸŒ http.py โ€” HTTP request execution layer.

๐Ÿงช Running the Tests

Run the full test suite:

uv run pytest

Coverage Includes

  • Failure tracking
  • Circuit opening thresholds
  • Cooldown transitions
  • Half-open probe gating
  • Recovery behavior
  • Retry policies
  • Distributed state persistence
  • Fallback execution paths

๐Ÿ“š Examples

The examples/ directory contains complete demonstrations and integrations.

How to run examples

  1. Start Redis:

    docker compose up -d
    
  2. Run the example:

    PYTHONPATH=. uv run python examples/slack_example.py
    

Available examples:

  • fastapi_integration.py
  • simulate_outage.py
  • slack_example.py
  • stripe_example.py

๐ŸŽฏ Use Cases

  • Service-to-service communication
  • Third-party API integrations
  • Payment gateways
  • Authentication providers
  • Event-driven systems
  • Containerized applications
  • Kubernetes deployments
  • Any environment where downstream dependencies may become unavailable

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ad_tech_inc_resilient_http-0.1.1.tar.gz (368.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ad_tech_inc_resilient_http-0.1.1-py3-none-any.whl (10.5 kB view details)

Uploaded Python 3

File details

Details for the file ad_tech_inc_resilient_http-0.1.1.tar.gz.

File metadata

File hashes

Hashes for ad_tech_inc_resilient_http-0.1.1.tar.gz
Algorithm Hash digest
SHA256 9f47959e30710d6dc850d971987a469ae41723fcfdfa3a647c88781feab5644f
MD5 6bc57cd43a3bc20717a6e5ab4923b7db
BLAKE2b-256 cb829f06916e0b07a9e1b1c474a98d0e500e60ebfa74b1b80289218a478f1259

See more details on using hashes here.

Provenance

The following attestation bundles were made for ad_tech_inc_resilient_http-0.1.1.tar.gz:

Publisher: publish.yml on AD-Technology-Inc/resilient-http-client

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ad_tech_inc_resilient_http-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for ad_tech_inc_resilient_http-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c07bb94a0910adf7f47bdc92a0b57f9521eebd9038ddcd56e870a102970d8063
MD5 389c8ff7895b1378d82c0ff2cb1c6627
BLAKE2b-256 891c078b93d1e6c55b6351c00108d5c4ecd19dbeef40fadbff553e72e3cd1434

See more details on using hashes here.

Provenance

The following attestation bundles were made for ad_tech_inc_resilient_http-0.1.1-py3-none-any.whl:

Publisher: publish.yml on AD-Technology-Inc/resilient-http-client

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page