Circuit breaker design pattern: Difference between revisions

Content deleted Content added
m top: replaced: Distirbuted → Distributed
WP:NOTHOWTO
Line 15:
 
[[Circuit breaker]] 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 [[Asynchrony (computer programming)|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]] or [[Redis]], 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==
Line 50 ⟶ 40:
 
[[File:Circuit Breaker -Half Open state.png|thumb|Circuit Breaker Half 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 User Cache).
 
==== Check ====
 
The following script could be run on a set interval through [[crontab]].
 
<syntaxhighlight lang="php">
$mysqli = new mysqli("localhost", "username", "password");
 
if ($mysqli->connect_error) {
apcu_add("dbStatus", "down");
} else {
apcu_add("dbStatus", "up");
$mysqli->close();
}
</syntaxhighlight>
 
====Usage in an application====
 
<syntaxhighlight lang="php">
if (apcu_fetch("dbStatus") === "down") {
echo "The database server is currently not available. Please try again in a minute.";
exit;
}
 
$mysqli = new mysqli("localhost", "username", "password", "database");
$result = $mysqli->query("SELECT * FROM table");
</syntaxhighlight>
 
==References==