How to Use Circuit Breaker Pattern in Laravel 8 ?

10-Apr-2023

.

Admin

How to Use Circuit Breaker Pattern in Laravel 8 ?

Hi Guys,

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

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.

Without using Circuit Breaker


use Illuminate\Support\Facades\Http;

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

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://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 8

#Laravel