Raxol.Core.CircuitBreaker (Raxol v2.0.1)

View Source

Circuit breaker implementation for external API calls.

Prevents cascading failures by monitoring external service calls and temporarily blocking requests when a service is experiencing issues.

States

  • Closed: Normal operation, requests pass through
  • Open: Service is failing, requests are blocked
  • Half-Open: Testing if service has recovered

Features

  • Automatic state transitions based on failure rates
  • Configurable thresholds and timeouts
  • Metrics collection and monitoring
  • Fallback strategies
  • Exponential backoff

Usage

# Define a circuit breaker for an API
defmodule MyApp.APIBreaker do
  use Raxol.Core.CircuitBreaker,

alias Raxol.Core.Runtime.Log

    name: :api_breaker,
    failure_threshold: 5,
    timeout: 30_000
end

# Use the circuit breaker
CircuitBreaker.call(:api_breaker, fn ->
  HTTPoison.get("https://api.example.com/data")
end)

Summary

Functions

Executes a function through the circuit breaker.

Executes a function with automatic fallback on circuit open.

Returns a specification to start this module under a supervisor.

Manually resets the circuit breaker to closed state.

Gets the current state of the circuit breaker.

Gets circuit breaker statistics.

Types

breaker_name()

@type breaker_name() :: atom()

breaker_opts()

@type breaker_opts() :: [
  failure_threshold: pos_integer(),
  success_threshold: pos_integer(),
  timeout: pos_integer(),
  half_open_timeout: pos_integer(),
  reset_timeout: pos_integer(),
  failure_rate_threshold: float(),
  volume_threshold: pos_integer(),
  fallback_fn: (-> term()),
  on_state_change: (state(), state() -> :ok)
]

state()

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

Functions

call(breaker_name, fun, timeout \\ 5000)

@spec call(breaker_name(), (-> result), timeout()) :: {:ok, result} | {:error, term()}
when result: term()

Executes a function through the circuit breaker.

call_with_fallback(breaker_name, fun, fallback_fn, timeout \\ 5000)

@spec call_with_fallback(breaker_name(), (-> result), (-> result), timeout()) ::
  result
when result: term()

Executes a function with automatic fallback on circuit open.

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

reset(breaker_name)

@spec reset(breaker_name()) :: :ok

Manually resets the circuit breaker to closed state.

start_link(init_opts \\ [])

state(breaker_name)

@spec state(breaker_name()) :: state()

Gets the current state of the circuit breaker.

stats(breaker_name)

@spec stats(breaker_name()) :: map()

Gets circuit breaker statistics.