Laravel 8 Circuit Breaker Pattern Tutorial with Example

Last updated on: by Editorial Team

Laravel 8 circuit breaker pattern tutorial; In this tutorial, we will see how to work with the laravel circuit breaker pattern; the Circuit breaker pattern is an extensively helpful design pattern particularly used in software development to restrict remote calls against unresponsive services.

Here is what Wikipedia says about circuit breaker pattern:

The circuit breaker is a design pattern used in 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.

This http circuit breaker pattern in laravel consists of a straightforward idea. We will show you how to create a function that contains a circuit breaker object which tracks the failures and throw errors when reached a certain threshold.

HTTP Request without Circuit Breaker Pattern

Generically, you use the following method to make HTTP the request in laravel. In the following code snippet, we created an index() function, defined the API endpoint, and taking the response in the dd() method.

<?php
    
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
    
class CrudController extends Controller
{
  
    public function index()
    {
        $req = Http::get('https://domain.com/api');
        $response = json_decode($req->body());
  
        dd($response);
    }
    
}

Circuit Breaker Pattern with timeout()

In the previous example, we described the approach that is not considered the best, fret not; in the subsequent step, we are using the timeout() method and limiting the HTTP requests.

Seldom, the api is not working, or api server is down; in that case, it will throw an error for the specified time.

<?php
    
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
    
class CrudController extends Controller
{
  
    public function index()
    {
        $req = Http::timeout(12)->get('https://domain.com/api');
        $response = json_decode($req->body());
  
        dd($response);
    }
    
}

Laravel Circuit Breaker Pattern Example

Laravel 8 comes with all the required packages needed for setting up circuit breaker patterns in laravel.

You have to add Exception, RateLimiter, HTTP Facade, and Request.

We can now use Laravel rate limiter and prevent laravel service from making a request to the unresponsive API for a specific amount of time.

Before making any further request, the circuit breaker pattern is ensuring how many failed attempts have been made. And not making the HTTP call for a particular time if the defined threshold has been passed.

<?php
    
namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Exception;
use Illuminate\Cache\RateLimiter;
use Illuminate\Support\Facades\Http;
  
class CrudController extends Controller
{

    public function index()
    {
        $limiter = app(RateLimiter::class);
        $actionKey = 'crud_name';
        $threshold = 6;
  
        try {

            if ($limiter->tooManyAttempts($actionKey, $threshold)) {
                return $this->failOrFallback();
            }
            $req = Http::timeout(4)->get('https://domain.com/api');
            $res = json_decode($req->body());
    
            dd($res);

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

}

The Laravel Circuit breaker pattern tutorial is over; we assume you liked this example and share it with others.