
Circuit is an efficient and feature complete Hystrix like Go implementation of the circuit breaker pattern. Learn more about the problems Hystrix and other circuit breakers solve on the Hystrix Wiki. A short summary of advantages are:
There are a large number of examples on the godoc that are worth looking at. They tend to be more up to date than the README doc.
See UPGRADE_GUIDE.md for upgrade instructions if you're upgrading from v3 to v4.
This example shows how to create a hello-world circuit from the circuit manager
// Manages all our circuits
h := circuit.Manager{}
// Create a circuit with a unique name
c := h.MustCreateCircuit("hello-world")
// Call the circuit
errResult := c.Execute(context.Background(), func(ctx context.Context) error {
return nil
}, nil)
fmt.Println("Result of execution:", errResult)
// Output: Result of execution: <nil>
This example shows how fallbacks execute to return alternate errors or provide logic when the circuit is open.
// You can create circuits without using the manager
c := circuit.NewCircuitFromConfig("hello-world-fallback", circuit.Config{})
errResult := c.Execute(context.Background(), func(ctx context.Context) error {
return errors.New("this will fail")
}, func(ctx context.Context, err error) error {
fmt.Println("Circuit failed with error, but fallback returns nil")
return nil
})
fmt.Println("Execution result:", errResult)
// Output: Circuit failed with error, but fallback returns nil
// Execution result: <nil>
It is recommended to use circuit.Execute and a context aware function. If, however, you want to exit
your run function early and leave it hanging (possibly forever), then you can call circuit.Go.
h := circuit.Manager{}
c := h.MustCreateCircuit("untrusting-circuit", circuit.Config{
Execution: circuit.ExecutionConfig{
// Time out the context after a few ms
Timeout: time.Millisecond * 30,
},
})
errResult := c.Go(context.Background(), func(ctx context.Context) error {
// Sleep 30 seconds, way longer than our timeout
time.Sleep(time.Second * 30)
return nil
}, nil)
fmt.Printf("err=%v", errResult)
// Output: err=context deadline exceeded
All configuration parameters are documented in config.go. Your circuit open/close logic configuration is documented with the logic. For hystrix, this configuration is in closers/hystrix and well documented on the Hystrix wiki.
This example configures the circuit to use Hystrix open/close logic with the default Hystrix parameters
configuration := hystrix.Factory{
// Hystrix open logic is to open the circuit after an % of errors
ConfigureOpener: hystrix.ConfigureOpener{
// We change the default to wait for 10 requests, not 20, before checking to close
RequestVolumeThreshold: 10,
// The default values match what hystrix does by default
},
// Hystrix close logic is to sleep then check
ConfigureCloser: hystrix.ConfigureCloser{
// The default values match what hystrix does by default
},
}
h := circuit.Manager{
// Tell the manager to use this configuration factory whenever it makes a new circuit
DefaultCircuitProperties: []circuit.CommandPropertiesConstructor{configuration.Configure},
}
// This circuit will inherit the configuration from the example
c := h.MustCreateCircuit("hystrix-circuit")
fmt.Println("This is a hystrix configured circuit", c.Name())
// Output: This is a hystrix configured circuit hystrix-circuit
Dashboard metrics can be enabled with the MetricEventStream object. This example creates an event stream handler, starts it, then later closes the handler
// metriceventstream uses rolling stats to report circuit information
sf := rolling.StatFactory{}
h := circuit.Manager{
DefaultCircuitProperties: []circuit.CommandPropertiesConstructor{sf.CreateConfig},
}
es := metriceventstream.MetricEventStream{
Manager: &h,
}
go func() {
if err := es.Start(); err != nil {
log.Fatal(err)
}
}()
// ES is a http.Handler, so you can pass it directly to your mux
http.Handle("/hystrix.stream", &es)
// ...
if err := es.Close(); err != nil {
log.Fatal(err)
}
// Output:
If you wanted to publish hystrix information on Expvar, you can register your manager.
h := circuit.Manager{}
expvar.Publish("hystrix", h.Var())
Implement interfaces CmdMetricCollector or FallbackMetricCollector to know what happens with commands or fallbacks. Then pass those implementations to configure.
config := circuit.Config{
Metrics: circuit.MetricsCollectors{
Run: []circuit.RunMetrics{
// Here is where I would insert my custom metric collector
},
},
}
circuit.NewCircuitFromConfig("custom-metrics", config)
Code executed with Execute does not spawn a goroutine and panics naturally go up the call stack to the caller.
This is also true for Go, where we attempt to recover and throw panics on the same stack that
calls Go. This example will panic, and the panic can be caught up the stack.
```go h := circuit.Manager{} c := h.MustCreateCircuit("panic_up")
defer func() { r := recover() if r != nil { fmt.Println("I recovered from a panic", r) } }() c.Execute(context.Background(), func(ctx context.Context) error { panic("oh no") }, nil) // Output: I recovered from a panic oh no
## [Runtime configuration changes](https://godoc.org/github.com/cep21/circuit/closers/hystrix#example-Closer-SetConfigThreadSafe)
Most configuration properties on
[the Hystrix Configuration page](https://github.com/Netflix/Hystrix/wiki/Configuration) that say they are modifyable at
runtime can be changed on the Circuit in a thread safe way. Most of the ones that cannot are related to stat
collection.
This example shows how to update hystrix configuration at runtime.
```go
// Start off using the defaults
configuration := hystrix.ConfigFactory{}
h := circuit.Manager{
// Tell the manager to use this configuration factory whenever it makes a new circuit
DefaultCircuitProperties: []circuit.CommandPropertiesConstructor{configuration.Configure},
}
c := h.MustCreateCircuit("hystrix-circuit")
fmt.Println("The default sleep window", c.OpenToClose.(*hystrix.Closer).Config().SleepWindow)
// This configuration update function is thread safe. We can modify this at runtime while the circuit is active
c.OpenToClose.(*hystrix.Closer).SetConfigThreadSafe(hystrix.ConfigureCloser{
SleepWindow: time.Second * 3,
})
fmt.Println("The new sleep window", c.OpenToClose.(*hystrix.Closer).Config().SleepWindow)
// Output:
// The default sleep window 5s
// The new sleep window 3s
If the context passed into a circuit function ends, before the circuit can
finish, it does not count the circuit as unhealthy. You can disable this
behavior with the IgnoreInterrupts flag.
This example proves that terminating a circuit call early because the passed in context died does not, by default, count as an error on the circuit. It also demonstrates setting up internal stat collection by default for all circuits
// Inject stat collection to prove these failures don't count
f := rolling.StatFactory{}
manager := circuit.Manager{
DefaultCircuitProperties: []circuit.CommandPropertiesConstructor{
f.CreateConfig,
},
}
c := manager.MustCreateCircuit("don't fail me bro")
// The passed in context times out in one millisecond
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()
errResult := c.Execute(ctx, func(ctx context.Context) error {
select {
case <- ctx.Done():
// This will return early, with an error, since the parent context was canceled after 1 ms
return ctx.Err()
case <- time.After(time.Hour):
panic("We never actually get this far")
}
}, nil)
rs := f.RunStats("don't fail me bro")
fmt.Println("errResult is", errResult)
fmt.Println("The error and timeout count is", rs.ErrTimeouts.TotalSum() + rs.ErrFailures.TotalSum())
// Output: errResult is context deadline exceeded
// The error and timeout count is 0
Configuration factories are supported on the root manager object. This allows you to create dynamic configuration per circuit name.
You can use DefaultCircuitProperties to set configuration dynamically for any circuit
myFactory := func(circuitName string) circuit.Config {
timeoutsByName := map[string]time.Duration{
"v1": time.Second,
"v2": time.Second * 2,
}
customTimeout := timeoutsByName[circuitName]
if customTimeout == 0 {
// Just return empty if you don't want to set any config
return circuit.Config{}
}
return circuit.Config{
Execution: circuit.ExecutionConfig{
Timeout: customTimeout,
},
}
}
// Hystrix manages circuits with unique names
h := circuit.Manager{
DefaultCircuitProperties: []circuit.CommandPropertiesConstructor{myFactory},
}
h.MustCreateCircuit("v1")
fmt.Println("The timeout of v1 is", h.GetCircuit("v1").Config().Execution.Timeout)
// Output: The timeout of v1 is 1s
Most services have the concept of an SLA, or service level agreement. Unfortunantly, this is usually tracked by the service owners, which creates incentives for people to inflate the health of their service.
This Circuit implementation formalizes an SLO of the template "X% of requests will return faster than Y ms". This is a value that canont be calculated just by looking at the p90 or p99 of requests in aggregate, but must be tracked per request. You can define a SLO for your service, which is a time less than the timeout time of a request, that works as a promise of health for the service. You can then report per circuit not just fail/pass but an extra "healthy" % over time that counts only requests that resopnd quickly enough.
This example creates a SLO tracker that counts failures at less than 20 ms. You will need to provide your own Collectors.
```go sloTrackerFactory := responsetimeslo.Factory{ Config: responsetimeslo.Config{ // Consider requests faster than 20 ms as passing MaximumHealthyTime: time.Millisecond * 20, }, // Pass in your collector here: for example, statsd CollectorConstructors: nil, } h := circuit.Manager{ DefaultCircuitProperties: []circ
$ claude mcp add circuit \
-- python -m otcore.mcp_server <graph>