Overview
Retry and circuit breaker utilities for HolyPHP with exponential backoff, retry predicates, and closed/open/half-open circuit state management.
bundled — works offline
backoff
circuit breaker
resilience
Quick start
import "retry";
// Retry an unreliable operation up to 3 times
$result = retry_run(function(int $attempt) {
if ($attempt < 3) {
throw new Exception("transient network error");
}
return "success";
}, 3);
// Compute exponential backoff delays (in milliseconds)
$delay1 = retry_backoff_delay(1, 100, 2.0, 5000); // 100
$delay2 = retry_backoff_delay(2, 100, 2.0, 5000); // 200
$delay3 = retry_backoff_delay(3, 100, 2.0, 5000); // 400
// Protect a downstream call with a CircuitBreaker
$cb = new CircuitBreaker(3, 30, 1);
$data = $cb->call(function() {
return "service response";
});
Installation
In a project
Inside a project (a folder with hphp.yaml, see Projects & packages):
hphp install retry
This adds the library to hphp.yaml, installs it into .hphp/packages/retry/ and pins the exact version in hphp.lock:
require:
retry: "^1.0"
Use it
import "retry";
retry is bundled with the compiler, so import "retry"; also works in a single file without installing anything, and hphp install works offline.
Outside a project
hphp install retry # for your user, shared by all scripts
hphp create myapp # or start a project, then: hphp install retry
Documentation
API Reference
retry_backoff_delay(int $attempt, int $baseMs = 100, float $multiplier = 2.0, int $maxMs = 30000): int
Calculates the exponential backoff delay in milliseconds for a given 1-based attempt number, clamped to $maxMs.
$attempt: 1-based attempt number (>= 1).
$baseMs: Initial delay in milliseconds (>= 0).
$multiplier: Growth factor per attempt (>= 1.0).
$maxMs: Maximum delay cap in milliseconds (>= 0).
- Returns: Delay in milliseconds as
int.
retry_run($fn, int $maxAttempts = 3, $shouldRetry = null, $onRetry = null)
Executes $fn($attempt) up to $maxAttempts times until it succeeds.
$fn: Callback function(int $attempt) to execute.
$maxAttempts: Maximum number of attempts (>= 1).
$shouldRetry: Optional predicate function(string $errorMessage, int $attempt): bool. Return false to abort immediately without further retries.
$onRetry: Optional hook function(string $errorMessage, int $attempt): void called after a failed attempt before the next retry.
- Returns: The return value of
$fn on success.
class CircuitBreaker
Implements a three-state ("closed", "open", "half-open") circuit breaker.
Constructor
new CircuitBreaker(int $failureThreshold = 5, int $resetTimeoutSec = 30, int $halfOpenMaxSuccesses = 1, $clock = null)
$failureThreshold: Consecutive failures required to open the circuit (>= 1).
$resetTimeoutSec: Seconds to wait in "open" state before transitioning to "half-open" (>= 0).
$halfOpenMaxSuccesses: Consecutive successes in "half-open" state required to close the circuit (>= 1).
$clock: Optional function(): int returning current unix timestamp in seconds (defaults to time()).
Methods
call($fn): Executes $fn() if the circuit is "closed" or "half-open", recording success/failure automatically. Throws when "open".
getState(): string: Returns "closed", "open", or "half-open" (auto-transitions "open" to "half-open" once $resetTimeoutSec has elapsed).
getFailureCount(): int: Returns the current failure count.
getSuccessCount(): int: Returns the current half-open success count.
recordSuccess(): void: Manually records a successful operation.
recordFailure(): void: Manually records a failed operation.
reset(): void: Resets the breaker to "closed" with zeroed counts.
Error Handling
All validation and runtime errors throw Exception with clear, prefixed messages:
retry: attempt must be >= 1, got ...
retry: baseMs must be >= 0, got ...
retry: multiplier must be >= 1.0, got ...
retry: maxMs must be >= 0, got ...
retry: maxAttempts must be >= 1, got ...
retry: operation callback must not be null
retry: failed after <N> attempts: <last error>
retry: aborted on attempt <N>: <error>
retry: circuit breaker is open
retry: failureThreshold must be >= 1, got ...
retry: resetTimeoutSec must be >= 0, got ...
retry: halfOpenMaxSuccesses must be >= 1, got ...
Examples
01Quick start
Bundled with the compiler — import "retry"; works offline in any file, or add it to a project with hphp install retry.
import "retry";
// Retry an unreliable operation up to 3 times
$result = retry_run(function(int $attempt) {
if ($attempt < 3) {
throw new Exception("transient network error");
}
return "success";
}, 3);
// Compute exponential backoff delays (in milliseconds)
$delay1 = retry_backoff_delay(1, 100, 2.0, 5000); // 100
$delay2 = retry_backoff_delay(2, 100, 2.0, 5000); // 200
$delay3 = retry_backoff_delay(3, 100, 2.0, 5000); // 400
// Protect a downstream call with a CircuitBreaker
$cb = new CircuitBreaker(3, 30, 1);
$data = $cb->call(function() {
return "service response";
});
Try ithphp install retry
hphp run main.hphp
Covered by the official test suite in tests/positive/lib_retry.hphp.