-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add circuit breaker for upstream provider overload protection #75
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kacpersaw
wants to merge
22
commits into
main
Choose a base branch
from
kacpersaw/aibridge-circuit-breaker
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
7700a8f
feat: add circuit breaker for upstream provider overload protection
kacpersaw aad288c
chore: apply make fmt
kacpersaw 47253f1
refactor: use sony/gobreaker for circuit breakers with per-endpoint i…
kacpersaw 8cf2d18
refactor: align CircuitBreakerConfig fields with gobreaker.Settings
kacpersaw 8e44145
refactor: remove CircuitState, use gobreaker.State directly
kacpersaw 7af3bc1
refactor: implement circuit breaker as middleware with per-provider c…
kacpersaw 521df9b
docs: clarify noop behavior when provider not configured
kacpersaw c85b836
Update go.mod
kacpersaw e446954
fix: update metrics help text to reflect 0/0.5/1 gauge values
kacpersaw 1d2315e
refactor: add CircuitBreaker interface with NoopCircuitBreaker
kacpersaw 6994f89
refactor: use gobreaker Execute for proper half-open rejection handling
kacpersaw 6a7d578
refactor: remove unused circuitBreakers field and getter from Request…
kacpersaw b0ff0eb
use per-provider maps for endpoints
kacpersaw bee7a4d
make fmt
kacpersaw 98c7b7a
use mux.Handle for cb middleware
kacpersaw 7733266
Move CircuitBreakerConfig to the Provider struct
kacpersaw 7c7c85b
Update tests
kacpersaw 8943ef0
default noop func for onChange
kacpersaw 7d2dcb1
create CircuitBreakers per Provider instead of a global one and remov…
kacpersaw e3438f4
Update bridge.go
kacpersaw a32f246
fix format
kacpersaw e929098
Apply review suggestions
kacpersaw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| package aibridge | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "net/http" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/sony/gobreaker/v2" | ||
| ) | ||
|
|
||
| // CircuitBreakerConfig holds configuration for circuit breakers. | ||
| // Fields match gobreaker.Settings for clarity. | ||
| type CircuitBreakerConfig struct { | ||
| // MaxRequests is the maximum number of requests allowed in half-open state. | ||
| MaxRequests uint32 | ||
| // Interval is the cyclic period of the closed state for clearing internal counts. | ||
| Interval time.Duration | ||
| // Timeout is how long the circuit stays open before transitioning to half-open. | ||
| Timeout time.Duration | ||
| // FailureThreshold is the number of consecutive failures that triggers the circuit to open. | ||
| FailureThreshold uint32 | ||
| // IsFailure determines if a status code should count as a failure. | ||
| // If nil, defaults to 429, 503, and 529 (Anthropic overloaded). | ||
| IsFailure func(statusCode int) bool | ||
| } | ||
|
|
||
| // DefaultCircuitBreakerConfig returns sensible defaults for circuit breaker configuration. | ||
| func DefaultCircuitBreakerConfig() CircuitBreakerConfig { | ||
| return CircuitBreakerConfig{ | ||
| FailureThreshold: 5, | ||
| Interval: 10 * time.Second, | ||
| Timeout: 30 * time.Second, | ||
| MaxRequests: 3, | ||
| IsFailure: DefaultIsFailure, | ||
| } | ||
| } | ||
|
|
||
| // DefaultIsFailure returns true for status codes that typically indicate | ||
| // upstream overload: 429 (Too Many Requests), 503 (Service Unavailable), | ||
| // and 529 (Anthropic Overloaded). | ||
| func DefaultIsFailure(statusCode int) bool { | ||
| switch statusCode { | ||
| case http.StatusTooManyRequests, // 429 | ||
| http.StatusServiceUnavailable, // 503 | ||
| 529: // Anthropic "Overloaded" | ||
| return true | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| // ProviderCircuitBreakers manages per-endpoint circuit breakers for a single provider. | ||
| type ProviderCircuitBreakers struct { | ||
| provider string | ||
| config CircuitBreakerConfig | ||
| breakers sync.Map // endpoint -> *gobreaker.CircuitBreaker[struct{}] | ||
| onChange func(endpoint string, from, to gobreaker.State) | ||
| } | ||
|
|
||
| // NewProviderCircuitBreakers creates circuit breakers for a single provider. | ||
| // Returns nil if config is nil (no circuit breaker protection). | ||
| func NewProviderCircuitBreakers(provider string, config *CircuitBreakerConfig, onChange func(endpoint string, from, to gobreaker.State)) *ProviderCircuitBreakers { | ||
| if config == nil { | ||
| return nil | ||
| } | ||
| if config.IsFailure == nil { | ||
| config.IsFailure = DefaultIsFailure | ||
| } | ||
| return &ProviderCircuitBreakers{ | ||
| provider: provider, | ||
| config: *config, | ||
| onChange: onChange, | ||
| } | ||
| } | ||
|
|
||
| // Get returns the circuit breaker for an endpoint, creating it if needed. | ||
| func (p *ProviderCircuitBreakers) Get(endpoint string) *gobreaker.CircuitBreaker[struct{}] { | ||
| if v, ok := p.breakers.Load(endpoint); ok { | ||
| return v.(*gobreaker.CircuitBreaker[struct{}]) | ||
| } | ||
|
|
||
| settings := gobreaker.Settings{ | ||
| Name: p.provider + ":" + endpoint, | ||
| MaxRequests: p.config.MaxRequests, | ||
| Interval: p.config.Interval, | ||
| Timeout: p.config.Timeout, | ||
| ReadyToTrip: func(counts gobreaker.Counts) bool { | ||
| return counts.ConsecutiveFailures >= p.config.FailureThreshold | ||
| }, | ||
| OnStateChange: func(_ string, from, to gobreaker.State) { | ||
| if p.onChange != nil { | ||
| p.onChange(endpoint, from, to) | ||
| } | ||
| }, | ||
| } | ||
|
|
||
| cb := gobreaker.NewCircuitBreaker[struct{}](settings) | ||
| actual, _ := p.breakers.LoadOrStore(endpoint, cb) | ||
| return actual.(*gobreaker.CircuitBreaker[struct{}]) | ||
| } | ||
|
|
||
| // statusCapturingWriter wraps http.ResponseWriter to capture the status code. | ||
| // It also implements http.Flusher to support streaming responses. | ||
| type statusCapturingWriter struct { | ||
| http.ResponseWriter | ||
| statusCode int | ||
| headerWritten bool | ||
| } | ||
|
|
||
| func (w *statusCapturingWriter) WriteHeader(code int) { | ||
| if !w.headerWritten { | ||
| w.statusCode = code | ||
| w.headerWritten = true | ||
| } | ||
| w.ResponseWriter.WriteHeader(code) | ||
| } | ||
|
|
||
| func (w *statusCapturingWriter) Write(b []byte) (int, error) { | ||
| if !w.headerWritten { | ||
| w.statusCode = http.StatusOK | ||
| w.headerWritten = true | ||
| } | ||
| return w.ResponseWriter.Write(b) | ||
| } | ||
|
|
||
| func (w *statusCapturingWriter) Flush() { | ||
| if f, ok := w.ResponseWriter.(http.Flusher); ok { | ||
| f.Flush() | ||
| } | ||
| } | ||
|
|
||
| // Unwrap returns the underlying ResponseWriter for interface checks. | ||
| func (w *statusCapturingWriter) Unwrap() http.ResponseWriter { | ||
| return w.ResponseWriter | ||
| } | ||
|
|
||
| // CircuitBreakerMiddleware returns middleware that wraps handlers with circuit breaker protection. | ||
| // It captures the response status code to determine success/failure without provider-specific logic. | ||
| // If cbs is nil, requests pass through without circuit breaker protection. | ||
| func CircuitBreakerMiddleware(cbs *ProviderCircuitBreakers, metrics *Metrics) func(http.Handler) http.Handler { | ||
| return func(next http.Handler) http.Handler { | ||
| // No circuit breaker configured - pass through | ||
| if cbs == nil { | ||
| return next | ||
| } | ||
|
|
||
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| endpoint := strings.TrimPrefix(r.URL.Path, "/"+cbs.provider) | ||
| cb := cbs.Get(endpoint) | ||
|
|
||
| // Wrap response writer to capture status code | ||
| sw := &statusCapturingWriter{ResponseWriter: w, statusCode: http.StatusOK} | ||
|
|
||
| _, err := cb.Execute(func() (struct{}, error) { | ||
| next.ServeHTTP(sw, r) | ||
| if cbs.config.IsFailure(sw.statusCode) { | ||
| return struct{}{}, fmt.Errorf("upstream error: %d", sw.statusCode) | ||
| } | ||
| return struct{}{}, nil | ||
| }) | ||
|
|
||
| if err != nil && (errors.Is(err, gobreaker.ErrOpenState) || errors.Is(err, gobreaker.ErrTooManyRequests)) { | ||
| if metrics != nil { | ||
| metrics.CircuitBreakerRejects.WithLabelValues(cbs.provider, endpoint).Inc() | ||
| } | ||
| http.Error(w, "circuit breaker is open", http.StatusServiceUnavailable) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| // stateToGaugeValue converts gobreaker.State to a gauge value. | ||
| // closed=0, half-open=0.5, open=1 | ||
| func stateToGaugeValue(s gobreaker.State) float64 { | ||
| switch s { | ||
| case gobreaker.StateClosed: | ||
| return 0 | ||
| case gobreaker.StateHalfOpen: | ||
| return 0.5 | ||
| case gobreaker.StateOpen: | ||
| return 1 | ||
| default: | ||
| return 0 | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.