Skip to content

Class HTM::CircuitBreaker

Inherits Object
Defined in lib/htm/circuit_breaker.rb

Circuit Breaker - Prevents cascading failures from external LLM services

Implements the circuit breaker pattern to protect against repeated failures when calling external LLM APIs for embeddings or tag extraction.

States: * :closed - Normal operation, requests flow through * :open - Circuit tripped, requests fail fast with CircuitBreakerOpenError * :half_open - Testing if service recovered, allows limited requests

@example Basic usage

breaker = HTM::CircuitBreaker.new(name: 'embedding')
result = breaker.call { external_api_call }

@example With custom thresholds

breaker = HTM::CircuitBreaker.new(
  name: 'tag_extraction',
  failure_threshold: 3,
  reset_timeout: 30
)

Constants

DEFAULT_FAILURE_THRESHOLD

Default configuration

DEFAULT_HALF_OPEN_MAX_CALLS

Seconds before trying half-open

DEFAULT_RESET_TIMEOUT

Failures before opening circuit

Attributes

failure_count [R]

Returns the value of attribute failure_count.

last_failure_time [R]

Returns the value of attribute last_failure_time.

name [R]

Returns the value of attribute name.

state [R]

Returns the value of attribute state.

Public Instance Methods

call()

Execute a block with circuit breaker protection - @raise [CircuitBreakerOpenError] If circuit is open - @raise [StandardError] If the block raises an error (after recording failure) - @return [Object] Result of the block if successful - @yield Block containing the protected operation

closed?()

Check if circuit is currently closed (normal operation) - @return [Boolean] true if circuit is closed

half_open?()

Check if circuit is in half-open state (testing recovery) - @return [Boolean] true if circuit is half-open

initialize(name:, failure_threshold: DEFAULT_FAILURE_THRESHOLD, reset_timeout: DEFAULT_RESET_TIMEOUT, half_open_max_calls: DEFAULT_HALF_OPEN_MAX_CALLS)

Initialize a new circuit breaker - @param name [String] Identifier for this circuit breaker (for logging) - @param failure_threshold [Integer] Number of failures before opening circuit - @param reset_timeout [Integer] Seconds to wait before attempting recovery - @param half_open_max_calls [Integer] Successful calls needed to close circuit - @return [CircuitBreaker] a new instance of CircuitBreaker

open?()

Check if circuit is currently open - @return [Boolean] true if circuit is open

reset!()

Manually reset the circuit breaker to closed state - @return [void]

stats()

Get current circuit breaker statistics - @return [Hash] Statistics including state, failure count, etc.