ExMCP.Transport.Beam.CircuitBreaker (ex_mcp v0.9.2)
View SourceCircuit breaker implementation for MCP service protection in BEAM transport clustering.
Implements the circuit breaker pattern to protect services from cascading failures. Tracks failure rates and automatically opens circuits when thresholds are exceeded, preventing requests from reaching failing services.
Circuit States
:closed- Normal operation, requests flow through:open- Circuit is open, requests are failed fast:half_open- Testing if service has recovered
Configuration Options
failure_threshold- Number of failures before opening circuitsuccess_threshold- Number of successes needed to close circuit from half-opentimeout- Time to wait before transitioning from open to half-openfailure_rate_threshold- Percentage of failures that triggers circuit openingminimum_throughput- Minimum requests before considering failure rate
Example Usage
# Create a circuit breaker
circuit_breaker = CircuitBreaker.new(%{
failure_threshold: 5,
timeout: 60000,
success_threshold: 3
})
# Record failures and successes
updated_cb = CircuitBreaker.record_failure(circuit_breaker)
updated_cb = CircuitBreaker.record_success(circuit_breaker)
# Check if requests should be allowed
case CircuitBreaker.allow_request?(updated_cb) do
true -> # Make request
false -> # Fail fast
end
Summary
Functions
Checks if a request should be allowed based on the current circuit state.
Checks if a request should be allowed and returns both the result and updated circuit breaker.
Forces the circuit breaker to a specific state.
Gets the current state of the circuit breaker.
Gets circuit breaker statistics.
Creates a new circuit breaker with the given configuration.
Records a failed operation and updates the circuit breaker state.
Records a successful operation and updates the circuit breaker state.
Resets the circuit breaker to its initial state.
Types
@type config() :: %{ failure_threshold: non_neg_integer(), success_threshold: non_neg_integer(), timeout: non_neg_integer(), failure_rate_threshold: float(), minimum_throughput: non_neg_integer(), reset_timeout: non_neg_integer() }
@type state() :: :closed | :open | :half_open
@type t() :: %ExMCP.Transport.Beam.CircuitBreaker{ config: map(), failure_count: non_neg_integer(), last_failure_time: integer() | nil, last_success_time: integer() | nil, opened_at: integer() | nil, state: state(), stats: map(), success_count: non_neg_integer() }
Functions
Checks if a request should be allowed based on the current circuit state.
Checks if a request should be allowed and returns both the result and updated circuit breaker.
Forces the circuit breaker to a specific state.
Gets the current state of the circuit breaker.
Gets circuit breaker statistics.
Creates a new circuit breaker with the given configuration.
Records a failed operation and updates the circuit breaker state.
Records a successful operation and updates the circuit breaker state.
Resets the circuit breaker to its initial state.