These days, it is quite common for our application to depend on others, especially if we are working in a microservices environment. It is quite common for our application to start reporting errors, and when investigating, we notice that some API from a partner team or supplier is down.
A good practice to increase the resilience of our application is to cut communication with those applications that are in a deprecated state. Observing other areas, we absorb the concept of Circuit Breaker from Electrical Engineering. An equipment, or circuit breaker, is placed in it, which automatically turns off if a fault occurs. This is very common in our homes, which have circuit breakers that turn off by themselves if the electrical network starts to become unstable.
In computing, our Circuit Breaker is a little more complex, since we also define an intermediate state. The drawing below better explains how a Circuit Breaker works:
Finally, the states are:
Pretty cool, right? But to better exemplify the concept, how about we do it in practice?
First, let's build our service A. It will be responsible for receiving requests, that is, it will be the service that our application depends on, the supplier's service, or etc. To make it easier, we will expose two endpoints, a /success that will always return 200 and a /failure that will always return 500.
package main import ( "fmt" "log" "net/http" ) func main() { http.HandleFunc("/success", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }) http.HandleFunc("/failure", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) }) fmt.Println("Server is running at http://localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
Service B will be responsible for calling service A. It will build our circuit breaker. Lucky for us, the Go community already has the gobreaker library that implements the pattern! First, we define the properties of our breaker:
var st gobreaker.Settings st.Name = "Circuit Breaker PoC" st.Timeout = time.Second * 5 st.MaxRequests = 2 st.ReadyToTrip = func(counts gobreaker.Counts) bool { return counts.ConsecutiveFailures >= 1 }
Although the library allows us to customize more things, we will focus on three:
Then we can initialize the breaker and make requests:
cb := gobreaker.NewCircuitBreaker[int](st) url := "http://localhost:8080/success" cb.Execute(func() (int, error) { return Get(url) }) fmt.Println("Circuit Breaker state:", cb.State()) // closed! url = "http://localhost:8080/failure" cb.Execute(func() (int, error) { return Get(url) }) fmt.Println("Circuit Breaker state:", cb.State()) // open! time.Sleep(time.Second * 6) url = "http://localhost:8080/success" cb.Execute(func() (int, error) { return Get(url) }) fmt.Println("Circuit Breaker state:", cb.State()) // half-open! url = "http://localhost:8080/success" cb.Execute(func() (int, error) { return Get(url) }) fmt.Println("Circuit Breaker state:", cb.State()) // closed!
We can notice that gobreaker works as a wrapper around a function. If the function returns an error, it increases the number of errors, if not, it increases the number of successes. So let's define this function:
func Get(url string) (int, error) { r, _ := http.Get(url) if r.StatusCode != http.StatusOK { return r.StatusCode, fmt.Errorf("failed to get %s", url) } return r.StatusCode, nil }
And we have our Go service using a circuit breaker! By using this pattern, you can increase the resilience and fault tolerance of your services. We can notice that when using the library, the complexity was completely abstracted, making the process of integrating this into our daily lives very simple. If you want to see the entire proof of concept code, just go here.
If you are curious to know other resilience patterns, Elton Minetto published a great post on the topic!
Tell me what you think of this post in the comments and here's a question: have you ever used circuit breakers before? Oh, you can also find me on my personal blog!
The above is the detailed content of Circuit Breaker in Go applications. For more information, please follow other related articles on the PHP Chinese website!