Circuit Breaker
Adaptive Circuit Breaker Usage Example
Adaptive circuit breaker is an intelligent circuit breaking mechanism that automatically decides whether to trigger circuit breaking by dynamically analyzing request error rates and system resource usage. This feature is particularly suitable for multi-server environments, where it can automatically adjust the circuit breaking strategy based on the actual processing capacity of each server, without the need for manual parameter configuration, effectively reducing operation and maintenance complexity.
Click to view Adaptive Circuit Breaker Usage Example.
Configuration Guide
Basic Configuration
In Web or gRPC services created by Sponge, the adaptive circuit breaker function is disabled by default. To enable it, please set the following in the YAML configuration file under the configs
directory:
app:
enableCircuitBreaker: false # Whether to enable adaptive circuit breaker, true: enable, false: disable
Web Service Configuration
- Default Circuit Breaking Conditions:
- Triggers circuit breaking only for HTTP 500 and 503 error codes
- Custom Configuration:
- Extensible range of error codes that trigger circuit breaking
- Supports custom fallback logic
- Configuration location:
internal/routers/routers.go
// circuit breaker middleware
if config.Get().App.EnableCircuitBreaker {
r.Use(middleware.CircuitBreaker(
middleware.WithValidCode(http.StatusRequestTimeout), // add error code 408 for circuit breaker
middleware.WithDegradeHandler(handler), // add custom degrade handler
))
}
gRPC Service Configuration
- Default Circuit Breaking Conditions:
- Triggers circuit breaking only for gRPC status codes Internal (13) and Unavailable (14)
- Custom Configuration:
- Extensible range of error codes that trigger circuit breaking
- Supports custom fallback logic
- Configuration location:
internal/server/grpc.go
// circuit breaker interceptor
if config.Get().App.EnableCircuitBreaker {
unaryServerInterceptors = append(unaryServerInterceptors, interceptor.UnaryServerCircuitBreaker(
// set grpc code for circuit breaker, default already includes codes.Internal and codes.Unavailable
interceptor.WithValidCode(codes.DeadlineExceeded), // add error code 4 for circuit breaker
interceptor.WithUnaryServerDegradeHandler(handler), // add custom degrade handler
))
}