Skip to Content
HeronJS 3.7 with fully support Typescript 6 is released & now is ESM native 🎉

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

ParameterTypeDefaultDescription
thresholdnumberNumber of consecutive failures before the circuit opens.
cooldownnumberTime (in milliseconds) to wait before attempting to close the circuit again.
fallbackstringName of the fallback method to call when the circuit is open.

Behavior

  1. Closed state — Requests pass through normally. Failures are counted.
  2. Open state — Once threshold consecutive failures occur, the circuit opens and all requests immediately call the fallback method.
  3. Half-Open state — After cooldown ms 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 liveness endpoint queries the application’s health.
  • If 3 consecutive calls to liveness fail, the circuit opens.
  • Subsequent calls are immediately redirected to fallback() for 60 seconds (the cooldown period).
  • 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 threshold high enough to avoid tripping on transient errors, but low enough to prevent cascading failures.
  • Match cooldown to 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