HOME

TheInfoList



OR:

Circuit breaker is a
design pattern A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" b ...
used in
software development Software development is the process of conceiving, specifying, designing, programming, documenting, testing, and bug fixing involved in creating and maintaining applications, frameworks, or other software components. Software development invol ...
. 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.


Common uses

Assume that an application connects to a
database In computing, a database is an organized collection of data stored and accessed electronically. Small databases can be stored on a file system, while large databases are hosted on computer clusters or cloud storage. The design of databases sp ...
100 times per second and the database fails. The application designer does not want to have the same error reoccur constantly. They also want to handle the error quickly and gracefully without waiting for
TCP connection TCP may refer to: Science and technology * Transformer coupled plasma * Tool Center Point, see Robot end effector Computing * Transmission Control Protocol, a fundamental Internet standard * Telephony control protocol, a Bluetooth communication s ...
timeout. Generally Circuit Breaker can be used to check the availability of an external service. An external service can be a database server or a web service used by the application.
Circuit breaker A circuit breaker is an electrical safety device designed to protect an electrical circuit from damage caused by an overcurrent or short circuit. Its basic function is to interrupt current flow to protect equipment and to prevent the risk ...
detects failures and prevents the application from trying to perform the action that is doomed to fail (until it's safe to retry).


Implementation

Implementations of the Circuit Breaker Design Pattern need to retain the state of the connection over a series of requests. It must offload the logic to detect failures from the actual requests. Therefore, the state machine within the circuit breaker needs to operate in some sense concurrently with the requests passing through it. One way this can be achieved is asynchronously. In a multi-node (clustered) server, the state of the upstream service will need to be reflected across all the nodes in the cluster. Therefore, implementations may need to use a persistent storage layer, e.g. a network cache such as
Memcached Memcached (pronounced variously ''mem-cash-dee'' or ''mem-cashed'') is a general-purpose distributed memory-caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of t ...
or
Redis Redis (; Remote Dictionary Server) is an in-memory data structure store, used as a distributed, in-memory key–value database, cache and message broker, with optional durability. Redis supports different kinds of abstract data structures, su ...
, or local cache (disk or memory based) to record the availability of what is, to the application, an external service. Circuit Breaker records the state of the external service on a given interval. Before the external service is used from the application, the storage layer is queried to retrieve the current state.


Performance implication

While it's safe to say that the benefits outweigh the consequences, implementing Circuit Breaker will negatively effect storage space, application complexity, and computational cost to the executing application. This is because it adds additional code into the execution path to check for the state of the circuit. This can be seen in the PHP example below, where checking APC for the database status costs a few extra cycles. Also, running the circuit breaker code itself consumes resources on the system where it is running, thus leaving less execution power for "real" applications. By how much depends on the storage layer used and generally available resources. The largest factors in this regard are the type of cache, for example, disk-based vs. memory-based and local vs. network.


Different States of Circuit Breaker

* Closed * Open * Half Open


Closed State

When everything is normal, the circuit breakers remained closed, and all the request passes through to the services as shown below. If the number of failures increases beyond the threshold, the circuit breaker trips and goes into an open state.


Open State

In this state circuit breaker returns an error immediately without even invoking the services. The Circuit breakers move into the half-open state after a timeout period elapses. Usually, it will have a monitoring system where the timeout will be specified.


Half Open State

In this state, the circuit breaker allows a limited number of requests from the Microservice to passthrough and invoke the operation. If the requests are successful, then the circuit breaker will go to the closed state. However, if the requests continue to fail, then it goes back to Open state.


Example implementation


PHP

The following is a sample implementation in PHP. The proof of concept stores the status of a MySQL server into a shared memory cache ( APC).


Check

The following script could be run on a set interval through crontab. $mysqli = new mysqli('localhost', 'user', 'pass'); if ($mysqli->connect_error) else


Usage in an application

if (apc_fetch('dbStatus')

'down') { echo 'The database server is currently not available. Please try again in a minute.'; exit; } $mysqli = new mysqli('localhost', 'user', 'pass', 'database'); $result = $mysqli->query('SELECT * FROM table');


External links


Example of PHP implementation with diagramsExample of Retry Pattern with Polly using C#Example of C# implementation from Anders Lybeckers using PollyPolly NuGet packageExample of C# implementation from Alexandr NikitinImplementation in PythonImplementation in PHP
*https://martinfowler.com/bliki/CircuitBreaker.html
Circuit Break Pattern States
Software design patterns Articles with example PHP code