PHPackages                             christopheraseidl/circuit-breaker - 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. christopheraseidl/circuit-breaker

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

christopheraseidl/circuit-breaker
=================================

A simple circuit breaker that prevents cascading failures.

v0.4.1(10mo ago)1418[4 PRs](https://github.com/christopheraseidl/circuit-breaker/pulls)1MITPHPPHP ^8.3CI passing

Since Jul 2Pushed 4mo agoCompare

[ Source](https://github.com/christopheraseidl/circuit-breaker)[ Packagist](https://packagist.org/packages/christopheraseidl/circuit-breaker)[ Docs](https://github.com/christopheraseidl/circuit-breaker)[ GitHub Sponsors](https://github.com/christopheraseidl)[ RSS](/packages/christopheraseidl-circuit-breaker/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (11)Versions (7)Used By (1)

Circuit Breaker
===============

[](#circuit-breaker)

[![Latest Version on Packagist](https://camo.githubusercontent.com/26707fd7983f080a30d11607017dab83feb19c423aa794a8c902480ead06119c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6368726973746f7068657261736569646c2f636972637569742d627265616b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/christopheraseidl/circuit-breaker)[![GitHub Tests Action Status](https://camo.githubusercontent.com/0684dad1db69981f727bd516bb506dd9c547b4fe9c56531022a4ed8301b28521/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6368726973746f7068657261736569646c2f636972637569742d627265616b65722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/christopheraseidl/circuit-breaker/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/da2e45e84665407f1bbafe0657e16ca13c312c008c787a489e7ae9478d525be2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6368726973746f7068657261736569646c2f636972637569742d627265616b65722f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/christopheraseidl/circuit-breaker/actions?query=workflow%3A%22Fix+PHP+code+style+issues%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/388cfa4ab7ccf4fe61c99a994d3baf21011067d7593a1d9dff4e32fec6b5a448/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6368726973746f7068657261736569646c2f636972637569742d627265616b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/christopheraseidl/circuit-breaker)

A framework-agnostic circuit breaker implementation that prevents cascading failures by monitoring error rates and temporarily blocking requests when thresholds are exceeded.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require christopheraseidl/circuit-breaker
```

### Laravel Installation

[](#laravel-installation)

The package auto-registers its service provider and automatically wires up Laravel's cache, logger, and mailer as adapters.

You may optionally publish the configuration file:

```
php artisan vendor:publish --tag="circuit-breaker-config"
```

After publishing, update the config file to use Laravel's `env()` helper (recommended):

```
'notifiers' => [
    'email' => [
        'recipients' => [env('MAIL_FROM_ADDRESS')],
        'from_address' => env('MAIL_FROM_ADDRESS'),
        'from_name' => env('MAIL_FROM_NAME'),
    ],
],
```

Optionally publish the email notification view:

```
php artisan vendor:publish --tag="circuit-breaker-views"
```

Usage
-----

[](#usage)

### Basic Example

[](#basic-example)

```
use christopheraseidl\CircuitBreaker\CircuitBreaker;

// Create circuit breaker instance
$breaker = new CircuitBreaker(
    name: 'payment-gateway',
    cache: $cache,        // Must implement CacheContract
    logger: $logger,      // Must implement LoggerContract
    notifier: $notifier,  // Must implement NotifierContract
    config: [
        'failure_threshold' => 5,
        'window_seconds' => 60,
        'recovery_timeout_seconds' => 300,
    ]
);

// Wrap external service calls
if ($breaker->canAttempt()) {
    try {
        $result = $paymentGateway->charge($amount);
        $breaker->recordSuccess();
        return $result;
    } catch (\Exception $e) {
        $breaker->recordFailure();
        throw $e;
    }
} else {
    throw new ServiceUnavailableException('Payment service temporarily unavailable');
}
```

### Laravel Example

[](#laravel-example)

```
use christopheraseidl\CircuitBreaker\CircuitBreakerFactory;

// Using dependency injection
public function __construct(
    private CircuitBreakerFactory $circuitBreakerFactory
) {}

public function processPayment($amount)
{
    $breaker = $this->circuitBreakerFactory->make('payment-service', [
        'failure_threshold' => 3,
        'recovery_timeout_seconds' => 120,
    ]);

    if ($breaker->canAttempt()) {
        try {
            $response = Http::timeout(5)->post('https://payments.example.com/charge', [
                'amount' => $amount,
            ]);
            $breaker->recordSuccess();
            return $response->json();
        } catch (\Exception $e) {
            $breaker->recordFailure();
            return ['error' => 'Payment service temporarily unavailable'];
        }
    }

    return ['error' => 'Payment service is currently down'];
}

// Or resolve from container
$factory = app(CircuitBreakerFactory::class);
$breaker = $factory->make('api-service');

if (! $breaker->canAttempt()) {
    return cache()->remember('api-fallback-data', 3600, fn() => [...]);
}
```

### Monitoring Circuit State

[](#monitoring-circuit-state)

```
// Check circuit state
if ($breaker->isOpen()) {
    // Circuit is open - requests are blocked
}

if ($breaker->isHalfOpen()) {
    // Circuit is testing recovery
}

// Get statistics
$stats = $breaker->getStats();
// [
//     'name' => 'payment-gateway',
//     'state' => 'open',
//     'failure_count' => 5,
//     'failure_threshold' => 5,
//     'recovery_timeout_seconds' => 300,
// ]

// Manually reset circuit
$breaker->reset();
```

Configuration
-------------

[](#configuration)

The default configuration covers common use cases:

```
[
    'defaults' => [
        'failure_threshold' => 5,          // Open circuit after 5 failures
        'window_seconds' => 60,            // Count failures within 60 seconds
        'recovery_timeout_seconds' => 300, // Try recovery after 5 minutes
        'half_open_max_attempts' => 3,     // Allow 3 tests before reopening
        'half_open_delay' => 1,            // Base delay, in seconds, between recovery attempts
    ],
    'notifiers' => [
        'email' => [
            'recipients' => null,      // Set email addresses for notifications
            'from_address' => null,    // Set sender email address
            'from_name' => 'Circuit Breaker',
        ],
    ],
]
```

Implementing Adapters
---------------------

[](#implementing-adapters)

To use the circuit breaker outside Laravel, implement the required contracts:

```
use christopheraseidl\CircuitBreaker\Contracts\CacheContract;

class RedisCache implements CacheContract
{
    public function put(string $key, mixed $value, ?int $ttl = 1): bool
    {
        return $this->redis->setex($key, $ttl, serialize($value));
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $value = $this->redis->get($key);
        return $value !== false ? unserialize($value) : $default;
    }

    // ... implement remaining methods
}
```

Testing
-------

[](#testing)

```
./vendor/bin/pest
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Chris Seidl](https://github.com/christopheraseidl)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance67

Regular maintenance activity

Popularity14

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 93.8% 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.

###  Release Activity

Cadence

Every ~12 days

Total

2

Last Release

301d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/639d641f14096c8c9e5e0e990b06414f5ed5f6ea4d13b6e103aae2405ce870fc?d=identicon)[christopheraseidl](/maintainers/christopheraseidl)

---

Top Contributors

[![christopheraseidl](https://avatars.githubusercontent.com/u/73406146?v=4)](https://github.com/christopheraseidl "christopheraseidl (15 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

laravelcircuit breakerchristopheraseidl

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/christopheraseidl-circuit-breaker/health.svg)

```
[![Health](https://phpackages.com/badges/christopheraseidl-circuit-breaker/health.svg)](https://phpackages.com/packages/christopheraseidl-circuit-breaker)
```

###  Alternatives

[francescomalatesta/laravel-circuit-breaker

A circuit breaker pattern implementation for the Laravel framework

2919.2k2](/packages/francescomalatesta-laravel-circuit-breaker)[stephenjude/filament-blog

Filament Blog Builder

20317.8k](/packages/stephenjude-filament-blog)[gabrielanhaia/laravel-circuit-breaker

Laravel integration for PHP Circuit Breaker — multiple storage drivers, middleware, Artisan commands, and event system

481.0k](/packages/gabrielanhaia-laravel-circuit-breaker)[datomatic/nova-detached-actions

A Laravel Nova tool to allow for placing actions in the Nova toolbar detached from the checkbox selection mechanism.

11229.2k](/packages/datomatic-nova-detached-actions)

PHPackages © 2026

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