Coffrify.Runtime.CircuitBreaker (Coffrify v0.9.0)

View Source

A GenServer-based circuit breaker that guards a remote endpoint from cascading failure.

States: :closed (allow) → :open (deny) → :half_open (probe) → :closed.

Usage

{:ok, breaker} = Coffrify.Runtime.CircuitBreaker.start_link(
  failure_threshold: 5,
  open_ms: 30_000,
  name: MyApp.CoffrifyBreaker
)

client = Coffrify.new(api_key: key, circuit_breaker: breaker)

When the breaker is open, the next call raises Coffrify.Error.CircuitOpen with the retry_at_ms timestamp.

Summary

Functions

Returns a specification to start this module under a supervisor.

Execute fun through the breaker.

Reset the breaker to :closed.

Return the current breaker snapshot.

Start a circuit breaker process.

Types

opts()

@type opts() :: [
  failure_threshold: pos_integer(),
  open_ms: pos_integer(),
  success_threshold_half_open: pos_integer(),
  name: GenServer.name()
]

state_name()

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

Functions

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

exec(server, fun)

@spec exec(GenServer.server(), (-> result)) :: result when result: var

Execute fun through the breaker.

Raises Coffrify.Error.CircuitOpen if the breaker is :open. Any exception raised by fun is counted as a failure and re-raised.

reset(server)

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

Reset the breaker to :closed.

snapshot(server)

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

Return the current breaker snapshot.

start_link(opts \\ [])

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

Start a circuit breaker process.

Options:

  • :failure_threshold (default 5) — consecutive failures to trip.
  • :open_ms (default 30_000) — duration the breaker stays open.
  • :success_threshold_half_open (default 1) — probes to recover.
  • :name — optional GenServer name.