AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 6.x

    • Release Notes
    • Upgrade Guide
    • New to this...
    • Contribution Guide
    • Security Policy
    • Code of Conduct
    • Origin
  • ACL

    • Introduction
    • How to install
    • Setup
    • Permissions
    • Roles
    • Users
    • Cached Permissions
  • Audit

    • Audit
    • How to install
    • Setup
    • Recording
    • Events
  • Circuits

    • Circuits
    • How to install
    • Setup
    • Usage
    • Events
  • Collections

    • Collections
    • How to install
    • Summation

      • Summation Collection
      • Items Processor
  • Config

    • Configuration Loader
    • How to install
    • Setup
    • Load Configuration Files
    • Custom File Parsers
  • Console

    • Command and Schedule Registration
    • How to install
    • Setup
    • Commands
    • Schedules
  • Container

    • IoC Service Container
    • How to install
    • Container
    • List Resolver
  • Core

    • Athenaeum Core Application
    • How to install
    • Setup
    • Usage

      • Configuration
      • Service Providers
      • Service Container
      • Events
      • Caching
      • Logging
      • Console
      • Task Scheduling
      • Exception Handling
      • Extending Core Application
      • Testing
  • Database

    • Introduction
    • How to install
    • Models

      • Instantiatable
      • Sluggable
    • Query

      • Criteria (Query Filter)
  • Dto

    • Data Transfer Object (DTO)
    • How to install
    • Create Interface
    • Implement DTO
    • How to use
    • Populate
    • Export
    • Json
    • Serialization
    • Nested DTOs
    • Array DTO
  • ETags

    • ETags
    • How to install
    • Setup
    • Usage
    • Generators

      • Default Generator
      • Custom Generator
    • Eloquent Models
    • Macros
  • Events

    • Register Listeners and Subscribers
    • How to install
    • Setup
    • Listeners
    • Subscribers
  • Filters

    • Search Filter Utilities
    • Prerequisites
    • How to install
    • Setup
    • Processor
    • Filters Builder
    • Predefined Resources

      • Search Processor
      • Sorting Processor
      • Constraints Processor
      • Matching Processor
    • Tip: Create a base builder
  • Flysystem

    • Introduction
    • Database Adapter

      • Introduction
      • How to install
      • Setup
      • Data Deduplication
      • MIME-Type Detection
  • Http

    • Api

      • Http API
      • How to install
      • Setup
      • Resources

        • Introduction
        • Timestamps
        • Self-Link
        • Relations
        • Registrar
      • Middleware

        • Introduction
        • Request Must Be Json
        • Capture Fields To Select
    • Clients

      • Http Clients
      • How to install
      • Setup
      • Basic Usage
      • Available Methods

        • Fluent Api
        • Protocol Version
        • Base Uri
        • Http Method and Uri
        • Headers
        • Accept & Content-Type
        • Authentication
        • Http Query
        • Payload Format
        • Payload
        • Attachments
        • Cookies
        • Response Expectations
        • Middleware
        • Conditions
        • Criteria
        • Redirects
        • Timeout
        • Debugging
        • Logging
        • Driver Options
        • Driver
      • Http Query Builder

        • Introduction
        • Select
        • Where
        • Dates
        • Include
        • Pagination
        • Sorting
        • Raw Expressions
        • Custom Grammar
    • Cookies

      • Http Cookies
      • How to install
      • Usage
    • Messages

      • Http Messages
      • How to install
      • Serializers
  • Maintenance

    • Modes

      • Maintenance Modes
      • How to install
      • Setup
      • Basic Usage
      • Available Drivers
  • Mime Types

    • MIME-Types
    • How to install
    • Setup
    • Usage
    • Drivers

      • Available Drivers
      • File Info
  • Properties

    • Properties Overload
    • How to install
    • Usage
    • Naming Convention
    • Properties Visibility
  • Redmine

    • Redmine Api Client
    • How to install
    • Setup
    • General Usage

      • Supported Operations
      • Fetch list of resources
      • Find
      • Fetch
      • Create new record
      • Update existing record
      • Delete existing record
      • Relations
    • Available Resources

      • Predefined Resources
      • Attachments
      • Enumerations
      • Issue Relations
      • Users
      • User Groups
      • Roles
      • Project Memberships
      • Versions (Milestones)
      • Issue Categories
      • Trackers
  • Service

    • Service Registrar
    • How to install
    • How to use
  • Streams

    • Streams
    • How to install
    • Setup
    • How to use

      • Introduction
      • Open and Close
      • Raw Resource
      • Seeking
      • Reading
      • Writing
      • Size
      • Truncate
      • Flush
      • Hash
      • MIME-Type
      • Output
      • Locking
      • Transactions
      • Meta
      • Misc
  • Support

    • Introduction
    • How to install
    • Laravel Aware-of Helpers

      • How to use
      • Enforce Via Interface
      • Custom Default
      • Pros and Cons
      • Available Helpers
    • Aware-of Properties

      • Generator
      • Available Aware-of Helpers
    • Live Templates
  • Testing

    • Introduction
    • How to install
    • Test Cases
    • Testing Aware-of Helpers
  • Utils

    • Introduction
    • How to install
    • Array
    • Duration
    • Json
    • Math
    • Memory
    • Method Helper
    • Invoker
    • Populatable
    • String
    • Version
  • Validation

    • Introduction
    • How to install
    • Setup
    • Rules

      • Alpha-Dash-Dot
      • Semantic Version
