-
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
5
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.
+496
−10
Open
Changes from all commits
Commits
Show all changes
5 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 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
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,131 @@ | ||
| package aibridge | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "net/http" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "github.com/sony/gobreaker/v2" | ||
| ) | ||
|
|
||
| // CircuitBreakerConfig holds configuration for circuit breakers. | ||
| // Fields match gobreaker.Settings for clarity. | ||
| type CircuitBreakerConfig struct { | ||
| // Enabled controls whether circuit breakers are active. | ||
| Enabled bool | ||
| // 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 | ||
| } | ||
|
|
||
| // DefaultCircuitBreakerConfig returns sensible defaults for circuit breaker configuration. | ||
| func DefaultCircuitBreakerConfig() CircuitBreakerConfig { | ||
| return CircuitBreakerConfig{ | ||
| Enabled: false, // Disabled by default for backward compatibility | ||
| FailureThreshold: 5, | ||
| Interval: 10 * time.Second, | ||
| Timeout: 30 * time.Second, | ||
| MaxRequests: 3, | ||
| } | ||
| } | ||
|
|
||
| // isCircuitBreakerFailure returns true if the given HTTP status code | ||
| // should count as a failure for circuit breaker purposes. | ||
| func isCircuitBreakerFailure(statusCode int) bool { | ||
| switch statusCode { | ||
| case http.StatusTooManyRequests, // 429 | ||
| http.StatusServiceUnavailable, // 503 | ||
| 529: // Anthropic "Overloaded" | ||
| return true | ||
| default: | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| // CircuitBreakers manages per-endpoint circuit breakers using sony/gobreaker. | ||
| // Circuit breakers are keyed by "provider:endpoint" for per-endpoint isolation. | ||
| type CircuitBreakers struct { | ||
| breakers sync.Map // map[string]*gobreaker.CircuitBreaker[any] | ||
| config CircuitBreakerConfig | ||
| onChange func(name string, from, to gobreaker.State) | ||
| } | ||
|
|
||
| // NewCircuitBreakers creates a new circuit breaker manager. | ||
| func NewCircuitBreakers(config CircuitBreakerConfig, onChange func(name string, from, to gobreaker.State)) *CircuitBreakers { | ||
| return &CircuitBreakers{ | ||
| config: config, | ||
| onChange: onChange, | ||
| } | ||
| } | ||
|
|
||
| // Allow checks if a request to provider/endpoint should be allowed. | ||
| func (c *CircuitBreakers) Allow(provider, endpoint string) bool { | ||
| if !c.config.Enabled { | ||
| return true | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| return cb.State() != gobreaker.StateOpen | ||
| } | ||
|
|
||
| // RecordSuccess records a successful request. | ||
| func (c *CircuitBreakers) RecordSuccess(provider, endpoint string) { | ||
| if !c.config.Enabled { | ||
| return | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| _, _ = cb.Execute(func() (any, error) { return nil, nil }) | ||
| } | ||
|
|
||
| // RecordFailure records a failed request. Returns true if this caused the circuit to open. | ||
| func (c *CircuitBreakers) RecordFailure(provider, endpoint string, statusCode int) bool { | ||
| if !c.config.Enabled || !isCircuitBreakerFailure(statusCode) { | ||
| return false | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| before := cb.State() | ||
| _, _ = cb.Execute(func() (any, error) { | ||
| return nil, fmt.Errorf("upstream error: %d", statusCode) | ||
| }) | ||
| return before != gobreaker.StateOpen && cb.State() == gobreaker.StateOpen | ||
| } | ||
|
|
||
| // State returns the current state for a provider/endpoint. | ||
| func (c *CircuitBreakers) State(provider, endpoint string) gobreaker.State { | ||
| if !c.config.Enabled { | ||
| return gobreaker.StateClosed | ||
| } | ||
| cb := c.getOrCreate(provider, endpoint) | ||
| return cb.State() | ||
| } | ||
|
|
||
| func (c *CircuitBreakers) getOrCreate(provider, endpoint string) *gobreaker.CircuitBreaker[any] { | ||
| key := provider + ":" + endpoint | ||
| if v, ok := c.breakers.Load(key); ok { | ||
| return v.(*gobreaker.CircuitBreaker[any]) | ||
| } | ||
|
|
||
| settings := gobreaker.Settings{ | ||
| Name: key, | ||
| MaxRequests: c.config.MaxRequests, | ||
| Interval: c.config.Interval, | ||
| Timeout: c.config.Timeout, | ||
| ReadyToTrip: func(counts gobreaker.Counts) bool { | ||
| return counts.ConsecutiveFailures >= c.config.FailureThreshold | ||
| }, | ||
| OnStateChange: func(name string, from, to gobreaker.State) { | ||
| if c.onChange != nil { | ||
| c.onChange(name, from, to) | ||
| } | ||
| }, | ||
| } | ||
|
|
||
| cb := gobreaker.NewCircuitBreaker[any](settings) | ||
| actual, _ := c.breakers.LoadOrStore(key, cb) | ||
| return actual.(*gobreaker.CircuitBreaker[any]) | ||
| } | ||
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.