Circuit Breaker Pattern with Redis in Laravel: Shielding External APIs from Cascading Failures
Circuit Breaker Pattern with Redis in Laravel: Shielding External APIs from Cascading Failures
Every developer who has integrated third-party APIs knows the pain. One slow or unresponsive service can turn your application into a sluggish mess. Requests pile up, threads hang, and before you know it, your entire application is on its knees. This is where the circuit breaker pattern becomes your lifeline.
In this post, I will show you how to build a robust circuit breaker using Redis and Laravel. This approach has saved my applications numerous times, and it can do the same for yours.
Understanding the Circuit Breaker Pattern
The circuit breaker pattern is a resilience design pattern that prevents cascading failures in distributed systems. Think of it like an electrical circuit breaker in your home. When the current exceeds safe levels, the breaker trips, cutting off electricity and preventing fires.
In software, the circuit breaker monitors calls to external services and fails fast when it detects problems. Instead of waiting for timeouts that propagate through your system, the breaker immediately returns an error or fallback response.
The circuit breaker operates in three states:
- Closed: Everything works normally. Requests pass through to the external service.
- Open: Too many failures detected. Requests are immediately blocked with a fast failure.
- Half-Open: After a timeout, a limited number of test requests are allowed through to check if the service recovered.
Why Redis for Circuit Breaker State?
You might wonder why we need Redis when we could store state in memory or a database. Here is why Redis excels for this use case:
- Speed: Sub-millisecond latency for state checks, critical for fail-fast behavior
- Atomic operations: Redis Lua scripts ensure thread-safe state transitions
- Expiration: Built-in TTL automatically handles recovery timeouts
- Shared state: Works across multiple application servers in a distributed setup
- No race conditions: Atomic increments and conditional updates prevent state corruption
Building the Circuit Breaker
Step 1: Configuration
Start by defining your circuit breaker settings in a configuration file. This makes your implementation flexible across different services.
<?php
// config/circuit-breaker.php
return [
'default' => [
'failure_threshold' => 5,
'success_threshold' => 3,
'timeout_duration' => 30, // seconds
'half_open_max_calls' => 2,
],
'services' => [
'payment_gateway' => [
'failure_threshold' => 3,
'timeout_duration' => 60,
],
'inventory_api' => [
'failure_threshold' => 10,
'timeout_duration' => 15,
],
],
];
Step 2: The Core Circuit Breaker Class
Here is the heart of our implementation. This class manages state transitions and provides a clean API for your application code.
<?php
namespace App\Services;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;
class CircuitBreaker
{
private string $name;
private array $config;
public function __construct(string $name)
{
$this->name = $name;
$this->config = array_merge(
config('circuit-breaker.default'),
config("circuit-breaker.services.{$name}", [])
);
}
public function call(callable $callback, ?callable $fallback = null)
{
$state = $this->getState();
if ($state === 'open') {
if ($this->shouldAttemptReset()) {
$this->transitionToHalfOpen();
$state = 'half-open';
} else {
Log::warning("Circuit breaker '{$this->name}' is OPEN. Failing fast.");
return $fallback ? $fallback() : $this->defaultFallback();
}
}
if ($state === 'half-open') {
$halfOpenCalls = $this->getHalfOpenCalls();
if ($halfOpenCalls >= $this->config['half_open_max_calls']) {
return $fallback ? $fallback() : $this->defaultFallback();
}
$this->incrementHalfOpenCalls();
}
try {
$result = $callback();
$this->recordSuccess();
return $result;
} catch (\Throwable $exception) {
$this->recordFailure();
if ($fallback) {
return $fallback();
}
throw $exception;
}
}
private function getState(): string
{
return Redis::get($this->stateKey()) ?: 'closed';
}
private function shouldAttemptReset(): bool
{
$openedAt = (int) Redis::get($this->openedAtKey());
return (time() - $openedAt) >= $this->config['timeout_duration'];
}
private function recordSuccess(): void
{
$state = $this->getState();
if ($state === 'half-open') {
$successes = Redis::incr($this->halfOpenSuccessKey());
if ($successes >= $this->config['success_threshold']) {
$this->transitionToClosed();
}
} else {
Redis::del($this->failureCountKey());
}
}
private function recordFailure(): void
{
Redis::incr($this->failureCountKey());
Redis::expire($this->failureCountKey(), 60);
$failures = (int) Redis::get($this->failureCountKey());
if ($failures >= $this->config['failure_threshold']) {
$this->transitionToOpen();
}
}
private function transitionToOpen(): void
{
Redis::set($this->stateKey(), 'open');
Redis::set($this->openedAtKey(), time());
Redis::del(
$this->failureCountKey(),
$this->halfOpenCallsKey(),
$this->halfOpenSuccessKey()
);
Log::error("Circuit breaker '{$this->name}' transitioned to OPEN");
}
private function transitionToHalfOpen(): void
{
Redis::set($this->stateKey(), 'half-open');
Redis::del($this->halfOpenCallsKey(), $this->halfOpenSuccessKey());
Log::info("Circuit breaker '{$this->name}' transitioned to HALF-OPEN");
}
private function transitionToClosed(): void
{
Redis::del(
$this->stateKey(),
$this->failureCountKey(),
$this->halfOpenCallsKey(),
$this->halfOpenSuccessKey(),
$this->openedAtKey()
);
Log::info("Circuit breaker '{$this->name}' transitioned to CLOSED");
}
private function incrementHalfOpenCalls(): void
{
Redis::incr($this->halfOpenCallsKey());
}
private function getHalfOpenCalls(): int
{
return (int) Redis::get($this->halfOpenCallsKey());
}
private function defaultFallback()
{
throw new \RuntimeException(
"Service '{$this->name}' is unavailable. Circuit breaker is open."
);
}
// Redis key helpers
private function stateKey(): string { return "cb:{$this->name}:state"; }
private function failureCountKey(): string { return "cb:{$this->name}:failures"; }
private function openedAtKey(): string { return "cb:{$this->name}:opened_at"; }
private function halfOpenCallsKey(): string { return "cb:{$this->name}:half_open_calls"; }
private function halfOpenSuccessKey(): string { return "cb:{$this->name}:half_open_success"; }
}
Step 3: Integration with Your Service Layer
Now let us see how to use this circuit breaker in a real service that calls an external payment API.
<?php
namespace App\Services;
use App\Exceptions\PaymentException;
use Illuminate\Support\Facades\Http;
class PaymentGatewayService
{
private CircuitBreaker $circuitBreaker;
public function __construct()
{
$this->circuitBreaker = new CircuitBreaker('payment_gateway');
}
public function processPayment(array $paymentData): array
{
return $this->circuitBreaker->call(
function () use ($paymentData) {
$response = Http::timeout(5)
->withHeaders(['Authorization' => 'Bearer ' . config('services.payment.key')])
->post('https://api.payment-provider.com/v2/charges', $paymentData);
if (!$response->successful()) {
throw new PaymentException("Payment API returned: " . $response->status());
}
return $response->json();
},
function () {
// Graceful degradation: queue for offline processing
dispatch(new ProcessPaymentOffline($paymentData));
return [
'status' => 'queued',
'message' => 'Payment queued for processing due to service unavailability',
'reference' => 'QUEUE-' . uniqid(),
];
}
);
}
}
Step 4: Handling Multiple Services with Facades
For larger applications, you might want a more Laravel-native approach. Here is a service provider and facade setup.
<?php
namespace App\Providers;
use App\Services\CircuitBreaker;
use Illuminate\Support\ServiceProvider;
class CircuitBreakerServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->bind('circuit-breaker', function ($app) {
return new class {
public function for(string $name): CircuitBreaker
{
return new CircuitBreaker($name);
}
};
});
}
}
<?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static \App\Services\CircuitBreaker for(string $name)
*/
class CircuitBreaker extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'circuit-breaker';
}
}
Usage then becomes clean and expressive:
use App\Facades\CircuitBreaker;
$result = CircuitBreaker::for('inventory_api')->call(
fn() => $this->fetchInventory($productId),
fn() => ['stock' => 0, 'cache' => true] // return cached or safe default
);
Monitoring and Observability
A circuit breaker without visibility is dangerous. You need to know when it trips and why. Extend your implementation with metrics publishing.
private function publishMetrics(string $event): void
{
Redis::lpush('cb:metrics', json_encode([
'circuit' => $this->name,
'event' => $event,
'timestamp' => now()->toIso8601String(),
]));
// Also emit to Laravel events for dashboards
event(new CircuitBreakerStateChanged($this->name, $event));
}
Create artisan commands to inspect circuit health:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class CircuitBreakerStatus extends Command
{
protected $signature = 'circuit-breaker:status {name?}';
public function handle(): void
{
if ($this->argument('name')) {
$this->showCircuit($this->argument('name'));
return;
}
$keys = Redis::keys('cb:*:state');
foreach ($keys as $key) {
$name = explode(':', $key)[1];
$this->showCircuit($name);
}
}
private function showCircuit(string $name): void
{
$state = Redis::get("cb:{$name}:state") ?: 'closed';
$failures = Redis::get("cb:{$name}:failures") ?: 0;
$openedAt = Redis::get("cb:{$name}:opened_at");
$this->info("Circuit: {$name}");
$this->line(" State: {$state}");
$this->line(" Recent failures: {$failures}");
if ($openedAt) {
$elapsed = time() - (int) $openedAt;
$this->line(" Open for: {$elapsed}s");
}
$this->newLine();
}
}
Production Considerations
Before deploying your circuit breaker, consider these critical points:
- Threshold tuning: Start with higher thresholds and adjust based on observed behavior. Too sensitive causes unnecessary outages; too lenient defeats the purpose.
- Redis availability: If Redis fails, your circuit breaker fails. Use Redis Sentinel or Cluster for high availability.
- Request context: Consider different thresholds for read versus write operations. Failed writes might need queuing; failed reads can use stale cache.
- Testing: Use tools like Toxiproxy to simulate network failures in your test suite.
- Gradual rollout: Deploy circuit breakers in shadow mode first, logging what would happen without actually blocking requests.
Conclusion
The circuit breaker pattern, implemented with Redis in Laravel, transforms how your application handles external service failures. Instead of cascading timeouts and thread exhaustion, you get predictable failure behavior with opportunities for graceful degradation.
The implementation I have shown gives you full control over state transitions, configurable per-service thresholds, and clean integration with your existing service layer. Start with one critical external dependency, observe how it behaves under real failure conditions, and expand from there.
Remember: resilience is not about preventing all failures. It is about failing in controlled ways that protect your system and your users.