PHPackages                             ananiaslitz/resilience - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. ananiaslitz/resilience

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ananiaslitz/resilience
======================

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

00PHP

Since Aug 4Pushed 2w agoCompare

[ Source](https://github.com/Ananiaslitz/resilience)[ Packagist](https://packagist.org/packages/ananiaslitz/resilience)[ RSS](/packages/ananiaslitz-resilience/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependenciesVersions (1)Used By (0)

Resilience — Fault Tolerance &amp; Resilience Library for PHP
=============================================================

[](#resilience--fault-tolerance--resilience-library-for-php)

**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
--------

[](#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 &amp; 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
------------

[](#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
-----

[](#usage)

### 1. Declarative Usage with Hyperf Attributes

[](#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

[](#2-standalone--vanilla-php-usage)

Use the core classes directly without any framework dependencies:

#### Circuit Breaker

[](#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

[](#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

[](#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
-----------------------------

[](#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
-------------

[](#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
-------

[](#license)

Resilience is open-sourced software licensed under the [MIT License](LICENSE).

###  Health Score

20

—

LowBetter than 12% of packages

Maintenance63

Regular maintenance activity

Popularity0

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity11

Early-stage or recently created project

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/963a9f4c77e080eaafe63352d0ec2e1dc101cb54b734c0a144223893793000b5?d=identicon)[Ananiaslitz](/maintainers/Ananiaslitz)

---

Top Contributors

[![DegasLitz](https://avatars.githubusercontent.com/u/207736081?v=4)](https://github.com/DegasLitz "DegasLitz (2 commits)")[![dhsananias](https://avatars.githubusercontent.com/u/29582813?v=4)](https://github.com/dhsananias "dhsananias (1 commits)")

### Embed Badge

![Health badge](/badges/ananiaslitz-resilience/health.svg)

```
[![Health](https://phpackages.com/badges/ananiaslitz-resilience/health.svg)](https://phpackages.com/packages/ananiaslitz-resilience)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
