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

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

algoyounes/circuit-breaker
==========================

Circuit Breaker is laravel package that provides a way to handle failures gracefully

v1.8(2mo ago)551.8kMITPHPPHP ^8.2CI passing

Since Jan 27Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/algoyounes/circuit-breaker)[ Packagist](https://packagist.org/packages/algoyounes/circuit-breaker)[ RSS](/packages/algoyounes-circuit-breaker/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (21)Versions (18)Used By (0)

[![Circuit Breaker Logo](assets/logo.png)](assets/logo.png)

[![Build Status](https://github.com/algoyounes/circuit-breaker/actions/workflows/unit-tests.yml/badge.svg)](https://github.com/algoyounes/circuit-breaker/actions)[![Total Downloads](https://camo.githubusercontent.com/24abf597c3dbfe57f93978fa321d6e40dcca908891a004959247d282682d6461/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616c676f796f756e65732f636972637569742d627265616b6572)](https://packagist.org/packages/algoyounes/circuit-breaker)[![Latest Stable Version](https://camo.githubusercontent.com/8f868a6e1fa782e34e9374da866d2f0336055eb646181a1a7c53bd7026a58a45/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c676f796f756e65732f636972637569742d627265616b6572)](https://packagist.org/packages/algoyounes/circuit-breaker)[![License](https://camo.githubusercontent.com/44c07c67cc298a9202b6c8909ebc7092a8f326d780de6f5af2721cd25ea784e7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f616c676f796f756e65732f636972637569742d627265616b6572)](https://packagist.org/packages/algoyounes/circuit-breaker)

**Circuit Breaker** is a Laravel package that provides a simple and efficient way to manage service calls and prevent cascading failures. It lets you define custom callbacks for key circuit states and run operations with circuit breaker logic.

The following diagram illustrates how the **Circuit Breaker Pattern** works:

[![circuit-breaker.png](assets/circuit-breaker.png)](assets/circuit-breaker.png)

For more info, check the official pattern doc [here](https://learn.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker).

Table of Contents
-----------------

[](#table-of-contents)

- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Usage](#usage)
    - [Custom Callbacks](#custom-callbacks)
    - [Running an Operation](#running-an-operation)
    - [Guzzle Middleware Integration](#guzzle-middleware-integration)
    - [Laravel Http Facade Integration](#laravel-http-facade-integration)
- [How It Works](#how-it-works)
    - [State Transitions](#state-transitions)
    - [Half-Open State Behavior](#half-open-state-behavior)
- [Configuration](#configuration)
- [Contributing](#contributing)
- [License](#license)

Prerequisites
-------------

[](#prerequisites)

This package requires:

- **PHP 8.2+**
- **Laravel 11+**
- **A configured Laravel cache driver**

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

[](#installation)

You can install the package via Composer:

```
composer require algoyounes/circuit-breaker
```

You can publish the configuration file using the following command:

```
php artisan vendor:publish --provider="AlgoYounes\CircuitBreaker\Providers\CircuitBreakerServiceProvider" --tag="config"
```

Usage
-----

[](#usage)

You can manage specific services with granular control using the `forService(...)` method. the `service-name` parameter is a unique identifier key for your service, ensuring its circuit breaker configuration is isolated from other services.

```
$circuit = $this->circuitManager->forService('service-name');
```

Tip

Use the unique `service-name` key across your application to consistently reference the same circuit configuration *(e.g., 'payment-service', ...)*

### Custom Callbacks

[](#custom-callbacks)

You can define callbacks for key circuit states:

CallbackDescriptionParameters Received`onOpen`Triggered when the circuit goes into **OPEN**, blocking calls to prevent further failures`CircuitTransition``onHalfOpen`The circuit enters **HALF-OPEN** to test stability, letting one request through`CircuitTransition``onClose`The circuit returns to **CLOSED**, allowing all requests without restrictions`CircuitTransition``onSuccess`Fires when a request succeeds, indicating system availability`CircuitResult`, `CircuitTransition``onFailure`Triggered when a request fails, potentially opening the circuit`CircuitResult`, `CircuitTransition``onSteadyState`Indicates the circuit is stable, with no need for changes`CircuitTransition`Example of defining callbacks:

```
$circuit->onOpen(function (CircuitTransition $circuitTransition) {
    // Your custom logic here
});

$circuit->onSuccess(function (CircuitResult $circuitResult, CircuitTransition $circuitTransition) {
    // Your custom logic here
});

// Params passed are optional
```

### Running an Operation

[](#running-an-operation)

To run an operation and manage its state through the circuit breaker, use the `run` method:

```
$circuit->run(function () {
    // Your service call here
});
// or
$circuit->run($this->serviceName->create(...));
```

This will execute the provided closure, applying the circuit breaker logic *(e.g., open, half-open, closed states)* around the service call.

Note

If you prefer a more direct approach, you can create a `CircuitBuilder` instance:

```
$circuit = CircuitBuilder::make('service-name')
```

#### Simplified Operation

[](#simplified-operation)

For a simplified approach, use the `run` method directly from `CircuitManager`:

```
$this->circuitManager->run('service-name', function () {
    // Your service call here
});
// or
$this->circuitManager->run('service-name', $this->serviceName->create(...));
```

### Guzzle Middleware Integration

[](#guzzle-middleware-integration)

The package provides a Guzzle middleware to automatically manage circuit breaker logic for HTTP requests.

To enable the middleware, add the following to your Guzzle client configuration:

```
use AlgoYounes\CircuitBreaker\Middleware\GuzzleMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
$stack->push(GuzzleMiddleware::create());

$client = new Client([
    'handler' => $stack,
]);

$response = $client->get('https://api.example.com', [
    'headers' => [
        'X-Circuit-Key' => 'service-name',
    ],
]);
```

### Laravel Http Facade Integration

[](#laravel-http-facade-integration)

The package integrates with Laravel's built-in `Http` facade out of the box:

```
use Illuminate\Support\Facades\Http;

$response = Http::withCircuitBreaker('payment-service')
    ->get('https://api.payment.com/charge', [
        'amount' => 1000,
    ]);
```

This automatically applies the circuit breaker middleware to the request using `payment-service` as the circuit key. You can chain it with any `Http` method:

```
$response = Http::withCircuitBreaker('shipping-service')
    ->withToken($apiToken)
    ->timeout(10)
    ->post('https://api.example.com/track', $payload);
```

When the circuit is open, a `RejectedException` is thrown:

```
use AlgoYounes\CircuitBreaker\Guzzle\Exceptions\RejectedException;

try {
    $response = Http::withCircuitBreaker('payment-service')
        ->get('https://api.example.com/charge');
} catch (RejectedException $e) {
    // Circuit is open — handle gracefully (e.g., return cached response, queue for retry)
}
```

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

[](#how-it-works)

### State Transitions

[](#state-transitions)

The circuit breaker operates in three states:

```
    ┌──────────────────────────────────────────────────────┐
    │                                                      │
    ▼                                                      │
 CLOSED ──── failures ≥ threshold ────► OPEN               │
 (normal)                               (all requests      │
                                         rejected)         │
                                           │               │
                                    cooldown expires       │
                                           │               │
                                           ▼               │
                                       HALF-OPEN           │
                                      (single probe)       │
                                        │       │          │
                                   success    failure      │
                                        │       │          │
                                        │       └──► OPEN  │
                                        │                  │
                                        └──────────────────┘

```

- **CLOSED** — Normal operation. All requests pass through. Failures are counted.
- **OPEN** — The service is considered down. All requests are rejected immediately without calling the service. After the `cooldown_period` expires, the circuit moves to HALF-OPEN.
- **HALF-OPEN** — A single probe request is sent to test the service. If it succeeds, the circuit closes. If it fails, the circuit re-opens.

### Half-Open State Behavior

[](#half-open-state-behavior)

When a circuit transitions from **OPEN** to **HALF-OPEN**, this package uses a **single-probe** approach — only one request is allowed to test the recovering service at a time. All other concurrent requests are rejected immediately until the probe completes.

```
OPEN (cooldown expired)
  │
  ├── Request A → probes service → success → CLOSED (all traffic resumes)
  ├── Request B → rejected (fail-fast)
  ├── Request C → rejected (fail-fast)
  └── ...

```

- If the probe **succeeds**, the circuit closes and normal traffic resumes.
- If the probe **fails**, the circuit re-opens and a new cooldown period begins.

**What your code receives when a request is rejected:**

- Via `run()` — returns a `CircuitResult` where `isSuccess()` and `isAvailable()` both return `false`
- Via `Http::withCircuitBreaker()` or Guzzle middleware — throws `RejectedException`

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

[](#configuration)

After publishing the config file, you can adjust these settings in `config/circuit-breaker.php`:

OptionDefaultDescription`enabled``true`Enable or disable the circuit breaker globally`defaults.failure_threshold``5`Number of failures before the circuit opens`defaults.cooldown_period``60`Seconds to wait before transitioning from OPEN to HALF-OPEN`defaults.success_threshold``1`Successful probes needed in HALF-OPEN to close the circuit`cache.ttl``86400`Cache entry lifetime in seconds`cache.prefix``circuit-breaker`Prefix for cache keys`cache.store``default`Laravel cache store to useYou can also override settings per service:

```
'services' => [
    'payment-service' => [
        'failure_threshold' => 10,
        'cooldown_period'   => 120,
        'success_threshold' => 3,
    ],
],
```

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

[](#contributing)

Thank you for considering contributing to the Circuit Breaker package! Please check the [CONTRIBUTING](CONTRIBUTING.md) file for more details.

License
-------

[](#license)

The Circuit Breaker package is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance86

Actively maintained with recent releases

Popularity33

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 93.2% 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 ~27 days

Total

17

Last Release

73d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/bfd15013ece7b7782813460af6ec7162ca0d9973cc0d9cf5ef3307f5afba0b5a?d=identicon)[Algo Younes](/maintainers/Algo%20Younes)

---

Top Contributors

[![algoyounes](https://avatars.githubusercontent.com/u/45436028?v=4)](https://github.com/algoyounes "algoyounes (68 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (5 commits)")

---

Tags

circuit-breakercircuit-breaker-patternlaravelresilienceresiliency-patternscircuit breakerlaravel-circuit-breakerphp-circuit-breaker

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[spatie/laravel-export

Create a static site bundle from a Laravel app

672139.5k6](/packages/spatie-laravel-export)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

43140.3k](/packages/harris21-laravel-fuse)[illuminate/auth

The Illuminate Auth package.

9327.9M1.2k](/packages/illuminate-auth)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45344.0k1](/packages/pressbooks-pressbooks)

PHPackages © 2026

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