Download the PHP package rasuvaeff/circuit-breaker without Composer

On this page you can find all versions of the php package rasuvaeff/circuit-breaker. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package circuit-breaker

rasuvaeff/circuit-breaker

Latest Stable Version Total Downloads Build Static analysis Psalm level PHP Русская версия

Circuit breaker resilience primitive: protects a downstream dependency from cascading failure. Closed → Open → HalfOpen state, switched by sliding-window success/failure counts. In Open, calls fail fast — no network round-trip — until a cooldown elapses; a bounded number of HalfOpen probes then decide whether to resume or reopen.

Pluggable distributed state via Storage: in-memory (tests/CLI), APCu (single host), Redis (multi-host cluster) — all three implement the exact same atomic admit()/recordOutcome() contract, so switching backends never changes behavior, only how far the shared state reaches.

Using an AI coding assistant? llms.txt contains a compact API reference you can share with the model. Projects using the llm/skills Composer plugin also get this package's agent skill synced into .agents/skills/ automatically on install.

Requirements

Installation

Usage

forRemoteApi() defaults successThreshold to 1 (one successful probe closes the circuit again). The full constructor exposes the same knobs explicitly:

Depend on CircuitBreakerInterface rather than the concrete class where a decorator or a test double should be able to replace the breaker.

With Redis (multi-host):

With ext-redis instead of predis:

With APCu (single host):

Request deadlines and cancellation (rasuvaeff/context)

When the callback runs under a rasuvaeff/context budget, its context exceptions say something about the caller, not the dependency. Counting them as failures lets one client with a short budget open the circuit for everyone. Classify them as ignored:

An ignored outcome is rethrown as is, skips $fallback and still releases a HalfOpen probe slot. The trade-off: an expiry cannot tell "our budget was short" from "the dependency is slow". If every caller's budget is generous and you want a slow dependency to open the circuit, count an expiry whose getPrevious() is a transport failure (that is how rasuvaeff/context-http reports a request that timed out against the budget). The breaker has no call timeout of its own — the budget is enforced by the transport.

Public API

