-
Notifications
You must be signed in to change notification settings - Fork 2.1k
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
cache: implement the circuit breaker pattern for asynchronous set operations in the cache client #7010
Merged
Merged
cache: implement the circuit breaker pattern for asynchronous set operations in the cache client #7010
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4dd89b7
Implement the circuit breaker pattern for asynchronous set operations…
damnever c9b1f7c
Add feature flag for circuitbreaker
damnever 808bdc9
Sync docs
damnever f76994e
Skip configuration validation if the circuit breaker is disabled
damnever 07d9134
Make lint happy
damnever e299abe
Abstract the logic of the circuit breaker
damnever 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 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 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 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 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 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 |
---|---|---|
|
@@ -17,6 +17,7 @@ import ( | |
"github.com/pkg/errors" | ||
"github.com/prometheus/client_golang/prometheus" | ||
"github.com/prometheus/client_golang/prometheus/promauto" | ||
"github.com/sony/gobreaker" | ||
"gopkg.in/yaml.v2" | ||
|
||
"github.com/thanos-io/thanos/pkg/discovery/dns" | ||
|
@@ -40,9 +41,11 @@ const ( | |
) | ||
|
||
var ( | ||
errMemcachedConfigNoAddrs = errors.New("no memcached addresses provided") | ||
errMemcachedDNSUpdateIntervalNotPositive = errors.New("DNS provider update interval must be positive") | ||
errMemcachedMaxAsyncConcurrencyNotPositive = errors.New("max async concurrency must be positive") | ||
errMemcachedConfigNoAddrs = errors.New("no memcached addresses provided") | ||
errMemcachedDNSUpdateIntervalNotPositive = errors.New("DNS provider update interval must be positive") | ||
errMemcachedMaxAsyncConcurrencyNotPositive = errors.New("max async concurrency must be positive") | ||
errCircuitBreakerConsecutiveFailuresNotPositive = errors.New("set async circuit breaker: consecutive failures must be greater than 0") | ||
errCircuitBreakerFailurePercentInvalid = errors.New("set async circuit breaker: failure percent must be in range (0,1]") | ||
|
||
defaultMemcachedClientConfig = MemcachedClientConfig{ | ||
Timeout: 500 * time.Millisecond, | ||
|
@@ -54,6 +57,13 @@ var ( | |
MaxGetMultiBatchSize: 0, | ||
DNSProviderUpdateInterval: 10 * time.Second, | ||
AutoDiscovery: false, | ||
|
||
SetAsyncCircuitBreakerEnabled: false, | ||
SetAsyncCircuitBreakerHalfOpenMaxRequests: 10, | ||
SetAsyncCircuitBreakerOpenDuration: 5 * time.Second, | ||
SetAsyncCircuitBreakerMinRequests: 50, | ||
SetAsyncCircuitBreakerConsecutiveFailures: 5, | ||
SetAsyncCircuitBreakerFailurePercent: 0.05, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We might need to keep an eye on this to make sure those values sane. |
||
} | ||
) | ||
|
||
|
@@ -141,6 +151,22 @@ type MemcachedClientConfig struct { | |
|
||
// AutoDiscovery configures memached client to perform auto-discovery instead of DNS resolution | ||
AutoDiscovery bool `yaml:"auto_discovery"` | ||
|
||
// SetAsyncCircuitBreakerEnabled enables circuite breaker for SetAsync operations. | ||
SetAsyncCircuitBreakerEnabled bool `yaml:"set_async_circuit_breaker_enabled"` | ||
// SetAsyncCircuitBreakerHalfOpenMaxRequests is the maximum number of requests allowed to pass through | ||
// when the circuit breaker is half-open. | ||
// If set to 0, the circuit breaker allows only 1 request. | ||
SetAsyncCircuitBreakerHalfOpenMaxRequests uint32 `yaml:"set_async_circuit_breaker_half_open_max_requests"` | ||
// SetAsyncCircuitBreakerOpenDuration is the period of the open state after which the state of the circuit breaker becomes half-open. | ||
// If set to 0, the circuit breaker resets it to 60 seconds. | ||
SetAsyncCircuitBreakerOpenDuration time.Duration `yaml:"set_async_circuit_breaker_open_duration"` | ||
// SetAsyncCircuitBreakerMinRequests is minimal requests to trigger the circuit breaker. | ||
SetAsyncCircuitBreakerMinRequests uint32 `yaml:"set_async_circuit_breaker_min_requests"` | ||
// SetAsyncCircuitBreakerConsecutiveFailures represents consecutive failures based on CircuitBreakerMinRequests to determine if the circuit breaker should open. | ||
SetAsyncCircuitBreakerConsecutiveFailures uint32 `yaml:"set_async_circuit_breaker_consecutive_failures"` | ||
// SetAsyncCircuitBreakerFailurePercent represents the failure percentage, which is based on CircuitBreakerMinRequests, to determine if the circuit breaker should open. | ||
SetAsyncCircuitBreakerFailurePercent float64 `yaml:"set_async_circuit_breaker_failure_percent"` | ||
} | ||
|
||
func (c *MemcachedClientConfig) validate() error { | ||
|
@@ -158,6 +184,12 @@ func (c *MemcachedClientConfig) validate() error { | |
return errMemcachedMaxAsyncConcurrencyNotPositive | ||
} | ||
|
||
if c.SetAsyncCircuitBreakerConsecutiveFailures == 0 { | ||
return errCircuitBreakerConsecutiveFailuresNotPositive | ||
} | ||
if c.SetAsyncCircuitBreakerFailurePercent <= 0 || c.SetAsyncCircuitBreakerFailurePercent > 1 { | ||
return errCircuitBreakerFailurePercentInvalid | ||
} | ||
damnever marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return nil | ||
} | ||
|
||
|
@@ -195,6 +227,8 @@ type memcachedClient struct { | |
dataSize *prometheus.HistogramVec | ||
|
||
p *AsyncOperationProcessor | ||
|
||
setAsyncCircuitBreaker CircuitBreaker | ||
} | ||
|
||
// AddressProvider performs node address resolution given a list of clusters. | ||
|
@@ -277,7 +311,21 @@ func newMemcachedClient( | |
config.MaxGetMultiConcurrency, | ||
gate.Gets, | ||
), | ||
p: NewAsyncOperationProcessor(config.MaxAsyncBufferSize, config.MaxAsyncConcurrency), | ||
p: NewAsyncOperationProcessor(config.MaxAsyncBufferSize, config.MaxAsyncConcurrency), | ||
setAsyncCircuitBreaker: noopCircuitBreaker{}, | ||
} | ||
if config.SetAsyncCircuitBreakerEnabled { | ||
c.setAsyncCircuitBreaker = gobreakerCircuitBreaker{gobreaker.NewCircuitBreaker(gobreaker.Settings{ | ||
Name: "memcached-set-async", | ||
MaxRequests: config.SetAsyncCircuitBreakerHalfOpenMaxRequests, | ||
Interval: 10 * time.Second, | ||
Timeout: config.SetAsyncCircuitBreakerOpenDuration, | ||
ReadyToTrip: func(counts gobreaker.Counts) bool { | ||
return counts.Requests >= config.SetAsyncCircuitBreakerMinRequests && | ||
(counts.ConsecutiveFailures >= uint32(config.SetAsyncCircuitBreakerConsecutiveFailures) || | ||
float64(counts.TotalFailures)/float64(counts.Requests) >= config.SetAsyncCircuitBreakerFailurePercent) | ||
}, | ||
})} | ||
} | ||
|
||
c.clientInfo = promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{ | ||
|
@@ -375,22 +423,31 @@ func (c *memcachedClient) SetAsync(key string, value []byte, ttl time.Duration) | |
start := time.Now() | ||
c.operations.WithLabelValues(opSet).Inc() | ||
|
||
err := c.client.Set(&memcache.Item{ | ||
Key: key, | ||
Value: value, | ||
Expiration: int32(time.Now().Add(ttl).Unix()), | ||
err := c.setAsyncCircuitBreaker.Execute(func() error { | ||
return c.client.Set(&memcache.Item{ | ||
Key: key, | ||
Value: value, | ||
Expiration: int32(time.Now().Add(ttl).Unix()), | ||
}) | ||
}) | ||
if err != nil { | ||
// If the PickServer will fail for any reason the server address will be nil | ||
// and so missing in the logs. We're OK with that (it's a best effort). | ||
serverAddr, _ := c.selector.PickServer(key) | ||
level.Debug(c.logger).Log( | ||
"msg", "failed to store item to memcached", | ||
"key", key, | ||
"sizeBytes", len(value), | ||
"server", serverAddr, | ||
"err", err, | ||
) | ||
if errors.Is(err, gobreaker.ErrOpenState) || errors.Is(err, gobreaker.ErrTooManyRequests) { | ||
level.Warn(c.logger).Log( | ||
"msg", "circuit breaker disallows storing item in memcached", | ||
"key", key, | ||
"err", err) | ||
} else { | ||
// If the PickServer will fail for any reason the server address will be nil | ||
// and so missing in the logs. We're OK with that (it's a best effort). | ||
serverAddr, _ := c.selector.PickServer(key) | ||
level.Debug(c.logger).Log( | ||
"msg", "failed to store item to memcached", | ||
"key", key, | ||
"sizeBytes", len(value), | ||
"server", serverAddr, | ||
"err", err, | ||
) | ||
} | ||
c.trackError(opSet, err) | ||
return | ||
} | ||
|
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If set to 0, the circuit breaker resets it to 60 seconds.
What does it mean? That the default value of this is
60 seconds
? 🤔There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, github.com/sony/gobreaker uses this default value.