Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/lib/monitoring/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,26 @@ export function recordAuthMetric(
createCounterMetric(name, 1, tags);
}

/** Circuit breaker state machine states. */
export type CircuitBreakerState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';

/**
* Record a circuit breaker state transition as a counter. The metric is
* named `circuit_breaker.state_change` and tagged with the previous and new
* states so dashboards can count each transition independently.
*/
export function recordCircuitBreakerStateChange(
previousState: CircuitBreakerState,
newState: CircuitBreakerState,
tags?: Record<string, string | number | boolean>,
): void {
createCounterMetric('circuit_breaker.state_change', 1, {
from: previousState,
to: newState,
...tags,
});
}

/** Rolling window used to turn individual request outcomes into a rate. */
export const DEFAULT_ERROR_RATE_WINDOW_MS = 60_000;

Expand Down
14 changes: 8 additions & 6 deletions src/utils/circuitBreaker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
* - HALF_OPEN: Testing if the system has recovered
*/

import { recordCircuitBreakerStateChange } from '@/lib/monitoring/metrics';

export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';

export interface CircuitBreakerConfig {
Expand Down Expand Up @@ -173,7 +175,8 @@ export class CircuitBreaker {
* Transition to a new state
*/
private transitionTo(newState: CircuitState): void {
if (this.state === newState) return;
const previousState = this.state;
if (previousState === newState) return;

this.state = newState;
this.lastStateChange = Date.now();
Expand All @@ -188,6 +191,8 @@ export class CircuitBreaker {
} else if (newState === 'HALF_OPEN') {
this.successCount = 0;
}

recordCircuitBreakerStateChange(previousState, newState);
}

/**
Expand All @@ -210,13 +215,10 @@ export class CircuitBreaker {
* Manually reset the circuit breaker
*/
reset(): void {
this.state = 'CLOSED';
this.failureCount = 0;
this.successCount = 0;
this.lastFailureTime = undefined;
this.lastStateChange = Date.now();
this.transitionTo('CLOSED');
this.failureHistory = [];
this.recoveryDeadline = undefined;
this.lastFailureTime = undefined;
}

/**
Expand Down
Loading