Type Description
CircuitBreakerInterface The breaker's public surface: call, canCall, state, metrics, forceOpen, forceClosed — type to depend on for decorators and test doubles
CircuitBreaker Implements CircuitBreakerInterface; plus publishState(). Constructor: config, storage, optional clock (defaults to SystemClock), optional observer and observerErrorHandler
BreakerConfig name, failureThreshold (Ratio), cooldown, successThreshold, required isFailure, probeLimit, probeTimeout, classifyResult; forRemoteApi(name, failures, window, within, cooldown, isFailure, successThreshold = 1, …) factory
Ratio "N failures out of the last M calls, within a sliding window" — backs failureThreshold
CircuitState Enum: Closed, Open, HalfOpen
Outcome Enum: Success, Failure, Ignored — result of isFailure() classification
Admission Enum: Allowed, Probe, Rejected — Storage::admit()'s decision
Storage Interface: admit, recordOutcome, snapshot, forceState — the distributed-state seam. admit()/recordOutcome() require the fencing triple (admission, admittedAt, attemptId)
StorageFailure Infrastructure exception for storage outages; exposes operation, breakerName, the original exception, and downstreamOutcome (the callback's exception when storage failed while recording it)
InMemoryStorage Single-process store (tests/CLI); no cross-process coordination
ApcuStorage Single-host cross-process store; apcu_add lock (lease, lockTtlSeconds) around the whole read-transition-write
RedisStorage Multi-host cross-process store; one Lua script per Storage method
CircuitScriptRunner Typed seam over a Redis script call (implement for another client)
Redis\PredisScriptRunner predis-backed CircuitScriptRunner; EVALSHA with EVAL fallback
Redis\PhpRedisScriptRunner ext-redis-backed CircuitScriptRunner; EVALSHA with EVAL fallback
StateRecord Snapshot returned by Storage: state, openedAt, successes, failures, rejected
Metrics Observability snapshot from CircuitBreaker::metrics(), mirrors StateRecord
CircuitTransition A committed state change: breakerName, from, to, occurredAt, reason, state
TransitionReason Enum: why a transition happened — FailureThresholdReached, CooldownElapsed, ProbeSucceeded, ProbeFailed, ForcedOpen, ForcedClosed, ForcedHalfOpen
CircuitObserver Interface receiving committed CircuitTransition events; optional error handler
LoggingCircuitObserver Ready-made CircuitObserver mirroring transitions into a PSR-3 LoggerInterface with severity by transition (→ Open error, → HalfOpen warning, → Closed info) and full context (name, from/to, reason, counters, timestamp)
CircuitSnapshotObserver Extends CircuitObserver with onSnapshot(string $breakerName, Metrics $metrics), delivered by CircuitBreaker::publishState()
CircuitOpenException Thrown (or passed to fallback) when a call is rejected; carries breakerName, retryAfter; retryAfterIn(ClockInterface): Duration gives the time left
Clock\SystemClock Psr\Clock\ClockInterface using the wall clock
Clock\FakeClock Controllable clock for testing cooldown/window expiry

How call() decides

  1. Storage::admit() — atomically applies the Open → HalfOpen cooldown transition, then decides Allowed (Closed) / Probe (HalfOpen, slot occupied) / Rejected (Open, or HalfOpen with no free probe slot).
  2. Rejected → $callback is never invoked. $fallback, if given, receives a fresh CircuitOpenException; otherwise it is thrown. In Open, retryAfter is the cooldown deadline; for a saturated HalfOpen, it is a conservative deadline based on probeTimeout.
  3. Allowed/Probe → $callback runs. Its outcome is classified via isFailure() into Success / Failure / Ignored, recorded with exactly one Storage::recordOutcome() call (this is also what releases a HalfOpen probe slot — including when $callback throws). The outcome is timestamped when the callback completes. The original Admission and an opaque attempt ID are passed so a reclaimed probe cannot affect a newer generation or enter a newly reset Closed window.
  4. A Failure outcome with $fallback given returns the fallback's result; otherwise the original exception is rethrown. An Ignored outcome (isFailure() === false) is always rethrown as-is — it never triggers $fallback and never counts against the threshold.

Sizing the knobs

How the state holds across workers/hosts

RedisStorage runs admit()/recordOutcome()/snapshot()/forceState() each as exactly one Lua script. Redis executes scripts to completion without interleaving another client's command, so the read-evaluate-transition sequence (check counters → decide → write new state) is atomic across every process racing on the same breaker — splitting that into separate INCR/GET/SET calls would reopen the exact check-then-act race the package exists to prevent. State lives in one Redis hash (state, openedAt, probe counters), one sorted set per breaker (the Closed sliding window, member = outcome, score = timestamp), and a set of opaque IDs for active probes. All keys share a Redis Cluster hash tag, so every multi-key script stays within one cluster slot.

ApcuStorage approximates that with an apcu_add-based lock around a read-transition-write of the whole entry (APCu has no server-side scripting). Locks carry integer owner tokens and release through CAS, so a stale owner cannot release a replacement lock after its lease expired. The lock is a lease (lockTtlSeconds, default 1s), not a Redis-grade mutex: a critical section that outlives its lease could otherwise commit over a worker that already took over, so the commit verifies ownership first and raises StorageFailure instead. That narrows the window rather than closing it — APCu cannot make the ownership check and the entry write one atomic step, so raise lockTtlSeconds if your workers can stall for longer. A rejected apcu_store() (shared memory exhausted) raises StorageFailure too: a transition that was not written is never reported as committed. APCu only coordinates workers on the same host — use RedisStorage for a pool spread across hosts.

Security

Caveats

Result classification and transitions

BreakerConfig::$classifyResult is optional and defaults every normal callback return to Outcome::Success. Configure it when an API reports downstream failure in a normal value; the original value is still returned and fallback is not invoked.

Pass a CircuitObserver to CircuitBreaker to receive committed CircuitTransition events without polling metrics(). An exception thrown by the observer never affects the protected call: it goes to observerErrorHandler when one is given (typically a logger call) and is discarded otherwise.

onTransition() fires only on a state change, so a gauge fed by it has no series until the breaker first trips. Implement CircuitSnapshotObserver and call publishState() once after wiring, or on every metrics scrape: it reads the current state from storage and passes it to onSnapshot(). It reads storage, so it is never called implicitly; storage errors surface as StorageFailure, observer errors propagate unchanged.

For logging, skip the hand-written observer: LoggingCircuitObserver wraps any PSR-3 LoggerInterface and maps each committed transition to a severity — Closed → Open and HalfOpen → Open (a failed probe re-tripping the breaker) are errors, entering HalfOpen is a warning, reaching Closed is info, and HalfOpen → HalfOpen (a probe completed without changing the state) is info with its own message. The context array carries the breaker name, from/to states, reason, successes/failures/rejected counters, and the transition timestamp (Y-m-d\TH:i:s.uP, microseconds preserved), so the log line needs no extra snapshot() read.

To turn a rejection into a Retry-After header or a re-queue delay, use CircuitOpenException::retryAfterIn($clock): the time left until retryAfter, never negative, with microsecond precision. Storage::admit() returns AdmissionResult, and recordOutcome() returns OutcomeResult; both carry optional transition metadata.

Implementing Storage yourself: $admission, $admittedAt, and $attemptId are required on recordOutcome() and must be exactly what admit() returned and received. An outcome that is not an Admission::Probe must never move a HalfOpen breaker — it was admitted while the breaker was Closed and belongs to no probe generation.

Examples

See examples/ for runnable scripts. Examples are expected to execute without fatal errors and stay aligned with the documented public API.

Script Shows Needs server?
01-in-memory.php Minimal breaker: tripping on failureThreshold, fallback no
02-redis-cluster.php Cross-host state via RedisStorage + predis yes
03-with-retry.php Composition with rasuvaeff/retry no
04-with-bulkhead.php Composition with rasuvaeff/bulkhead no
05-prometheus-metrics.php Exporting Metrics in Prometheus exposition format no
06-apcu.php Single-host cross-process state via ApcuStorage no (needs ext-apcu)
07-storage-outage.php Handling StorageFailure separately from downstream failures no

Development

No PHP/Composer on the host — run in Docker via the composer:2 image:

Integration tests need a Redis server (self-skip unless REDIS_HOST is set), ext-apcu (self-skip via ApcuStorage::isAvailable()) and ext-redis (self-skip via extension_loaded('redis')); the base composer:2 image has none of them, so run the suite in an image carrying apcu, pcntl and redis (plus apc.enable_cli=1):

License

BSD-3-Clause


All versions of circuit-breaker with dependencies

PHP Build Version
Package Version
Requires php Version 8.3 - 8.5
psr/clock Version ^1.0
psr/log Version ^3.0
rasuvaeff/duration Version ^1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package rasuvaeff/circuit-breaker contains the following files

Loading the files please wait ...