Snakepit.CircuitBreaker (Snakepit v0.8.7)

View Source

Circuit breaker for Python worker fault tolerance.

Implements the circuit breaker pattern to prevent cascading failures when workers are experiencing issues.

States

  • :closed - Normal operation, all calls allowed
  • :open - Failure threshold exceeded, calls rejected
  • :half_open - Testing if service recovered, limited calls allowed

Usage

{:ok, cb} = CircuitBreaker.start_link(name: :my_cb, failure_threshold: 5)

case CircuitBreaker.call(cb, fn -> risky_operation() end) do
  {:ok, result} -> handle_success(result)
  {:error, :circuit_open} -> handle_circuit_open()
  {:error, reason} -> handle_error(reason)
end

Summary

Functions

Checks if a call is allowed through the circuit.

Executes a function through the circuit breaker.

Returns a specification to start this module under a supervisor.

Records a failed call.

Records a successful call.

Resets the circuit breaker to closed state.

Starts a circuit breaker.

Returns the current circuit state.

Returns circuit breaker statistics.

Types

state()

@type state() :: :closed | :open | :half_open

t()

@type t() :: %{
  state: state(),
  failure_count: non_neg_integer(),
  success_count: non_neg_integer(),
  failure_threshold: pos_integer(),
  reset_timeout_ms: pos_integer(),
  half_open_max_calls: pos_integer(),
  half_open_calls: non_neg_integer(),
  last_failure_time: integer() | nil,
  name: atom() | nil
}

Functions

allow_call?(server)

@spec allow_call?(GenServer.server()) :: boolean()

Checks if a call is allowed through the circuit.

call(server, fun)

@spec call(GenServer.server(), (-> any())) :: any()

Executes a function through the circuit breaker.

Returns {:error, :circuit_open} if the circuit is open.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

record_failure(server)

@spec record_failure(GenServer.server()) :: :ok

Records a failed call.

record_success(server)

@spec record_success(GenServer.server()) :: :ok

Records a successful call.

reset(server)

@spec reset(GenServer.server()) :: :ok

Resets the circuit breaker to closed state.

start_link(opts \\ [])

@spec start_link(keyword()) :: GenServer.on_start()

Starts a circuit breaker.

Options

  • :name - GenServer name (optional)
  • :failure_threshold - Number of failures before opening (default: 5)
  • :reset_timeout_ms - Time before transitioning to half-open (default: 30000)
  • :half_open_max_calls - Max calls allowed in half-open state (default: 1)

state(server)

@spec state(GenServer.server()) :: state()

Returns the current circuit state.

stats(server)

@spec stats(GenServer.server()) :: map()

Returns circuit breaker statistics.