Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

ganesha

> DevOps
Open source

:elephant: A Circuit Breaker pattern implementation for PHP applications.

668 stars0 likes2 views
WebsiteGitHub

About

:elephant: A Circuit Breaker pattern implementation for PHP applications.

Ganesha

Ganesha is PHP implementation of Circuit Breaker pattern which has multi strategies to avoid cascading failures and supports various storages to record statistics.

This is one of the Circuit Breaker implementations in PHP that is actively developed, production-ready, well-tested and well-documented. :muscle: You can easily integrate Ganesha into your existing code base, as Ganesha provides just simple interfaces and Guzzle Middleware behaves transparency.

Table of contents

  • Ganesha
  • Table of contents
  • Are you interested?
  • Unveil Ganesha
  • Usage
  • Strategies
  • Adapters
  • Customizing storage keys
  • Ganesha :heart: Guzzle
  • Ganesha :heart: OpenAPI Generator
  • Ganesha :heart: Symfony HttpClient
  • Companies using Ganesha :rocket:
  • The articles/videos Ganesha loves :sparkles: :elephant: :sparkles:
  • Run tests
  • Requirements
  • Build promotion site with Soushi
  • Author

Are you interested?

Here is an example which shows you how Ganesha behaves when a failure occurs.
It is easily executable. All you need is Docker.

Unveil Ganesha

bash
# Install Composer
$ curl -sS https://getcomposer.org/installer | php

# Run the Composer command to install the latest version of Ganesha
$ php composer.phar require ackintosh/ganesha

Usage

Ganesha provides following simple interfaces. Each method receives a string (named $service in example) to identify the service. $service will be the service name of the API, the endpoint name, etc. Please remember that Ganesha detects system failure for each $service.

php
$ganesha->isAvailable($service);
$ganesha->success($service);
$ganesha->failure($service);
…

Three states of circuit breaker

(martinfowler.com : CircuitBreaker)

Ganesha follows the states and transitions described in the article faithfully. $ganesha->isAvailable() returns true if the circuit states on Closed, otherwise it returns false.

Subscribe to events in ganesha

  • When the circuit state transitions to Open the event Ganesha::EVENT_TRIPPED is triggered
  • When the state back to Closed the event Ganesha::EVENT_CALMED_DOWN is triggered
…

Disable

If disabled, Ganesha keeps to record success/failure statistics, but Ganesha doesn't trip even if the failure count reached to a threshold.

php
// Ganesha with Count strategy(threshold `3`).
// $ganesha = Ackintosh\Ganesha\Builder::withCountStrategy() ...

// Disable
Ackintosh\Ganesha::disable();

// Although the failure is recorded to storage,
$ganesha->failure($service);
$ganesha->failure($service);
$ganesha->failure($service);

// Ganesha does not trip and Ganesha::isAvailable() returns true.
var_dump($ganesha->isAvailable($service));
// bool(true)

Reset

Resets the statistics saved in a storage.

php
$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
    // ...
    ->build();

$ganesha->reset();

Strategies

Ganesha has two strategies which avoids cascading failures.

Rate

…

Note about "time window": The Storage Adapter implements either SlidingTimeWindow or TumblingTimeWindow. The difference of the implementation comes from constraints of the storage functionalities.

[SlidingTimeWindow]

  • SlidingTimeWindow implements a time period that stretches back in time from the present. For instance, a SlidingTimeWindow of 30 seconds includes any events that have occurred in the past 30 seconds.
  • Redis adapter and MongoDB adapter implements SlidingTimeWindow.

The details to help us understand visually is shown below:
(quoted from Introduction to Stream Analytics windowing functions - Microsoft Azure)

[TumblingTimeWindow]

  • TumblingTimeWindow implements time segments, which are divided by a value of timeWindow.
  • APCu adapter and Memcached adapter implement TumblingTimeWindow.

The details to help us understand visually is shown below:
(quoted from Introduction to Stream Analytics windowing functions - Microsoft Azure)

Count

If you prefer the Count strategy use Builder::withCountStrategy() to build an instance.

…

Adapters

APCu

The APCu adapter requires the APCu extension.

php
$adapter = new Ackintosh\Ganesha\Storage\Adapter\Apcu();

$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
    ->adapter($adapter)
    // ... (omitted) ...
    ->build();

Note: APCu is internal to each server/instance, not pooled like most Memcache and Redis setups. Each worker's circuit breaker will activate or reset individually, and failure thresholds should be set lower to compensate.

Redis

Redis adapter requires phpredis or Predis client instance. The example below is using phpredis.

php
$redis = new \Redis();
$redis->connect('localhost');
$adapter = new Ackintosh\Ganesha\Storage\Adapter\Redis($redis);

