Backend Boilerplates go Advanced

Go Circuit Breaker Pattern

Simple circuit breaker for outbound HTTP calls in Go — open, closed, half-open states.

go
type State int
const (Closed State = iota; Open; HalfOpen)

type CircuitBreaker struct {
    failures, threshold int
    state               State
    openAt              time.Time
}

func (cb *CircuitBreaker) Call(fn func() error) error {
    if cb.state == Open && time.Since(cb.openAt) < 30*time.Second {
        return errors.New("circuit open")
    }
    if err := fn(); err != nil {
        cb.failures++
        if cb.failures >= cb.threshold { cb.state = Open; cb.openAt = time.Now() }
        return err
    }
    cb.failures = 0; cb.state = Closed
    return nil
}

Prerequisites

  • Go >= 1.21

Pro Tips

  • → Use sony/gobreaker for production.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
go
Level
Advanced
Read time
6 min
Published
Sep 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.