Weave Code
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

Php Circuit Breaker Laravel Package

ejsmont-artur/php-circuit-breaker

Laravel-friendly PHP circuit breaker implementation to add resiliency to external service calls. Supports configurable failure thresholds, timeouts and recovery, helping prevent cascading failures when APIs or dependencies are down or slow.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Resilience Pattern Alignment: The Circuit Breaker pattern is a natural fit for Laravel applications requiring fault tolerance, particularly in microservices, external API integrations, or database-heavy workflows. It aligns with Laravel’s service container and dependency injection principles, enabling clean integration into existing middleware, service layers, or queue jobs.
  • Use Cases:
    • External API Calls: Mitigate cascading failures when calling third-party services (e.g., payment gateways, SaaS APIs).
    • Database Operations: Protect critical queries (e.g., payment processing, inventory updates) from overloading or failing databases.
    • Queue Workers: Prevent retries from overwhelming failed jobs (e.g., email services, webhooks).
    • Legacy System Interactions: Safeguard interactions with unreliable legacy systems.
  • Laravel Synergy: Works seamlessly with Laravel’s events, tasks, and HTTP clients (e.g., HttpClient facade). Can be wrapped around repositories, services, or controllers without invasive changes.

Integration Feasibility

  • Low Coupling: The package is stateless (configurable via constructor) and dependency-injected, making it easy to plug into Laravel’s service container. No need for global state or monolithic configuration.
  • Middleware Support: Can be implemented as Laravel middleware to protect HTTP routes (e.g., API endpoints calling external services).
  • Queue Job Wrapping: Can be applied to queue jobs via job middleware or by wrapping the job’s handle() method.
  • Service Layer Integration: Ideal for repositories or services that interact with external systems (e.g., PaymentService, ThirdPartyApiClient).
  • Event Listeners: Can be used to wrap event handlers that trigger external actions (e.g., OrderShipped event calling a shipping API).

Technical Risk

Risk Area Assessment Mitigation Strategy
State Management The package relies on in-memory state (open/half-open/closed) by default. In distributed environments (e.g., Laravel Forge + multiple servers), this could lead to inconsistent states. Use Redis or database-backed state storage (e.g., via php-circuit-breaker’s StateStorageInterface). Laravel’s cache() facade can also be adapted for persistence.
Configuration Complexity Overly granular configurations (e.g., per-endpoint timeouts) may require boilerplate setup. Leverage Laravel config files (config/circuit-breakers.php) to centralize settings. Use dependency injection to pass configurations dynamically.
Observability Gaps Default implementation lacks metrics (e.g., Prometheus) or logging hooks. Integrate with Laravel’s logging (Log::channel()) or monitoring tools (e.g., Datadog, New Relic) via custom state listeners.
Testing Overhead Testing circuit breaker states (e.g., "half-open") requires mocking time and simulating failures, which can be cumbersome. Use Laravel’s testing helpers (e.g., travel() for time manipulation) and Pest/PHPUnit to assert state transitions.
Performance Overhead Circuit breaker checks add minimal latency (~1–5ms per call), but high-throughput systems may need optimization. Benchmark in staging. For ultra-low-latency paths, consider bypassing the breaker for internal-only calls.

Key Questions

  1. State Persistence:
    • Will the circuit breaker run in a distributed environment (e.g., multiple Laravel instances)? If yes, how will state be shared (Redis, DB, etc.)?
  2. Granularity Needs:
    • Should circuit breakers be per-endpoint (e.g., stripe-api, payment-service) or global (e.g., all external calls)?
  3. Fallback Strategies:
    • What fallback behaviors are needed when the circuit is open (e.g., return cached data, queue retry, notify admin)?
  4. Monitoring:
    • How will circuit breaker states and failures be monitored (e.g., Laravel Horizon, custom dashboard)?
  5. Integration Points:
    • Where in the stack should it be applied first? (e.g., HTTP middleware, service layer, or repository level)
  6. Testing Strategy:
    • How will failure scenarios (e.g., circuit open/half-open) be tested in CI/CD?
  7. Dependency Conflicts:
    • Could this conflict with existing retry libraries (e.g., laravel-retryable) or queue drivers?

