NOTE: to use php-backoff with PHP 5.x please use the lastet release of branch 1.x
This method is static and returns an array with the default options:
cap
: Max duration allowed (in microseconds). If backoff duration is greater than cap, cap is returned, default is1000000
microseconds.maxAttempts
: Number of attempts before thrown an Yriveiro\Backoff\BackoffException. Default is0
, no limit.
This method use and exponential function E(attempt) = (2**attempt - 1)
to calculate backoff time.
attempt
: incremental value that represents the current retry number.
Exponential backoff has one disadvantage. In high concurrence, we can have multiples calls with the same backoff time due the time is highly bound to the current attempt, different calls could be in the same attempt.
To solve this we can add a jitter value to allow some randomization.
equalJitter
uses the function: E(attempt) = min(((2**attempt - 1) / 2), random(0, ((2**attempt - 1) / 2)))
.
attempt
: incremental value that represents the current retry number.
Full jitter behaves like equalJitter
method, the main difference between them is the way in how the jitter value is calculated.
fullJitter
uses the function: E(attempt) = min(random(0, (2**attempt - 1) / 2))
.
attempt
: incremental value that represents the current retry number.
With zero configuration, we will never stop to try fetch data. The exit condition is your responsibility.
$attempt = 1;
$backoff = new Backoff();
$response = $http->get('http://myservice.com/user/1');
while (!$response) {
$time = $backoff->exponential($attempt);
$attempt++;
usleep($time);
$response = $http->get('http://myservice.com/user/1');
}
$attempt = 1;
$options = Backoff::getDefaultOptions();
$options['maxAttempts'] = 3;
$backoff = new Backoff($options);
$response = $http->get('http://myservice.com/user/1');
try
while (!$response) {
$time = $backoff->fullJitter($attempt);
$attempt++;
usleep($time);
$response = $http->get('http://myservice.com/user/1');
}
} catch (Yriveiro\Backoff\BackoffException $e) {
// Handle the exception
}
The recommended way to install this package is through Composer.
php composer.phar require "yriveiro/php-backoff"
Tests are performed using the phpunit
library, to run them:
php vendor/bin/phpunit tests
None.
Have an idea? Found a bug?, contributions are welcome :)
Backoff is licensed under MIT license.