How to Use Circuit Breaker Pattern in Laravel

Today we’ll talk about & setup circuit breaker pattern in Laravel. Let’s begin:

Table of Contents

  1. Circuit Breaker Pattern
  2. Use in Laravel

Circuit Breaker Pattern

According to Wikipedia, “The circuit breaker is a design pattern used in modern software development. It is used to detect failures and encapsulates the logic of preventing a failure from constantly recurring, during maintenance, temporary external system failure or unexpected system difficulties.”
To know more about the circuit breaker pattern, please read this article.

Use in Laravel

Before using circuit breaker, let’s see an example of normal usage:

use Illuminate\Support\Facades\Http;

public function index()
{
    $response = Http::get('https://example.app/api/users');
    $content = json_decode($response->body());

    dd($content);
}

It’s not good practice. We should alway set timeout like:

use Illuminate\Support\Facades\Http;

public function index()
{
    $response = Http::timeout(5)->get('https://example.app/api/users');
    $content = json_decode($response->body());

    dd($content);
}

The timeout(5) means, the HTTP client will stop requesting the API after 5 seconds and will throw an exception.

Now it is okay but still not preventing our service to make a request to the API. So, the solution is:

use Illuminate\Cache\RateLimiter;
use Illuminate\Support\Facades\Http;

public function index()
{
    $limiter = app(RateLimiter::class);
    $actionKey = 'service_name';
    $threshold = 5;

    try {
        if ($limiter->tooManyAttempts($actionKey, $threshold)) {
            // Exceeded the maximum number of failed attempts.
            return $this->failOrFallback();
        }
        $response = Http::timeout(2)->get('https://example.app/api/users');
        $content = json_decode($response->body());

        dd($content);
    } catch (\Exception $exception) {
        $limiter->hit($actionKey, Carbon::now()->addMinutes(10));
        return $this->failOrFallback();
    }
}

By this way we can prevent our application from making any more requests to this API for a certain amount of time.

That’s all. Thanks for reading. ?