search
HomeBackend DevelopmentGolangCircuit Breaker in Go applications

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:

Circuit Breaker em aplicações Go

Finally, the states are:

  • open: there is no communication between applications. Upon reaching this state, a timer starts to allow time for the reset service. At the end of the timer, we transition to half-open.
  • closed: there is communication between applications. For each failed request, a counter is updated. If the failure limit is reached, we transition the circuit to open.
  • half-open: recovery state until communication can flow completely. In it, a success counter is updated with each request. If the ideal number of successes is reached, we move the circuit to closed. If requests fail, we transition back to open.

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:

  • Timeout: the time that the circuit will remain in the open state. In our case, the time was set to 5 seconds.
  • MaxRequests: number of successful requests before going to closed. In our example, we set it to 2 requests.
  • ReadyToTrip: defines the condition to transition from closed to open. To make it easier, let's say one failure is enough.

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Mastering Go Strings: A Deep Dive into the 'strings' PackageMastering Go Strings: A Deep Dive into the 'strings' PackageMay 12, 2025 am 12:05 AM

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

'encoding/binary' Package in Go: Your Go-To for Binary Operations'encoding/binary' Package in Go: Your Go-To for Binary OperationsMay 12, 2025 am 12:03 AM

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Go Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageGo Byte Slice Manipulation Tutorial: Mastering the 'bytes' PackageMay 12, 2025 am 12:02 AM

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.

How do you use the 'strings' package to manipulate strings in Go?How do you use the 'strings' package to manipulate strings in Go?May 12, 2025 am 12:01 AM

You can use the "strings" package in Go to manipulate strings. 1) Use strings.TrimSpace to remove whitespace characters at both ends of the string. 2) Use strings.Split to split the string into slices according to the specified delimiter. 3) Merge string slices into one string through strings.Join. 4) Use strings.Contains to check whether the string contains a specific substring. 5) Use strings.ReplaceAll to perform global replacement. Pay attention to performance and potential pitfalls when using it.

How to use the 'bytes' package to manipulate byte slices in Go (step by step)How to use the 'bytes' package to manipulate byte slices in Go (step by step)May 12, 2025 am 12:01 AM

ThebytespackageinGoishighlyeffectiveforbyteslicemanipulation,offeringfunctionsforsearching,splitting,joining,andbuffering.1)Usebytes.Containstosearchforbytesequences.2)bytes.Splithelpsbreakdownbyteslicesusingdelimiters.3)bytes.Joinreconstructsbytesli

GO bytes package: What are the alternatives?GO bytes package: What are the alternatives?May 11, 2025 am 12:11 AM

ThealternativestoGo'sbytespackageincludethestringspackage,bufiopackage,andcustomstructs.1)Thestringspackagecanbeusedforbytemanipulationbyconvertingbytestostringsandback.2)Thebufiopackageisidealforhandlinglargestreamsofbytedataefficiently.3)Customstru

Manipulating Byte Slices in Go: The Power of the 'bytes' PackageManipulating Byte Slices in Go: The Power of the 'bytes' PackageMay 11, 2025 am 12:09 AM

The"bytes"packageinGoisessentialforefficientlymanipulatingbyteslices,crucialforbinarydata,networkprotocols,andfileI/O.ItoffersfunctionslikeIndexforsearching,Bufferforhandlinglargedatasets,Readerforsimulatingstreamreading,andJoinforefficient

Go Strings Package: A Comprehensive Guide to String ManipulationGo Strings Package: A Comprehensive Guide to String ManipulationMay 11, 2025 am 12:08 AM

Go'sstringspackageiscrucialforefficientstringmanipulation,offeringtoolslikestrings.Split(),strings.Join(),strings.ReplaceAll(),andstrings.Contains().1)strings.Split()dividesastringintosubstrings;2)strings.Join()combinesslicesintoastring;3)strings.Rep

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool