Configuration#

AutoBreaker provides flexible configuration options for different use cases.

Basic Settings#

1
2
3
4
breaker := autobreaker.New(autobreaker.Settings{
    Name:    "service-name",
    Timeout: 30 * time.Second, // Open → HalfOpen transition time
})

Default behavior uses adaptive thresholds (5% failure rate, minimum 20 observations).

Advanced Configuration#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
breaker := autobreaker.New(autobreaker.Settings{
    Name:                 "service-name",
    Timeout:              30 * time.Second,
    MaxRequests:          3,     // Concurrent requests in half-open state
    Interval:             60 * time.Second, // Stats reset interval

    // Adaptive threshold settings
    AdaptiveThreshold:    true,
    FailureRateThreshold: 0.05,  // Trip at 5% error rate
    MinimumObservations:  20,    // Minimum requests before evaluating

    // Callbacks (must be fast: <1μs)
    OnStateChange: func(name string, from, to autobreaker.State) {
        go log.Printf("%s: %v → %v", name, from, to) // Async
    },

    IsSuccessful: func(err error) bool {
        // Don't count 4xx client errors as failures
        if httpErr, ok := err.(*HTTPError); ok {
            return httpErr.Code >= 400 && httpErr.Code < 500
        }
        return err == nil
    },
})

Runtime Updates#

Update settings without restarting:

1
2
3
4
err := breaker.UpdateSettings(autobreaker.SettingsUpdate{
    FailureRateThreshold: autobreaker.Float64Ptr(0.10),
    Timeout:              autobreaker.DurationPtr(15 * time.Second),
})

Settings Reference#

SettingTypeDefaultDescription
NamestringRequiredCircuit breaker identifier
Timeouttime.Duration60 * time.SecondOpen → HalfOpen transition time
MaxRequestsuint321Concurrent requests in half-open state
Intervaltime.Duration0 (disabled)Statistics reset interval
AdaptiveThresholdbooltrueEnable percentage-based thresholds
FailureRateThresholdfloat640.05Trip at >5% error rate
MinimumObservationsuint3220Minimum requests before evaluating
OnStateChangefunc(string, State, State)nilState change callback
IsSuccessfulfunc(error) boolnilCustom error classification

Performance Considerations#

Callback Performance: ReadyToTrip, OnStateChange, and IsSuccessful callbacks execute synchronously on every request. Keep them <1μs.

1
2
3
4
5
6
7
8
9
// Good: Async logging
OnStateChange: func(name string, from, to State) {
    go metrics.Record(name, from, to) // Async, non-blocking
}

// Bad: Blocking I/O in callback
OnStateChange: func(name string, from, to State) {
    db.SaveStateChange(name, from, to) // Blocks!
}

Best Practices#

  1. Use descriptive names - Helps with monitoring and debugging
  2. Set reasonable timeouts - Match your service’s typical recovery time
  3. Monitor failure rates - Adjust thresholds based on observed behavior
  4. Use async callbacks - Keep the hot path fast
  5. Test with examples - See examples for production patterns