ananiaslitz/resilience

Fault tolerance and resilience library for PHP 8.1+ inspired by Resilience4j (CircuitBreaker, Retry, RateLimiter, TimeLimiter) with Hyperf Attributes support.

Maintainers

Package info

github.com/Ananiaslitz/resilience

pkg:composer/ananiaslitz/resilience

Transparency log

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main 2026-08-04 22:20 UTC

This package is auto-updated.

Last update: 2026-08-04 22:22:13 UTC


README

Resilience is a lightweight, zero-framework-dependency fault tolerance library for PHP 8.1+ inspired by Resilience4j. It provides Circuit Breaker, Automatic Retry with Exponential Backoff, Rate Limiter, and Fallback execution mechanisms for high-availability systems.

It includes native Hyperf AOP Attributes (#[CircuitBreaker], #[Retry], #[RateLimiter]) for zero-touch method decoration in Hyperf microservices, while remaining 100% usable as a standalone Vanilla PHP library.

Features

  • Circuit Breaker — Multi-state machine (CLOSED, OPEN, HALF_OPEN) tracking failure rate and slow call thresholds using a sliding window.
  • Automatic Retry — Configurable retry attempts, exponential backoff, random jitter (to prevent thundering herd), and exception filters.
  • Rate Limiter — Sliding window rate limiting with configurable refresh periods and acquire timeouts.
  • Fallback Execution — Seamless fallback execution when circuits open, retries exhaust, or rate limits are exceeded.
  • Hyperf Attributes & AOP — Declarative method decoration via PHP 8 attributes (#[CircuitBreaker], #[Retry], #[RateLimiter]).
  • Framework Agnostic Core — Pure Vanilla PHP core compatible with Laravel, Symfony, Hyperf, Workerman, Swoole, or raw PHP scripts.

Installation

Install the package via Composer:

composer require ananiaslitz/resilience

For Hyperf applications, publish the configuration file (optional):

php bin/hyperf.php vendor:publish ananiaslitz/resilience

Usage

1. Declarative Usage with Hyperf Attributes

Decorate any class method using PHP 8 attributes:

namespace App\Service;

use Resilience\Attribute\CircuitBreaker;
use Resilience\Attribute\Retry;
use Resilience\Attribute\RateLimiter;

class PaymentService
{
    #[CircuitBreaker(name: 'stripe', failureRateThreshold: 50.0, fallback: 'paymentFallback')]
    #[Retry(name: 'stripe', maxAttempts: 3, waitDurationMs: 200.0, backoffMultiplier: 2.0)]
    #[RateLimiter(name: 'stripe', limitForPeriod: 10)]
    public function processPayment(array $payload): array
    {
        // Primary API call
        return $this->stripeClient->charge($payload);
    }

    public function paymentFallback(array $payload, \Throwable $exception): array
    {
        // Graceful fallback when circuit is OPEN or retries are exhausted
        return [
            'status'  => 'fallback',
            'gateway' => 'pagarme',
            'message' => 'Primary payment gateway unavailable. Routed to secondary provider.',
        ];
    }
}

2. Standalone / Vanilla PHP Usage

Use the core classes directly without any framework dependencies:

Circuit Breaker

use Resilience\CircuitBreaker\CircuitBreaker;
use Resilience\CircuitBreaker\CircuitBreakerConfig;

$config = new CircuitBreakerConfig(
    failureRateThreshold: 50.0,
    waitDurationInOpenStateMs: 10000.0,
    slidingWindowSize: 20
);

$cb = CircuitBreaker::of('stripe', $config);

$result = $cb->execute(
    action: fn() => $httpClient->get('https://api.stripe.com/v1/charges'),
    fallback: fn(\Throwable $e) => ['status' => 'fallback_response']
);

Automatic Retry with Exponential Backoff

use Resilience\Retry\Retry;
use Resilience\Retry\RetryConfig;

$retry = Retry::of('external_api', new RetryConfig(
    maxAttempts: 3,
    waitDurationMs: 100.0,
    backoffMultiplier: 2.0,
    jitter: true
));

$response = $retry->execute(
    action: fn() => $apiClient->fetchData(),
    fallback: fn(\Throwable $e) => null
);

Rate Limiter

use Resilience\RateLimiter\RateLimiter;
use Resilience\RateLimiter\RateLimiterConfig;

$rateLimiter = RateLimiter::of('api_limiter', new RateLimiterConfig(
    limitForPeriod: 10,
    limitRefreshPeriodMs: 1000.0
));

$rateLimiter->execute(
    action: fn() => $service->doWork()
);

Circuit Breaker State Machine

       ┌──────────┐
       │  CLOSED  │ ◄────── Calls succeed / Failure rate < threshold
       └────┬─────┘
            │ Failure rate >= threshold (or slow calls exceed limit)
            ▼
       ┌──────────┐
       │   OPEN   │ ◄────── Calls rejected immediately with CallNotPermittedException
       └────┬─────┘
            │ Wait duration in OPEN state elapses
            ▼
       ┌──────────┐
       │ HALF_OPEN│ ──────► Failure in HALF_OPEN ──────► OPEN
       └────┬─────┘
            │ Permitted calls succeed
            ▼
         CLOSED

Configuration

The default configuration file for Hyperf is published to config/autoload/resilience.php:

return [
    'circuit_breaker' => [
        'default' => [
            'failure_rate_threshold'          => 50.0,
            'slow_call_rate_threshold'        => 100.0,
            'slow_call_duration_threshold_ms' => 2000.0,
            'sliding_window_size'             => 100,
            'minimum_number_of_calls'         => 10,
            'wait_duration_in_open_state_ms'  => 10000.0,
        ],
    ],

    'retry' => [
        'default' => [
            'max_attempts'       => 3,
            'wait_duration_ms'   => 200.0,
            'backoff_multiplier' => 2.0,
            'jitter'             => true,
        ],
    ],

    'rate_limiter' => [
        'default' => [
            'limit_for_period'        => 10,
            'limit_refresh_period_ms' => 1000.0,
            'timeout_duration_ms'     => 0.0,
        ],
    ],
];

License

Resilience is open-sourced software licensed under the MIT License.