Hello Artisan
In this tutorial i will explain circuit breaker design pattern in Laravel applications and also i will share some code that how we can use circuit breaker design pattern. 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. - Wikipedia
Circuit breaker is a design pattern that prevents request execution against unresponsive services.You will be happy to know that Laravel 7.x ships with all the ingredients needed to build a circuit breaker
Let's see some example of circuit breaker. Before the circuit breaker pattern our application looked something like this:
$response = Http::get('https://fake-search-service.com/api/v1/search?q=Laravel');
return view('articles.index', ['articles' => $response->body()];
The HTTP client will wait for a couple of seconds before throwing an exception to us so it’s a good practice to always define timeout for our requests. Luckily Laravel's client comes with a handy method to define the timeout of our request.
$response = Http::timeout(2)->get('https://fake-search-service.com/api/v1/search?q=Laravel');
return view('articles.index', ['articles' => $response->body()];
Okey, all are fine but we are still not preventing our service to make a request to the unresponsive API.
$limiter = app(RateLimiter::class);
$actionKey = 'search_service';
$threshold = 10;
try {
if ($limiter->tooManyAttempts($actionKey, $threshold)) {
// Exceeded the maximum number of failed attempts.
return $this->failOrFallback();
}
$response = Http::timeout(2)->get('https://fake-search-service.com/api/v1/search?q=Laravel');
return view('articles.index', ['articles' => $response->body()]);
} catch (\Exception $exception) {
$limiter->hit($actionKey, Carbon::now()->addMinutes(15));
return $this->failOrFallback();
}
By using Laravel's RateLimiter you can count the failed attempts performed to the search API $limiter->hit($actionKey, Carbon::now()->addMinutes(15))
.
By counting those attempts you can prevent our application from making any more requests to this API for a certain amount of time.
Before every request, we check if there are too many failed attempts $limiter->tooManyAttempts($actionKey, $threshold)
and if the failed attempts have passed our threshold we will prevent our service to request the search API for 15 minutes.
Now you can use this method in your application. Hope it will helpfull for you.
#design-pattern #circuit-breaker #laravel