Convert Figma logo to code with AI

rubyist logocircuitbreaker

Circuit Breakers in Go

1,123
109
1,123
22

Top Related Projects

24,073

Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.

Quick Overview

CircuitBreaker is a Ruby gem that implements the Circuit Breaker pattern. It helps prevent cascading failures in distributed systems by temporarily disabling problematic services, allowing them time to recover and protecting the system from repeated failures.

Pros

  • Simple and lightweight implementation of the Circuit Breaker pattern
  • Customizable failure thresholds and retry timeouts
  • Supports both block-based and method-based circuit breakers
  • Includes a monitoring interface for tracking circuit state

Cons

  • Limited documentation and examples
  • Not actively maintained (last update was in 2017)
  • Lacks advanced features like half-open state or adaptive thresholds
  • No built-in support for distributed circuit breakers

Code Examples

  1. Basic usage with a block:
cb = CircuitBreaker.new(threshold: 5, timeout: 20)

cb.execute do
  # Your code that might fail
  api.make_request
end
  1. Method-based circuit breaker:
class ApiClient
  include CircuitBreaker

  circuit_method :make_request, threshold: 5, timeout: 20

  def make_request
    # Your API request code
  end
end
  1. Custom error handling:
cb = CircuitBreaker.new(threshold: 3, timeout: 30)

cb.execute do
  result = api.make_request
  raise CustomError if result.status != :ok
  result
end

Getting Started

To use CircuitBreaker in your Ruby project:

  1. Add to your Gemfile:

    gem 'circuitbreaker'
    
  2. Install the gem:

    bundle install
    
  3. Use in your code:

    require 'circuit_breaker'
    
    cb = CircuitBreaker.new(threshold: 5, timeout: 20)
    cb.execute { your_code_here }
    

Competitor Comparisons

24,073

Hystrix is a latency and fault tolerance library designed to isolate points of access to remote systems, services and 3rd party libraries, stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.

Pros of Hystrix

  • More comprehensive fault tolerance library with features beyond circuit breaking
  • Supports multiple programming languages and frameworks
  • Provides real-time monitoring and configuration capabilities

Cons of Hystrix

  • More complex to set up and use compared to simpler alternatives
  • Heavier resource footprint due to its extensive feature set
  • No longer actively maintained (in maintenance mode since 2018)

Code Comparison

Circuitbreaker (Ruby):

CircuitBreaker.new do |cb|
  cb.timeout = 5
  cb.failure_threshold = 5
  cb.retry_after = 30
end

Hystrix (Java):

HystrixCommand.Setter config = HystrixCommand.Setter
    .withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))
    .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
        .withCircuitBreakerRequestVolumeThreshold(20)
        .withCircuitBreakerSleepWindowInMilliseconds(5000)
        .withCircuitBreakerErrorThresholdPercentage(50)
    );

Circuitbreaker is a lightweight Ruby gem focused specifically on implementing the circuit breaker pattern. It offers a simple API for basic circuit breaking functionality.

Hystrix, on the other hand, is a more feature-rich fault tolerance library developed by Netflix. It provides circuit breaking along with other resilience patterns like bulkheading and fallbacks. Hystrix offers more advanced configuration options and monitoring capabilities but comes with increased complexity and resource usage.

While Circuitbreaker is Ruby-specific, Hystrix supports multiple languages and integrates well with various frameworks. However, it's worth noting that Hystrix is no longer actively developed, which may impact its long-term viability for new projects.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

circuitbreaker

Circuitbreaker provides an easy way to use the Circuit Breaker pattern in a Go program.

Circuit breakers are typically used when your program makes remote calls. Remote calls can often hang for a while before they time out. If your application makes a lot of these requests, many resources can be tied up waiting for these time outs to occur. A circuit breaker wraps these remote calls and will trip after a defined amount of failures or time outs occur. When a circuit breaker is tripped any future calls will avoid making the remote call and return an error to the caller. In the meantime, the circuit breaker will periodically allow some calls to be tried again and will close the circuit if those are successful.

You can read more about this pattern and how it's used at:

GoDoc

Installation

  go get github.com/rubyist/circuitbreaker

Examples

Here is a quick example of what circuitbreaker provides

// Creates a circuit breaker that will trip if the function fails 10 times
cb := circuit.NewThresholdBreaker(10)

events := cb.Subscribe()
go func() {
  for {
    e := <-events
    // Monitor breaker events like BreakerTripped, BreakerReset, BreakerFail, BreakerReady
  }
}()

cb.Call(func() error {
	// This is where you'll do some remote call
	// If it fails, return an error
}, 0)

Circuitbreaker can also wrap a time out around the remote call.

// Creates a circuit breaker that will trip after 10 failures
// using a time out of 5 seconds
cb := circuit.NewThresholdBreaker(10)

cb.Call(func() error {
  // This is where you'll do some remote call
  // If it fails, return an error
}, time.Second * 5) // This will time out after 5 seconds, which counts as a failure

// Proceed as above

Circuitbreaker can also trip based on the number of consecutive failures.

// Creates a circuit breaker that will trip if 10 consecutive failures occur
cb := circuit.NewConsecutiveBreaker(10)

// Proceed as above

Circuitbreaker can trip based on the error rate.

// Creates a circuit breaker based on the error rate
cb := circuit.NewRateBreaker(0.95, 100) // trip when error rate hits 95%, with at least 100 samples

// Proceed as above

If it doesn't make sense to wrap logic in Call(), breakers can be handled manually.

cb := circuit.NewThresholdBreaker(10)

for {
  if cb.Ready() {
    // Breaker is not tripped, proceed
    err := doSomething()
    if err != nil {
      cb.Fail() // This will trip the breaker once it's failed 10 times
      continue
    }
    cb.Success()
  } else {
    // Breaker is in a tripped state.
  }
}

Circuitbreaker also provides a wrapper around http.Client that will wrap a time out around any request.

// Passing in nil will create a regular http.Client.
// You can also build your own http.Client and pass it in
client := circuit.NewHTTPClient(time.Second * 5, 10, nil)

resp, err := client.Get("http://example.com/resource.json")

See the godoc for more examples.

Bugs, Issues, Feedback

Right here on GitHub: https://github.com/rubyist/circuitbreaker