1. Architectural Overview & Why Naive Retries Cause Cascading Meltdowns
In a distributed microservices topology, when a downstream database or payment gateway slows down from 15ms to 2,500ms, upstream worker pools quickly saturate their thread/connection limits waiting on doomed sockets. Without a Circuit Breaker and Priority-Aware Load Shedder, every slow downstream dependency turns into a fleet-wide cascading outage.
Core Engineering Invariants
- Minimum Volume Gate (
minimumCalls): Never trip a circuit on 1 failure out of 1 request during low-traffic intervals. Require a statistically meaningful sample within the sliding time window (windowSizeMs). - Fast-Fail Isolation in
OPENState: While open, reject calls in $O(1)$ memory without allocating sockets or timers, returning a degraded fallback orCircuitOpenError. - Bounded
HALF_OPENProbing: WhencooldownMsexpires, prevent a thundering herd of 10,000 concurrent requests from hammering a recovering service. Admit at mosthalfOpenMaxCallstrial probes; if any probe fails, immediately re-open the circuit. - Priority-Aware Concurrency Shedding (Little's Law $L = \lambda W$): Before the circuit even trips, bound in-flight concurrency (
maxConcurrency). Once utilization crossesshedLowPriorityAt(e.g., 75%), shedLOWpriority background/analytics requests so capacity remains reserved forHIGH/NORMALuser-facing traffic.
2. State Machine & Sliding Health Window Deep Dive
Rolling Time-Window Pruning
Instead of resetting counters on arbitrary fixed clock ticks (which suffers from boundary blind spots), _pruneWindow(now) evicts call outcomes older than now - windowSizeMs. Every recordSuccess() and recordFailure() evaluates live health across the trailing window.
Graceful Degradation & Fallback Hooks
When execute(fn, { priority, fallback }) rejects due to CIRCUIT_OPEN or ELOADSHED, callers can supply a deterministic fallback(err) handler—serving stale cache entries, queued acknowledgments, or default recommendations instead of HTTP 500s.
3. Verification & Running the Lab
Run the interactive demonstration:
node demo.jsRun the automated assertion suite:
node test.js