How to Implement Circuit Breaker Pattern in Go

Web
Go has no built-in circuit breaker; use the sony/gobreaker library to stop cascading failures when external services are down.

The Go standard library does not include a built-in Circuit Breaker pattern; you must implement it manually or use a third-party library like sony/gobreaker.

package main

import (
	"fmt"
	"time"

	"github.com/sony/gobreaker"
)

func main() {
	// Create a circuit breaker with 3 max failures and 10s reset timeout
	cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{
		Name:                   "example",
		MaxRequests:            0,
		MaxFailures:            3,
		ResetTimeout:           10 * time.Second,
		ReadyToTrip: func(counts gobreaker.Counts) bool {
			return counts.Total >= 5 && counts.Failures > 0
		},
	})

	// Execute a function through the breaker
	if err := cb.Execute(func() error {
		// Your external call logic here
		return fmt.Errorf("service unavailable")
	}); err != nil {
		if err == gobreaker.ErrOpenState {
			fmt.Println("Circuit is open, request rejected")
		} else {
			fmt.Println("Request failed:", err)
		}
	}
}

Install the library first: go get github.com/sony/gobreaker.