How to use Circuit Breaker Pattern in Laravel 9?

May 05, 2022 . Admin

Hi Guys,

In this tutorial, I am going to learn you how to use circuit breaker pattern in laravel 9 application. We will show circuit breaker pattern in laravel 9 app. I will teach you use of circuit breaker pattern in laravel 9.

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.

Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Without using Circuit Breaker
<?php

use Illuminate\Support\Facades\Http;

/**
 * Write code on Method
 *
 * @return response()
 */
public function index()
{
    $response = Http::timeout(5)->get('https://jsonplaceholder.typicode.com/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:

Using Circuit Breaker
<?php

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

/**
 * Write code on Method
 *
 * @return response()
 */
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://jsonplaceholder.typicode.com/users');
        $content = json_decode($response->body());

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

It will help you...

#Laravel 9