You are viewing documentation for an outdated version. It is no longer supported!

Usage

  • Obtain Circuit Breaker
  • Attempt
  • Otherwise Callback
    • Default Otherwise Callback
  • Retries & Failure Threshold
  • Recovery (Half-Open)

Obtain Circuit Breaker

Once you have defined your "service" and circuit breaker settings, in your config/circuit-breaker, you can obtain a CircuitBreaker instance. This can be done via the CircuitBreakerManagerTrait.

<?php

use Aedart\Circuits\Traits\CircuitBreakerManagerTrait;

class WeatherService
{
    use CircuitBreakerManagerTrait;
    
    public function forecast()
    {
        // Obtain circuit breaker for "weather_service" (defined in your
        // config/circuit-breakers.php file)
        $circuitBreaker = $this->getCircuitBreakerManager()
            ->create('weather_service');
            
        // ...remaining not shown
    }
}

Attempt

Use the attempt() method to invoke a callback. Depending on your configuration, this callback will be attempted executed one or multiple times (See retries in your configuration file), until it either succeeds or fails entirely.

use Aedart\Contracts\Circuits\CircuitBreaker;

return $circuitBreaker->attempt(function(CircuitBreaker $cb) {
    // Call 3rd party service, return result ...
    $response = $http::get('https://acme.org/api/weather-service/v1/forecast');

    if ($response->failed()) {
        throw new RuntimeException('Unable to obtain forecast');
    }

    return $response;
});

Otherwise Callback

Use the $otherwise argument to state a callback, which will be invoked if the attempt should fail.

use Aedart\Contracts\Circuits\CircuitBreaker;
use Acme\Services\Weather\ServiceUnavailable;

return $circuitBreaker->attempt(function(CircuitBreaker $cb) {
    // ... callback not shown ...
}, function(CircuitBreaker $cb) {
    // Attempt has failed, do something else
    $lastFailure = $cb->lastFailure();
    $reason = $lastFailure->reason();

    if (!empty($reason)) {
        throw new ServiceUnavailable($reason);
    }
    
    throw new ServiceUnavailable('Weather Service is currently unavailable');
});

Behind the scenes, if the circuit breaker has detected too many failed attempts, across instances, then the $otherwise callback can be invoked immidiatly, allowing a fast-failure to occur. This happens when the failure_threshold has been reached.

Default Otherwise Callback

You may also specify a default otherwise callback to be invoked, when none provided via the attempt() method.

use Aedart\Contracts\Circuits\CircuitBreaker;

$result = $circuitBreaker
    ->otherwise(function(CircuitBreaker $cb) {
        // ...not shown...
    })
    ->attempt(function(CircuitBreaker $cb) {
        // ...callback not shown...
    });

Retries & Failure Threshold

It is very important to understand that, each failed attempt increases the failure count. The circuit breaker's internal store keeps track of this failure count, across instances. This means that, if you have configured your circuit breaker to perform a certain amount retries, it might not actually perform all attempts, if the failure_threshold is reached, during those attempts.

Please be mindful og how you choose to configure your retries and failure_threshold.

Recovery (Half-Open)

When the circuit breaker is in Open state (circuit tripped - failure state), it will automatically try to switch state to the Half-Open state, each time attempt() is invoked. However, this only happens after the grace_period has past (available in your configuration).

Note

By default, only a single circuit breaker instance will be able to obtain the Half-Open state, across instances.

If a circuit breaker achieves changing state to Half-Open, it will invoke the provided $callback. Should the callback succeed, then the failure count will be reset, across all instances. This means that the circuit breaker changes its state back to Closed.

If the callback does not succeed, the circuit breaker will remain in Open state and invoke the $otherwise callback.

Lastly, if the Half-Open state cannot be obtained, then the circuit breaker resumes its normal behaviour and invokes the $otherwise callback.

Edit page
Last Updated: 16/02/2023, 09:10
Contributors: Alin Eugen Deac, alin
Prev
Setup
Next
Events