Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Circuit Breaker Bundle Laravel Package

bizkit/circuit-breaker-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require bizkit/circuit-breaker-bundle
    

    Enable in config/bundles.php:

    return [
        // ...
        Bizkit\CircuitBreakerBundle\BizkitCircuitBreakerBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Add to config/packages/bizkit_circuit_breaker.yaml:

    bizkit_circuit_breaker:
        http_client: '@http_client'  # Default client to decorate
        cache_pool: 'cache.app'      # PSR-6 cache pool
        default_config:
            threshold: 5             # Failures before opening
            timeout: 30              # Seconds to stay open
            half_open_timeout: 60    # Seconds to test half-open state
            exceptions: [\Exception] # Exceptions to count as failures
    
  3. First Use Case Inject the decorated client into a service:

    use Symfony\Contracts\HttpClient\HttpClientInterface;
    
    class MyService {
        public function __construct(private HttpClientInterface $httpClient) {}
    
        public function fetchData() {
            $response = $this->httpClient->request('GET', 'https://api.example.com/data');
            return $response->toArray();
        }
    }
    

    The bundle automatically wraps requests with circuit breaker logic.


Implementation Patterns

Decorating Scoped Clients

Configure additional clients in config/packages/bizkit_circuit_breaker.yaml:

bizkit_circuit_breaker:
    http_clients:
        external_api:
            client: '@external_api_client'
            config:
                threshold: 3
                timeout: 60

Custom Exception Handling

Extend failure detection by overriding the exceptions config:

default_config:
    exceptions:
        - \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
        - \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
        - \App\Exception\CustomApiException

Event-Driven Workflows

Leverage Symfony’s event dispatcher (if installed) to react to circuit breaker states:

use Bizkit\CircuitBreakerBundle\Event\CircuitBreakerEvent;

class CircuitBreakerListener {
    public function onCircuitBreakerStateChange(CircuitBreakerEvent $event) {
        if ($event->isOpen()) {
            // Log or notify (e.g., Slack, Sentry)
            $this->logger->warning('Circuit breaker opened for: ' . $event->getClientId());
        }
    }
}

Register in config/services.yaml:

services:
    App\EventListener\CircuitBreakerListener:
        tags:
            - { name: kernel.event_listener, event: bizkit.circuit_breaker.state_change }

Dynamic Configuration

Override configurations per environment or dynamically:

// In a service
$container->get('bizkit_circuit_breaker.configurator')->configureClient(
    'external_api',
    ['threshold' => 10, 'timeout' => 120]
);

Gotchas and Tips

Debugging Circuit States

  • Inspect State: Use the bizkit_circuit_breaker.cache service to manually check states:
    $cache = $container->get('bizkit_circuit_breaker.cache');
    $state = $cache->getItem('http_client_'.md5('https://api.example.com'));
    
  • Clear Cache: Reset states for testing:
    php bin/console cache:clear bizkit_circuit_breaker
    

Configuration Quirks

  • Cache Key Collisions: Ensure unique keys for scoped clients by prefixing with client IDs (handled automatically).
  • Default Config Overrides: Scoped client configs override defaults. Explicitly set all values to avoid inheritance:
    http_clients:
        my_client:
            config:
                threshold: 5
                timeout: 30
                half_open_timeout: 60  # Required to override
    

Performance Tips

  • Cache Pool: Use a fast cache (e.g., cache.array_taggable) for development; switch to cache.redis or cache.apcu in production.
  • Timeouts: Set half_open_timeout longer than timeout to avoid rapid state fluctuations.

Extension Points

  • Custom Strategies: Extend Bizkit\CircuitBreakerBundle\Strategy\CircuitBreakerStrategy to implement custom logic (e.g., adaptive thresholds).
  • Cache Adapter: Replace the PSR-6 cache with a custom adapter by binding your own service to bizkit_circuit_breaker.cache.

Common Pitfalls

  • Ignored Exceptions: Ensure all expected failure exceptions are listed in exceptions; otherwise, they won’t trigger the breaker.
  • State Persistence: The cache must persist across requests (e.g., Redis, database). In-memory caches (like cache.array) will reset on restart.
  • Half-Open State: The first request after timeout enters the half-open state. If it fails, the circuit reopens immediately. Design retry logic accordingly.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings
coleus/apps
seampact/laravel
emmyconceptng/laravel-ng-postcode
jjsquady/round-robin