Docs Home / Go SDK / Circuit Breaker

Circuit Breaker

The Circuit Breaker pattern protects your application from cascading failures by monitoring remote calls and opening a circuit when error thresholds are exceeded. The Go SDK provides a simple, configurable implementation.

Features

Installation

go get github.com/example/sdk/go/circuitbreaker

Basic Usage

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/example/sdk/go/circuitbreaker"
)

func main() {
    // Create a circuit breaker with defaults
    cb := circuitbreaker.New(circuitbreaker.Config{
        FailureThreshold: 5,
        SuccessThreshold: 2,
        OpenTimeout:      10 * time.Second,
    })

    // Wrap a function that may fail
    operation := func(ctx context.Context) (string, error) {
        // Simulated remote call
        return fetchData()
    }

    for i := 0; i < 10; i++ {
        ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
        defer cancel()

        result, err := cb.Execute(ctx, operation)
        if err != nil {
            fmt.Printf("Attempt %d: error: %v (state=%s)\n", i+1, err, cb.State())
            continue
        }
        fmt.Printf("Attempt %d: success: %s (state=%s)\n", i+1, result, cb.State())
    }
}

// Simulated remote call that fails 60% of the time
func fetchData() (string, error) {
    if time.Now().UnixNano()%5 == 0 {
        return "", fmt.Errorf("remote service unavailable")
    }
    return "data payload", nil
}

Configuration Options

Field Type Description
FailureThreshold int Number of consecutive failures before opening the circuit.
SuccessThreshold int Number of consecutive successes required to close a half‑open circuit.
OpenTimeout time.Duration Duration the circuit remains open before transitioning to half‑open.
OnStateChange func(oldState, newState State) Optional callback invoked on every state transition.

Metrics

Use cb.Stats() to retrieve runtime statistics:

type Stats struct {
    State           State
    FailureCount    int
    SuccessCount    int
    ConsecutiveFailures int
    ConsecutiveSuccesses int
    LastFailureTime time.Time
}

Advanced Topics