Skip to main content

FaultShield

Lightweight, zero-dependency resilience and fault-tolerance toolkit for Python.

Python 3.9+ Zero Dependencies Tests Passed License: MIT


Overview

Modern distributed systems, microservices, cloud APIs, and background job runners inevitably experience network blips, cascading failures, downstream rate limits, and transient latency spikes.

faultshield provides production-grade resilience primitives in pure standard library Python with zero external dependencies. It brings the power of enterprise resilience patterns (like Polly and Resilience4j) to Python applications with clean decorators, context managers, and a fluent pipeline API.

Core Capabilities

  • Zero External Dependencies: Pure Python 3.9+ standard library.
  • Circuit Breaker: Full state machine (CLOSED, OPEN, HALF_OPEN) with sliding window failure rate evaluation, slow call detection, and automatic recovery.
  • Adaptive Retries with Jitter: Exponential backoff with Full, Equal, and Decorrelated jitter algorithms to prevent thundering herds.
  • Token Bucket Rate Limiting: Traffic shaping and quota enforcement with burst tolerance and thread-safe token replenishment.
  • Bulkhead Concurrency Isolation: Isolate worker pools, limit simultaneous in-flight operations, and protect critical downstream resources.
  • Execution Timeout Guard: Enforce strict execution time bounds on operations without hanging worker threads.
  • Fallback Strategies: Graceful degradation to default values or cached responses on failures.
  • Fluent Resilience Pipeline: Combine all policies into a single cohesive execution chain with integrated telemetry.
  • Embedded Telemetry & Metrics: Real-time tracking of success rates, retry counts, circuit trips, rejections, and latency percentiles (p50, p90, p99).

Quickstart

1. Circuit Breaker

Protect unreliable external APIs with fast failure and automatic recovery:

from faultshield import CircuitBreaker, CircuitOpenError

# Trip circuit when failure rate reaches 50% across 10 calls; cooldown for 30s
breaker = CircuitBreaker(
    name="payment_gateway",
    failure_rate_threshold=50.0,
    recovery_timeout=30.0,
    sliding_window_size=10,
    minimum_number_of_calls=5,
    fallback=lambda exc: {"status": "degraded", "cached": True},
)

@breaker
def charge_card(account_id: str, amount: float):
    # Remote call that may raise ConnectionError
    return api_client.charge(account_id, amount)

# Or invoke directly:
result = breaker.execute(charge_card, "acc_123", 49.99)

2. Adaptive Retries with Full Jitter

from faultshield import RetryPolicy, JitterStrategy

policy = RetryPolicy(
    max_attempts=3,
    initial_delay=0.1,
    max_delay=5.0,
    backoff_factor=2.0,
    jitter=JitterStrategy.FULL,
    retry_on=(ConnectionError, TimeoutError),
)

@policy
def query_database():
    return db.query("SELECT * FROM items")

3. Fluent Resilience Pipeline

Combine Retries, Circuit Breaker, Timeout, Bulkhead, and Rate Limiter into a single pipeline:

from faultshield import ResiliencePipeline, JitterStrategy

pipeline = (
    ResiliencePipeline("customer_api")
    .add_fallback(lambda exc: {"status": "fallback", "data": []})
    .add_retry(max_attempts=3, initial_delay=0.05, jitter=JitterStrategy.FULL)
    .add_circuit_breaker(failure_rate_threshold=50.0, recovery_timeout=15.0)
    .add_timeout(seconds=2.0)
    .add_bulkhead(max_concurrent=10)
    .add_rate_limiter(rate=50.0, capacity=100.0)
)

@pipeline
def get_customer(customer_id: int):
    return http_get(f"/customers/{customer_id}")

# Access runtime telemetry
metrics = pipeline.get_metrics()
print(f"Success rate: {metrics['success_rate_pct']}% | Retries: {metrics['retries']}")

4. Bulkhead & Rate Limiting

from faultshield import Bulkhead, RateLimiter

limiter = RateLimiter(rate=10.0, capacity=20.0)
bulkhead = Bulkhead(max_concurrent=5, max_queued=10, queue_timeout=1.0)

with limiter:
    with bulkhead:
        # Protected critical section
        do_heavy_work()

CLI & Benchmarking

FaultShield includes a command-line tool for stress testing and interactive demonstrations:

# Run comparative benchmark: Unprotected vs FaultShield protected
faultshield benchmark -n 100 -f 0.4

# Run interactive circuit breaker state walkthrough
faultshield demo

Sample Benchmark Output:

====================================================================
BENCHMARK COMPARISON RESULTS
--------------------------------------------------------------------
Metric                           | Unprotected     | FaultShield Protected
--------------------------------------------------------------------
Successful Invocations           | 58              | 58             
Uncaught Crash / Exceptions      | 42              | 0              
Rescued by Fallback              | N/A             | 42             
Retries Executed                 | 0               | 26             
Total Elapsed Time               | 0.0028s         | 0.0412s        
--------------------------------------------------------------------
Reliability Gain: Unprotected 58.0% -> Protected 100% availability
====================================================================

Architecture & Deep Dive

For mathematical formulations of the jitter algorithms, token bucket equations, and state machine transitions, see docs/ARCHITECTURE.md.

For installation and developer setup instructions, see docs/SETUP.md.


License

This project is licensed under the MIT License.

Metadata

Release files for faultshield 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for faultshield 0.1.0
File Size Uploaded Provenance Actions
faultshield-0.1.0.tar.gz 24.8 kB With provenance Details for faultshield-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for faultshield 0.1.0
File Interpreter ABI Platform Actions
faultshield-0.1.0-py3-none-any.whl Python 3 none any Details for faultshield-0.1.0-py3-none-any.whl

Total release size: 47.6 kB

Release files / faultshield-0.1.0.tar.gz

Download URL faultshield-0.1.0.tar.gz
Size 24.8 kB
Tags Source
SHA-256 checksum
How to use checksums
0dc7060ccc3063546e14b0799cc4438d1155e96b8242ab2847ea7b4949ef4580
BLAKE2b-256 checksum
How to use checksums
223a9d1ac9f91cb2277de39bc73b02fc0179147fef7dc5cf43e8bc3c1f5ac2bc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

Release files / faultshield-0.1.0-py3-none-any.whl

Download URL faultshield-0.1.0-py3-none-any.whl
Size 22.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a82db3232a564c07fb4e9c702c91136b612e1c7ef5091f8bd5e651a7a55ac147
BLAKE2b-256 checksum
How to use checksums
a58bdec566e316fbcb26cc58f17e94c28d6b72262fa9c5b6d008f2c695e94ad5
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

Security for faultshield 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for faultshield-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page