Skip to content

Monitoring

getState(key) returns a non-mutating snapshot of a circuit, so you can poll it from a health endpoint or scheduled job without affecting behaviour (it never flips OPEN → HALF_OPEN).

typescript
import { Injectable, Inject } from '@nestjs/common';
import { CIRCUIT_BREAKER_SERVICE, ICircuitBreakerService, CircuitState } from '@nestjs-redisx/circuit-breaker';

/**
 * Expose circuit state for dashboards / health checks. `getState` is
 * non-mutating, so polling it never affects the breaker.
 */
@Injectable()
export class BreakerMonitor {
  private readonly circuits = ['stripe', 'users-api', 'search'];

  constructor(
    @Inject(CIRCUIT_BREAKER_SERVICE)
    private readonly breaker: ICircuitBreakerService,
  ) {}

  async snapshot(): Promise<Record<string, CircuitState>> {
    const entries = await Promise.all(this.circuits.map(async (key) => [key, (await this.breaker.getState(key)).state] as const));
    return Object.fromEntries(entries);
  }

  async isDegraded(): Promise<boolean> {
    const states = await this.snapshot();
    return Object.values(states).some((state) => state !== 'closed');
  }
}

Snapshot fields

typescript
interface ICircuitSnapshot {
  state: 'closed' | 'open' | 'half-open';
  failuresInWindow: number; // CLOSED: failures still inside the rolling window
  halfOpenSuccesses: number; // HALF_OPEN: probes that have succeeded
  halfOpenInFlight: number; // HALF_OPEN: permitted probes not yet resolved
}

Ideas

  • Health check — report degraded when any circuit is not closed.
  • Dashboards — expose per-circuit state as a gauge (0 = closed, 1 = half-open, 2 = open).
  • Alerts — page when a critical circuit stays OPEN longer than expected.

TIP

Pair this with the Metrics plugin to publish circuit state as Prometheus gauges alongside your other application metrics.

Released under the MIT License.