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

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

gabrielanhaia/php-circuit-breaker
=================================

Circuit breaker pattern for PHP with multiple storage adapters, event system, and manual override.

v3.0.0(5mo ago)173.7k↓27.9%[2 issues](https://github.com/gabrielanhaia/php-circuit-breaker/issues)2MITPHPPHP &gt;=8.1CI failing

Since Jun 22Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/gabrielanhaia/php-circuit-breaker)[ Packagist](https://packagist.org/packages/gabrielanhaia/php-circuit-breaker)[ RSS](/packages/gabrielanhaia-php-circuit-breaker/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (4)Dependencies (7)Versions (13)Used By (2)

[![CI](https://github.com/gabrielanhaia/php-circuit-breaker/actions/workflows/ci.yml/badge.svg)](https://github.com/gabrielanhaia/php-circuit-breaker/actions/workflows/ci.yml/badge.svg)[![Licence](https://camo.githubusercontent.com/a3ad04e1813250aaf6af1d9c40974c71e39fb4a5819aa0e83f7862601076aa25/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e63652d4d49542d626c7565)](https://camo.githubusercontent.com/a3ad04e1813250aaf6af1d9c40974c71e39fb4a5819aa0e83f7862601076aa25/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e63652d4d49542d626c7565)[![PHP](https://camo.githubusercontent.com/ea69ff8021a683c7b1ff683bfd909a5c960efd54004b1782ad84add19aecdac8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d383839324246)](https://camo.githubusercontent.com/ea69ff8021a683c7b1ff683bfd909a5c960efd54004b1782ad84add19aecdac8/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d383839324246)[![Buy Me a Coffee](https://camo.githubusercontent.com/a38be2655e000d36e657e0d09b2891f50838f76f20fa955b7e4f2e68e1fed937/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4275792532304d6525323061253230436f666665652d737570706f72742d79656c6c6f773f6c6f676f3d6275796d6561636f66666565)](https://buymeacoffee.com/anhaia)

PHP Circuit Breaker
===================

[](#php-circuit-breaker)

A robust, production-ready implementation of the [Circuit Breaker pattern](https://martinfowler.com/bliki/CircuitBreaker.html) for PHP. Protect your microservices from cascading failures with configurable thresholds, multiple storage backends, an event system, and manual override capabilities.

How It Works
------------

[](#how-it-works)

 ```
stateDiagram-v2
    [*] --> Closed
    Closed --> Open : Failures ≥ threshold
    Open --> HalfOpen : Timeout expires
    HalfOpen --> Closed : Successes ≥ threshold
    HalfOpen --> Open : Any failure
```

      Loading StateDescription**Closed**Normal operation. Requests pass through. Failures are counted.**Open**Circuit is tripped. All requests are rejected immediately.**Half-Open**Recovery probe. Limited requests are allowed to test if the service has recovered.Installation
------------

[](#installation)

```
composer require gabrielanhaia/php-circuit-breaker:^3.0
```

### Optional Dependencies

[](#optional-dependencies)

Install only what you need:

```
# For Redis storage
# Requires ext-redis PHP extension

# For PSR-16 (SimpleCache) storage
composer require psr/simple-cache

# For PSR-6 (Cache) storage
composer require psr/cache

# For PSR-14 event dispatcher bridge
composer require psr/event-dispatcher
```

Quick Start
-----------

[](#quick-start)

```
use GabrielAnhaia\PhpCircuitBreaker\CircuitBreaker;
use GabrielAnhaia\PhpCircuitBreaker\CircuitBreakerConfig;
use GabrielAnhaia\PhpCircuitBreaker\Storage\InMemoryStorage;

$storage = new InMemoryStorage();
$config  = new CircuitBreakerConfig(
    failureThreshold: 5,
    openTimeout:      30,
);

$cb = new CircuitBreaker($storage, $config);

$service = 'payment-api';

if (!$cb->canPass($service)) {
    // Circuit is open — use fallback
    return cachedResponse();
}

try {
    $result = callPaymentApi();
    $cb->recordSuccess($service);
    return $result;
} catch (\Throwable $e) {
    $cb->recordFailure($service);
    return cachedResponse();
}
```

Features
--------

[](#features)

- **Multiple storage backends** — InMemory, Redis, APCu, Memcached, PSR-6, PSR-16
- **Success threshold** — require N consecutive successes before closing a half-open circuit
- **Event system** — react to state changes with listeners; optional PSR-14 bridge
- **Manual override** — force circuits open/closed for maintenance windows or testing
- **State inspection** — query effective circuit state at any time
- **Immutable config** — type-safe `CircuitBreakerConfig` value object
- **Zero required extensions** — only `ext-redis`, `ext-apcu`, `ext-memcached` needed if you use those adapters
- **PHPStan level max** — fully statically analyzed
- **PHP 8.1+** — uses native enums, readonly properties, and named arguments

Documentation
-------------

[](#documentation)

TopicDescription[Configuration](docs/configuration.md)Config object, parameter table, exception mode[Storage Adapters](docs/storage-adapters.md)All 6 adapters, key scheme, comparison table[Event System](docs/events.md)Events, sequence diagram, SimpleEventDispatcher, PSR-14 bridge[Manual Override](docs/manual-override.md)`forceState()`, `clearOverride()`, state inspection[Architecture](docs/architecture.md)Class diagram, directory structure, request flowUpgrading from v2
-----------------

[](#upgrading-from-v2)

See [UPGRADE-3.0.md](UPGRADE-3.0.md) for a detailed migration guide.

### Key Breaking Changes

[](#key-breaking-changes)

v2v3`CircuitStateEnum``CircuitState` (backing value `'close'` → `'closed'`)`CircuitBreakerAdapter` (abstract class)`CircuitBreakerStorageInterface``new CircuitBreaker($adapter, $settings)``new CircuitBreaker($storage, $config)``Alert` interfaceEvent listeners`AdapterException``StorageException``CircuitException``OpenCircuitException``ext-redis` required`ext-redis` optional (suggested)### Deprecated Methods (Removed in v4)

[](#deprecated-methods-removed-in-v4)

- `$cb->failed($service)` → use `$cb->recordFailure($service)`
- `$cb->succeed($service)` → use `$cb->recordSuccess($service)`

Development
-----------

[](#development)

```
# Install dependencies
composer install

# Run tests
composer test                              # All tests
vendor/bin/phpunit --testsuite Unit        # Unit tests only
vendor/bin/phpunit --testsuite Integration # Integration tests only

# Static analysis
composer phpstan

# Code style
composer cs-check    # Check for violations
composer cs-fix      # Auto-fix violations
```

### CI

[](#ci)

GitHub Actions runs on PHP 8.1, 8.2, 8.3, 8.4 with three jobs:

- **Tests** — unit + integration (with Redis service)
- **Static Analysis** — PHPStan level max
- **Code Style** — PHP-CS-Fixer (PER-CS + PHP 8.1 migration)

Support
-------

[](#support)

If this library helps you, consider buying me a coffee:

[![Buy Me a Coffee](https://camo.githubusercontent.com/4c3bb38a901ae456180b167f696783cbb8b110dfde824322cfb879d719173426/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4275792532304d6525323061253230436f666665652d737570706f72742d79656c6c6f773f6c6f676f3d6275796d6561636f66666565267374796c653d666f722d7468652d6261646765)](https://buymeacoffee.com/anhaia)

License
-------

[](#license)

MIT — see [LICENSE](LICENSE) for details.

---

Created by [Gabriel Anhaia](https://www.linkedin.com/in/gabrielanhaia) | [Buy Me a Coffee](https://buymeacoffee.com/anhaia)

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance70

Regular maintenance activity

Popularity31

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity71

Established project with proven stability

 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 ~410 days

Recently: every ~513 days

Total

6

Last Release

150d ago

Major Versions

1.x-dev → 2.0.02025-08-31

2.x-dev → v3.0.02026-02-05

PHP version history (2 changes)2.0.0PHP ^8.1

v3.0.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/70de9e48cd27f693c91e0b91c3afd82adf08d817cd5128a8b8b43f4431d6f7b4?d=identicon)[gabrielanhaia](/maintainers/gabrielanhaia)

---

Top Contributors

[![gabrielanhaia](https://avatars.githubusercontent.com/u/15172908?v=4)](https://github.com/gabrielanhaia "gabrielanhaia (61 commits)")

---

Tags

circuit-breakerlaravellaravel-frameworklumenlumen-frameworkmicroservicesphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[naux/auto-correct

12411.4k2](/packages/naux-auto-correct)[eljam/circuit-breaker

A php Circuit Breaker

1711.1k1](/packages/eljam-circuit-breaker)

PHPackages © 2026

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