Module Message_templates.Circuit_breaker

Circuit breaker pattern for error recovery

The circuit breaker prevents cascade failures by temporarily blocking calls when failures exceed a threshold. It has three states:

Example:

  let cb =
    Circuit_breaker.create ~failure_threshold:5 ~reset_timeout_ms:30000 ()
  in

  (* Protected call *)
  let success = Circuit_breaker.call cb (fun () -> risky_operation ()) in

  if not success then
    Printf.printf "Circuit is open, request rejected\n"
type state =
  1. | Closed
  2. | Open
  3. | Half_open

Circuit breaker state

type t

Circuit breaker (opaque)

val create : failure_threshold:int -> reset_timeout_ms:int -> unit -> t

Create a new circuit breaker

  • parameter failure_threshold

    Number of failures before opening circuit

  • parameter reset_timeout_ms

    Milliseconds to wait before trying Half_open

  • returns

    A new circuit breaker in Closed state

val call : t -> (unit -> 'a) -> 'a option

Call a protected function through the circuit breaker

  • parameter t

    The circuit breaker

  • parameter f

    Function to call if circuit is closed

  • returns

    Some result if call succeeded, None if circuit is open or call failed

val get_state : t -> state

Get current circuit state

  • parameter t

    The circuit breaker

  • returns

    Current state (Closed, Open, or Half_open)

val reset : t -> unit

Manually reset the circuit breaker

Forces circuit back to Closed state.

  • parameter t

    The circuit breaker

val get_stats : t -> int * state * float

Get failure statistics as (failure_count, current_state, last_failure_time)

  • parameter t

    The circuit breaker

  • returns

    Statistics tuple: (failure_count, current_state, last_failure_time)