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

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

stfn/php-circuit-breaker
========================

This is circuit-breaker pattern implemented in PHP

v0.1.5(2y ago)031MITPHPPHP ^8.1

Since Jan 25Pushed 2y ago1 watchersCompare

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

READMEChangelogDependencies (2)Versions (7)Used By (0)

Circuit breaker in PHP
======================

[](#circuit-breaker-in-php)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6789d40899eb8d840fcb7b716af4fac8ce01864734c84177ea09beb441de6459/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7374666e2f7068702d636972637569742d627265616b65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/stfn/php-circuit-breaker)

This package provides an implementation of the circuit breaker pattern in PHP. You can find more info about it [here](https://learn.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker).

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

[](#installation)

You can install the package via composer:

```
composer require stfn/php-circuit-breaker
```

Usage
-----

[](#usage)

Wrap your potentially error-prone function with the circuit breaker, and it will monitor and handle failures.

```
use Stfn\CircuitBreaker\CircuitBreaker;

$result = CircuitBreaker::for('3rd-party-service')->call(function () {
    // Your function that could fail
});
```

States
------

[](#states)

Circuit breaker can have 4 different states.

### Closed

[](#closed)

In the `Closed` state, the circuit breaker is fully operational, allowing calls to the 3rd party service. Any exceptions that occur during this state are counted.

### Half Open

[](#half-open)

The Half Open state is a transitional phase where the circuit breaker allows a limited number of calls to the 3rd party service. If these calls are successful, the circuit is closed again. However, if the service continues to exhibit issues, the circuit is moved back to the `Open` state.

### Open

[](#open)

The `Open` state indicates that the circuit breaker has detected a critical failure, and the call method will fail immediately, throwing a `CircuitOpenException` exception.

### Force Open

[](#force-open)

`Force Open` is not part of the regular flow. It can be utilized when intentional suspension of calls to a service is required. In this state, a `CircuitOpenException` will be thrown.

To force the circuit breaker into the Force Open state, use the following:

```
use Stfn\CircuitBreaker\CircuitBreaker;

$breaker = CircuitBreaker::for('3rd-party-service')->forceOpenCircuit();
```

This feature provides a manual override to stop calls to a service temporarily, offering additional control when needed.

Storage
-------

[](#storage)

By default, the circuit breaker uses `InMemoryStorage` as a storage driver, which is not suitable for most of PHP applications.

More useful would be to use `RedisStorage`.

```
use Stfn\CircuitBreaker\Storage\RedisStorage;
use Stfn\CircuitBreaker\CircuitBreaker;

$redis = new \Redis();
$redis->connect("127.0.0.1");

$storage = new RedisStorage($redis);

$result = CircuitBreaker::for('3rd-party-service')
    ->storage($storage)
    ->call(function () {
        // Your function that could fail
    });
```

You could also write your implementation of storage. You should just implement `CircuitBreakerStorage` interface.

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

[](#configuration)

Each circuit breaker has default configuration settings, but you can customize them to fit your needs:

```
use Stfn\CircuitBreaker\CircuitBreaker;

$breaker = CircuitBreaker::for('3rd-party-service')
    ->withOptions([
        'failure_threshold' => 10, // Number of failures triggering the transition to the open state
        'recovery_time' => 120, // Time in seconds to keep the circuit breaker open before attempting recovery
        'sample_duration' => 60, // Duration in seconds within which failures are counted
        'consecutive_success' => 3 // Number of consecutive successful calls required to transition from half open to closed state
    ]);
```

Excluding some failures
-----------------------

[](#excluding-some-failures)

Change the circuit breaker behavior by configuring it to exclude certain types of failures:

```
use Stfn\CircuitBreaker\CircuitBreaker;

$breaker = CircuitBreaker::for('3rd-party-service')
    ->skipFailureCount(function ($exception) {
        return $exception->getCode() < 500;
    });
```

Listeners
---------

[](#listeners)

You can add listeners for circuit breaker actions by extending the CircuitBreakerListener class:

```
use Stfn\CircuitBreaker\CircuitBreakerListener;
use Stfn\CircuitBreaker\CircuitState;

class LoggerListener extends CircuitBreakerListener
{
    public function beforeCall(CircuitBreaker $breaker, \Closure $action,...$args) : void
    {
        Log::info("before call");
    }

    public function onSuccess(CircuitBreaker $breaker, $result): void
    {
        Log::info($result);
    }

    public function onFail(CircuitBreaker $breaker, $exception) : void
    {
        Log::info($exception);
    }

    public function onStateChange(CircuitBreaker $breaker, CircuitState $previousState, CircuitState $newState)
    {
        Log::info($previousState, $newState);
    }
}
```

Attach the listener to the circuit breaker:

```
use Stfn\CircuitBreaker\CircuitBreaker;

$breaker = CircuitBreaker::for('3rd-party-service')
    ->listeners([new LoggerListener()]);
```

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

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

###  Health Score

21

—

LowBetter than 19% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~0 days

Total

6

Last Release

839d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ab08845d8fb0e2eb1bc4a304ab3a0919ca2c2a0ae0198689d4744047c6e5c809?d=identicon)[stfndamjanovic](/maintainers/stfndamjanovic)

---

Top Contributors

[![stfndamjanovic](https://avatars.githubusercontent.com/u/22433990?v=4)](https://github.com/stfndamjanovic "stfndamjanovic (80 commits)")

---

Tags

circuit-breakercircuit-breaker-patternfailure-handlingmicroservicephpstfndamjanoviccircuit-breaker-php

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[nizsheanez/yii2-asset-converter

Less, Sass, Scss and Phamlp converter for Yii2. No system requires. yii2-composer support, Less autoupdate, customizing of output directory

64167.5k6](/packages/nizsheanez-yii2-asset-converter)[jijunair/laravel-referral

Laravel package for a referral system

9223.8k](/packages/jijunair-laravel-referral)[japanese-holiday/japanese-holiday

30122.9k](/packages/japanese-holiday-japanese-holiday)[topshelfcraft/environment-label

...so you don't forget where you are.

16231.4k10](/packages/topshelfcraft-environment-label)[moc/notfound

Neos CMS package that loads a normal editable page for displaying a 404 error

18167.5k](/packages/moc-notfound)[phpinnacle/buffer

PHPinnacle binary buffer implementation

2493.7k10](/packages/phpinnacle-buffer)

PHPackages © 2026

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