Circuit breaker design pattern

This is an old revision of this page, as edited by Illtillwillkillbill (talk | contribs) at 17:50, 28 November 2010 (restructured text, added example implementation in PHP). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.


Circuit breaker is a design pattern in modern software development.

Circuit breaker is used to detect failures and encapsulates logic of preventing a failure to reoccur constantly (during maintenance, temporary external system failure or unexpected system difficulties).

Common Uses

Your application connects to a database 100 times per second and the database fails. You do not want to have the same error reoccur constantly. You also want to handle the error quickly and gracefully without waiting for TCP connection timeout.

Circuit breaker is used to detect failures and prevent application from trying to perform the action that is doomed to fail (until its safe to retry).

Example Implementation

PHP

The following is a POC example implementation in PHP.

Check

The following script could be run on a set interval through crontab.

$db = mysql_connect('localhost','root','pass');
if ($db === false) {
    apc_store('dbUp', 'up');
} else {
    apc_store('dbUp', 'down');
    @mysql_close($db);
}

Usage in an application

if (apc_fetch('dbUp') === 'down') {
    echo "The database server is currently not available. Please try again in a minute.";
    exit;
}
$db  = mysql_connect('localhost', 'root', 'pass');
$res = mysql_db_query('database', 'SELECT * FROM table');