$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
    ->adapter($adapter)
    // ... (omitted) ...
    ->build();

Memcached

Memcached adapter requires memcached (NOT memcache) extension.

php
$memcached = new \Memcached();
$memcached->addServer('localhost', 11211);
$adapter = new Ackintosh\Ganesha\Storage\Adapter\Memcached($memcached);

$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
    ->adapter($adapter)
    // ... (omitted) ...
    ->build();

MongoDB

MongoDB adapter requires mongodb extension.

php
$manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017/');
$adapter = new Ackintosh\Ganesha\Storage\Adapter\MongoDB($manager, 'dbName', 'collectionName');

$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
    ->adapter($adapter)
    // ... (omitted) ...
    ->build();

Customizing storage keys

If you want to customize the keys to be used when storing circuit breaker information, set an instance which implements StorageKeysInterface.

php
class YourStorageKeys implements StorageKeysInterface
{
    public function prefix()
    {
        return 'your_prefix_';
    }

    // ... (omitted) ...
}

$ganesha = Ackintosh\Ganesha\Builder::withRateStrategy()
    // The keys which will stored by Ganesha to the storage you specified via `adapter`
    // will be prefixed with `your_prefix_`.
    ->storageKeys(new YourStorageKeys())
    // ... (omitted) ...
    ->build();

Ganesha :heart: Guzzle

If you are using Guzzle (v6 or higher), Guzzle Middleware powered by Ganesha makes it easy to integrate Circuit Breaker to your existing code base.

…

How does Guzzle Middleware determine the $service?

As documented in Usage, Ganesha detects failures for each $service. Below, We will show you how Guzzle Middleware determine $service and how we specify $service explicitly.

By default, the host name is used as $service.

php
// In the example above, `api.example.com` is used as `$service`.
$client->get('http://api.example.com/awesome_resource');

You can also specify $service via a option passed to client, or request header. If both are specified, the option value takes precedence.

…

Alternatively, you can apply your own rules by implementing a class that implements the ServiceNameExtractorInterface.

…

How does Guzzle Middleware determine the failure?

By default, if the next handler promise is fulfilled ganesha will consider it a success, and a failure if it is rejected.

You can implement your own rules on fulfilled response by passing an implementation of FailureDetectorInterface to the middleware.

php
use Ackintosh\Ganesha\GuzzleMiddleware\FailureDetectorInterface;
use Psr\Http\Message\ResponseInterface;

class HttpStatusFailureDetector implements FailureDetectorInterface
{
    public function isFailureResponse(ResponseInterface $response) : bool
    {
        return in_array($response->getStatusCode(), [503, 504], true);
    }
}

// ---
$ganesha = Builder::withRateStrategy()
    // ...
    ->build();
$middleware = new GuzzleMiddleware(
    $ganesha,
    // Pass the failure detector to the GuzzleMiddleware constructor.
    failureDetector: new HttpStatusFailureDetector()
);

Ganesha :heart: OpenAPI Generator

PHP client generated by OpenAPI Generator is using Guzzle as HTTP client and as we mentioned as Ganesha :heart: Guzzle, Guzzle Middleware powered by Ganesha is ready. So it is easily possible to integrate Ganesha and the PHP client generated by OpenAPI Generator in a smart way as below.

php
// For details on how to build middleware please see https://github.com/ackintosh/ganesha#ganesha-heart-guzzle
$middleware = new GuzzleMiddleware($ganesha);

// Set the middleware to HTTP client.
$handlers = HandlerStack::create();
$handlers->push($middleware);
$client = new Client(['handler' => $handlers]);

// Just pass the HTTP client to the constructor of API class.
$api = new PetApi($client);

try {
    // Ganesha is working in the shadows! The result of api call is monitored by Ganesha.
    $api->getPetById(123);
} catch (RejectedException $e) {
    awesomeErrorHandling($e);
}

Ganesha :heart: Symfony HttpClient

If you are using Symfony HttpClient, GaneshaHttpClient makes it easy to integrate Circuit Breaker to your existing code base.

…

How does GaneshaHttpClient determine the $service?

As documented in Usage, Ganesha detects failures for each $service. Below, We will show you how GaneshaHttpClient determine $service and how we specify $service explicitly.

By default, the host name is used as $service.

php
// In the example above, `api.example.com` is used as `$

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPcircuit-breakercircuit-breaker-patternfault-toleranceguzzle

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
CategoryDevOps
PricingOpen source

> Related tools

D
Docker
容器化平台,标准化应用交付
G
GitHub Actions
GitHub 原生 CI/CD 工作流
N
Nginx
高性能 Web 服务器与反向代理