Integration Approach

Stack Fit

Laravel Component Integration Strategy Example Implementation
HTTP Client Wrap HttpClient calls (e.g., Http::post()) with the circuit breaker. ```php
use EjsmontArtur\CircuitBreaker\CircuitBreaker;
use Illuminate\Support\Facades\Http;

$breaker = new CircuitBreaker( fn() => Http::post('https://api.example.com/pay'), config('circuit-breakers.payment_timeout') ); $response = $breaker->execute();

| **Middleware**              | Create a **Laravel middleware** to protect API routes calling external services.                                                                                                                               | ```php
public function handle(Request $request, Closure $next) {
    $breaker = new CircuitBreaker(
        fn() => $next($request),
        config('circuit-breakers.api_timeout')
    );
    return $breaker->execute();
}
```                                                                                                                                                                                                                     |
| **Queue Jobs**              | Wrap job `handle()` methods or use **job middleware**.                                                                                                                                                           | ```php
// In job middleware
public function handle($job, Closure $next) {
    $breaker = new CircuitBreaker(
        fn() => $next($job),
        config('circuit-breakers.job_timeout')
    );
    return $breaker->execute();
}
```                                                                                                                                                                                                                     |
| **Service Layer**           | Inject the circuit breaker into **services** (e.g., `PaymentService`).                                                                                                                                       | ```php
class PaymentService {
    public function __construct(
        private CircuitBreaker $stripeBreaker
    ) {}

    public function charge(ChargeRequest $request) {
        return $this->stripeBreaker->execute(
            fn() => Stripe::charges()->create($request->toArray())
        );
    }
}
```                                                                                                                                                                                                                     |
| **Repositories**            | Protect **database-heavy operations** (e.g., bulk inserts) that may fail under load.                                                                                                                               | ```php
class UserRepository {
    public function __construct(
        private CircuitBreaker $dbBreaker
    ) {}

    public function bulkCreate(array $users) {
        return $this->dbBreaker->execute(
            fn() => DB::table('users')->insert($users)
        );
    }
}
```                                                                                                                                                                                                                     |
| **Event Listeners**         | Safeguard **event handlers** that trigger external actions.                                                                                                                                                   | ```php
public function handle(OrderShipped $event) {
    $breaker = new CircuitBreaker(
        fn() => $this->shippingApi->notify($event->order),
        config('circuit-breakers.shipping_timeout')
    );
    $breaker->execute();
}
```                                                                                                                                                                                                                     |

### **Migration Path**
1. **Phase 1: Pilot Integration**
   - Start with **non-critical external APIs** (e.g., analytics, logging).
   - Implement **middleware-based protection** for API routes.
   - Validate state persistence (Redis/DB) in staging.

2. **Phase 2: Service Layer Adoption**
   - Refactor **services** (e.g., `PaymentService`, `ThirdPartyApi`) to use circuit breakers.
   - Add **fallback logic** (e.g., cached responses, admin alerts).

3. **Phase 3: Queue & Job Protection**
   - Apply to **high-failure-rate jobs** (e.g., webhook retries, email sends).
   - Monitor **queue backlogs** to ensure breakers aren’t masking deeper issues.

4. **Phase 4: Observability & Optimization**
   - Integrate with **Laravel monitoring** (e.g., Horizon, Sentry).
   - Tune **timeout thresholds** based on real-world latency data.

### **Compatibility**
| **Compatibility Factor**    | **Assessment**                                                                                                                                                                                                 | **Workaround**                                                                                                                                                                                                 |
|-----------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Laravel Version**         | Works with **Laravel 8+** (PHP 7.4+).                                                                                                                                                                   | For
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle