Overview
The @CircuitBreaker decorator provides fault tolerance for your API endpoints by monitoring failures and preventing calls to a service when it’s likely to fail. When the failure threshold is exceeded, the circuit “opens” and subsequent calls are routed to a fallback method instead.
Import
import { CircuitBreaker } from '@heronjs/common';API
| Parameter | Type | Default | Description |
|---|---|---|---|
threshold | number | — | Number of consecutive failures before the circuit opens. |
cooldown | number | — | Time (in milliseconds) to wait before attempting to close the circuit again. |
fallback | string | — | Name of the fallback method to call when the circuit is open. |
Behavior
- Closed state — Requests pass through normally. Failures are counted.
- Open state — Once
thresholdconsecutive failures occur, the circuit opens and all requests immediately call thefallbackmethod. - Half-Open state — After
cooldownms elapses, a single test request is allowed through. If it succeeds the circuit closes; if it fails the circuit remains open.
Note: The fallback method must be defined in the same class and match the signature of the original method (or return a compatible type).
Example
import { Controller, Get, Queries, CircuitBreaker } from '@heronjs/common';
import { Observable, of } from 'rxjs';
import { HealthCheckRest, OutputProps } from './types';
@Controller({ uri: 'cb' })
export class HealthController {
@Get({ uri: '/check' })
@CircuitBreaker<HealthCheckRest>({
threshold: 3,
cooldown: 60000,
fallback: 'cb_fallback',
})
cb_check(@Queries() a: {}): Observable<OutputProps> {
}
cb_fallback(): Observable<{ status: string }> {
return of('Server not available!');
}
}In this example:
- The
livenessendpoint queries the application’s health. - If 3 consecutive calls to
livenessfail, the circuit opens. - Subsequent calls are immediately redirected to
fallback()for 60 seconds (thecooldownperiod). fallback()returns a static response indicating the server is unavailable.
Parameters explained
- threshold: 3 — After 3 failures the circuit opens. Choose a threshold that balances false positives against timely protection.
- cooldown: 60000 — The circuit remains open for 60 seconds before allowing a single probe request. Adjust based on your service’s expected recovery time.
- fallback: ‘fallback’ — The method name to call when the circuit is open. The method must exist on the same class.
Best Practices
- Set
thresholdhigh enough to avoid tripping on transient errors, but low enough to prevent cascading failures. - Match
cooldownto your downstream service’s typical recovery window. - Keep fallback methods simple and fast — avoid performing complex logic or making external calls inside them.
Last updated on