Top Related Projects
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.
A standard library for microservices.
Circuit Breaker implemented in Go
Circuit Breakers in Go
Resiliency patterns for golang
Quick Overview
hystrix-go is a Go implementation of Netflix's Hystrix library, which provides latency and fault tolerance for distributed systems. It helps prevent cascading failures in complex systems by isolating points of access to remote systems, services, and 3rd party libraries.
Pros
- Implements circuit breaker pattern for improved system resilience
- Provides real-time monitoring and configuration of failure thresholds
- Supports fallback mechanisms for graceful degradation
- Easy integration with existing Go applications
Cons
- Limited documentation compared to the original Java implementation
- Some features from the Java version may not be available
- Requires careful configuration to avoid false positives or negatives
- May introduce additional complexity to the codebase
Code Examples
- Creating a command:
import "github.com/afex/hystrix-go/hystrix"
// Define a command
hystrix.Go("my_command", func() error {
// Your code here
return nil
}, func(err error) error {
// Fallback function
return nil
})
- Configuring a command:
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
Timeout: 1000,
MaxConcurrentRequests: 100,
ErrorPercentThreshold: 25,
})
- Using the circuit breaker with HTTP requests:
import "github.com/afex/hystrix-go/hystrix"
import "net/http"
client := &http.Client{}
hystrix.Go("http_request", func() error {
resp, err := client.Get("http://example.com")
if err != nil {
return err
}
defer resp.Body.Close()
// Process response
return nil
}, nil)
Getting Started
To use hystrix-go in your project:
-
Install the package:
go get github.com/afex/hystrix-go/hystrix
-
Import the package in your Go code:
import "github.com/afex/hystrix-go/hystrix"
-
Define and configure your commands:
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{ Timeout: 1000, MaxConcurrentRequests: 100, ErrorPercentThreshold: 25, })
-
Use the circuit breaker in your code:
hystrix.Go("my_command", func() error { // Your code here return nil }, nil)
Competitor Comparisons
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 mature and widely adopted project with extensive documentation
- Supports multiple programming languages (Java, Go, Python, etc.)
- Offers a dashboard for real-time monitoring and configuration
Cons of Hystrix
- No longer actively maintained (in maintenance mode since 2018)
- Heavier and more complex implementation compared to hystrix-go
- Requires additional setup for non-Java languages
Code Comparison
Hystrix (Java):
HystrixCommand<String> command = new HystrixCommand<String>(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")) {
@Override
protected String run() {
return "Hello, Hystrix!";
}
};
String result = command.execute();
hystrix-go:
hystrix.Go("my_command", func() error {
// Do stuff
return nil
}, nil)
Additional Notes
- hystrix-go is a lightweight Go implementation inspired by Hystrix
- hystrix-go focuses on simplicity and Go-specific features
- Hystrix provides more advanced features like request collapsing and caching
- hystrix-go is actively maintained and may be a better choice for Go-specific projects
- Both libraries implement circuit breaker patterns for fault tolerance
A standard library for microservices.
Pros of kit
- Comprehensive microservices toolkit with support for various patterns and protocols
- Modular design allows for easy integration of specific components
- Active development and community support
Cons of kit
- Steeper learning curve due to its extensive feature set
- May be overkill for simpler applications or services
- Requires more setup and configuration compared to focused libraries
Code Comparison
hystrix-go example:
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
Timeout: 1000,
MaxConcurrentRequests: 100,
ErrorPercentThreshold: 25,
})
hystrix.Do("my_command", func() error {
// Do work here
return nil
}, nil)
kit example:
var svc MyService
svc = myServiceImplementation{}
svc = loggingMiddleware{logger, svc}
svc = instrumentingMiddleware{
requestCount: kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{}, []string{"method"}),
requestLatency: kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{}, []string{"method"}),
svc,
}
hystrix-go focuses specifically on circuit breaking and fault tolerance, while kit provides a more comprehensive toolkit for building microservices. hystrix-go is simpler to integrate for its specific use case, while kit offers more flexibility and features at the cost of increased complexity.
Circuit Breaker implemented in Go
Pros of gobreaker
- Simpler and more lightweight implementation
- Better documentation and examples
- More active maintenance and recent updates
Cons of gobreaker
- Fewer features compared to hystrix-go (e.g., no request collapsing)
- Less configurable than hystrix-go
- Not a direct port of Netflix's Hystrix, which may be a consideration for some users
Code Comparison
hystrix-go:
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
Timeout: 1000,
MaxConcurrentRequests: 100,
ErrorPercentThreshold: 25,
})
err := hystrix.Do("my_command", func() error {
// Make API call or run logic here
return nil
}, nil)
gobreaker:
cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{
Name: "my-circuit-breaker",
MaxRequests: 100,
Interval: time.Minute,
Timeout: time.Second,
})
result, err := cb.Execute(func() (interface{}, error) {
// Make API call or run logic here
return nil, nil
})
Both libraries provide circuit breaker functionality, but hystrix-go offers more configuration options and features, while gobreaker has a simpler API and is easier to integrate into existing Go projects. The choice between the two depends on the specific requirements of your application and the level of control you need over the circuit breaker behavior.
Circuit Breakers in Go
Pros of circuitbreaker
- Simpler and more lightweight implementation
- Easier to integrate into existing Go projects
- More flexible configuration options for circuit breaker behavior
Cons of circuitbreaker
- Less comprehensive feature set compared to hystrix-go
- Lacks built-in metrics and monitoring capabilities
- Not as actively maintained or widely adopted in the community
Code Comparison
circuitbreaker:
cb := circuit.NewBreaker(&circuit.Options{
BackOff: 1 * time.Second,
MaxRetries: 3,
})
err := cb.Call(func() error {
// Your code here
return nil
}, 0)
hystrix-go:
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
Timeout: 1000,
MaxConcurrentRequests: 100,
ErrorPercentThreshold: 25,
})
err := hystrix.Do("my_command", func() error {
// Your code here
return nil
}, nil)
Both libraries provide circuit breaker functionality for Go applications, but hystrix-go offers a more feature-rich implementation based on Netflix's Hystrix library. circuitbreaker is simpler and may be easier to integrate into existing projects, while hystrix-go provides more advanced features like metrics, fallbacks, and configurable thresholds. The choice between the two depends on the specific requirements of your project and the level of circuit breaker functionality needed.
Resiliency patterns for golang
Pros of go-resiliency
- Offers a broader set of resilience patterns (Circuit Breaker, Retrier, Semaphore, Timeout)
- Lightweight and easy to integrate into existing Go projects
- More flexible configuration options for each pattern
Cons of go-resiliency
- Less actively maintained compared to hystrix-go
- Lacks some advanced features like metrics and dashboard integration
- May require more manual implementation for complex scenarios
Code Comparison
hystrix-go:
hystrix.Go("my_command", func() error {
// Do stuff
}, nil)
go-resiliency:
cb := circuitbreaker.NewCircuitBreaker(circuitbreaker.DefaultSettings)
err := cb.Run(func() error {
// Do stuff
})
Both libraries provide circuit breaker functionality, but go-resiliency offers a more explicit approach to configuration and execution. hystrix-go uses a global configuration model, while go-resiliency allows for more localized settings.
go-resiliency provides a wider range of resilience patterns, making it more versatile for different scenarios. However, hystrix-go offers better integration with metrics and monitoring tools, which can be crucial for large-scale applications.
In terms of community support and ongoing development, hystrix-go has a slight edge, with more recent updates and a larger user base. This could be an important factor for long-term project maintenance and support.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
hystrix-go
Hystrix is a great project from Netflix.
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.
I think the Hystrix patterns of programmer-defined fallbacks and adaptive health monitoring are good for any distributed system. Go routines and channels are great concurrency primitives, but don't directly help our application stay available during failures.
hystrix-go aims to allow Go programmers to easily build applications with similar execution semantics of the Java-based Hystrix library.
For more about how Hystrix works, refer to the Java Hystrix wiki
For API documentation, refer to GoDoc
How to use
import "github.com/afex/hystrix-go/hystrix"
Execute code as a Hystrix command
Define your application logic which relies on external systems, passing your function to hystrix.Go
. When that system is healthy this will be the only thing which executes.
hystrix.Go("my_command", func() error {
// talk to other services
return nil
}, nil)
Defining fallback behavior
If you want code to execute during a service outage, pass in a second function to hystrix.Go
. Ideally, the logic here will allow your application to gracefully handle external services being unavailable.
This triggers when your code returns an error, or whenever it is unable to complete based on a variety of health checks.
hystrix.Go("my_command", func() error {
// talk to other services
return nil
}, func(err error) error {
// do this when services are down
return nil
})
Waiting for output
Calling hystrix.Go
is like launching a goroutine, except you receive a channel of errors you can choose to monitor.
output := make(chan bool, 1)
errors := hystrix.Go("my_command", func() error {
// talk to other services
output <- true
return nil
}, nil)
select {
case out := <-output:
// success
case err := <-errors:
// failure
}
Synchronous API
Since calling a command and immediately waiting for it to finish is a common pattern, a synchronous API is available with the hystrix.Do
function which returns a single error.
err := hystrix.Do("my_command", func() error {
// talk to other services
return nil
}, nil)
Configure settings
During application boot, you can call hystrix.ConfigureCommand()
to tweak the settings for each command.
hystrix.ConfigureCommand("my_command", hystrix.CommandConfig{
Timeout: 1000,
MaxConcurrentRequests: 100,
ErrorPercentThreshold: 25,
})
You can also use hystrix.Configure()
which accepts a map[string]CommandConfig
.
Enable dashboard metrics
In your main.go, register the event stream HTTP handler on a port and launch it in a goroutine. Once you configure turbine for your Hystrix Dashboard to start streaming events, your commands will automatically begin appearing.
hystrixStreamHandler := hystrix.NewStreamHandler()
hystrixStreamHandler.Start()
go http.ListenAndServe(net.JoinHostPort("", "81"), hystrixStreamHandler)
Send circuit metrics to Statsd
c, err := plugins.InitializeStatsdCollector(&plugins.StatsdCollectorConfig{
StatsdAddr: "localhost:8125",
Prefix: "myapp.hystrix",
})
if err != nil {
log.Fatalf("could not initialize statsd client: %v", err)
}
metricCollector.Registry.Register(c.NewStatsdCollector)
FAQ
What happens if my run function panics? Does hystrix-go trigger the fallback?
No. hystrix-go does not use recover()
so panics will kill the process like normal.
Build and Test
- Install vagrant and VirtualBox
- Clone the hystrix-go repository
- Inside the hystrix-go directory, run
vagrant up
, thenvagrant ssh
cd /go/src/github.com/afex/hystrix-go
go test ./...
Top Related Projects
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.
A standard library for microservices.
Circuit Breaker implemented in Go
Circuit Breakers in Go
Resiliency patterns for golang
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot