CircuitBreaker implements the circuit breaker pattern for endpoint-specific failure handling Execute runs the given function with circuit breaker protection GetState returns the current state of the circuit breaker GetStats returns current statistics for monitoring IsOpen returns true if the circuit breaker is open (rejecting requests)
func (*CircuitBreakerManager).GetCircuitBreaker(endpoint string) *CircuitBreaker
CircuitBreakerEntry wraps a circuit breaker with access tracking
CircuitBreakerManager manages circuit breakers for multiple endpoints GetAllStats returns statistics for all circuit breakers GetCircuitBreaker returns the circuit breaker for an endpoint, creating it if necessary Reset resets all circuit breakers (useful for testing) Shutdown stops the cleanup goroutine
ClusterStateReloadCallback is a callback function that triggers cluster state reload.
This is used by node clients to notify their parent ClusterClient about SMIGRATED notifications.
The hostPort parameter indicates the destination node (e.g., "127.0.0.1:6379").
The slotRanges parameter contains the migrated slots (e.g., ["1234", "5000-6000"]).
Currently, implementations typically reload the entire cluster state, but in the future
this could be optimized to reload only the specific slots.
func (*Manager).SetClusterStateReloadCallback(callback ClusterStateReloadCallback)
Config provides configuration options for maintenance notifications Circuit breaker configuration for endpoint failure handling
CircuitBreakerFailureThreshold is the number of failures before opening the circuit.
Default: 5 CircuitBreakerMaxRequests is the maximum number of requests allowed in half-open state.
Default: 3 CircuitBreakerResetTimeout is how long to wait before testing if the endpoint recovered.
Default: 60 seconds EndpointType specifies the type of endpoint to request in MOVING notifications.
Valid values: EndpointTypeAuto, EndpointTypeInternalIP, EndpointTypeInternalFQDN,
EndpointTypeExternalIP, EndpointTypeExternalFQDN, EndpointTypeNone
Default: EndpointTypeAuto HandoffQueueSize is the size of the buffered channel used to queue handoff requests.
If the queue is full, new handoff requests will be rejected.
Scales with both worker count and pool size for better burst handling.
Default: max(20×MaxWorkers, PoolSize), capped by MaxActiveConns+1 (if set) or 5×PoolSize
When set: minimum 200, capped by MaxActiveConns+1 (if set) or 5×PoolSize HandoffTimeout is the maximum time to wait for connection handoff to complete.
If handoff takes longer than this, the old connection will be forcibly closed.
Default: 15 seconds (matches server-side eviction timeout) MaxHandoffRetries is the maximum number of times to retry a failed handoff.
After this many retries, the connection will be removed from the pool.
Default: 3 MaxWorkers is the maximum number of worker goroutines for processing handoff requests.
Workers are created on-demand and automatically cleaned up when idle.
If zero, defaults to min(10, PoolSize/2) to handle bursts effectively.
If explicitly set, enforces minimum of PoolSize/2
Default: min(PoolSize/2, max(10, PoolSize/3)), Minimum when set: PoolSize/2 Mode controls how client maintenance notifications are handled.
Valid values: ModeDisabled, ModeEnabled, ModeAuto
Default: ModeAuto PostHandoffRelaxedDuration is how long to keep relaxed timeouts on the new connection
after a handoff completes. This provides additional resilience during cluster transitions.
Default: 2 * RelaxedTimeout RelaxedTimeout is the concrete timeout value to use during
MIGRATING/FAILING_OVER states to accommodate increased latency.
This applies to both read and write timeouts.
Default: 10 seconds ApplyDefaults applies default values to any zero-value fields in the configuration.
This ensures that partially configured structs get sensible defaults for missing fields. ApplyDefaultsWithPoolConfig applies default values to any zero-value fields in the configuration,
using the provided pool size and max active connections to calculate worker and queue defaults.
This ensures that partially configured structs get sensible defaults for missing fields. ApplyDefaultsWithPoolSize applies default values to any zero-value fields in the configuration,
using the provided pool size to calculate worker defaults.
This ensures that partially configured structs get sensible defaults for missing fields. Clone creates a deep copy of the configuration.(*Config) IsEnabled() bool Validate checks if the configuration is valid.
func DefaultConfig() *Config
func (*Config).ApplyDefaults() *Config
func (*Config).ApplyDefaultsWithPoolConfig(poolSize int, maxActiveConns int) *Config
func (*Config).ApplyDefaultsWithPoolSize(poolSize int) *Config
func (*Config).Clone() *Config
func NewManager(client interfaces.ClientInterface, pool pool.Pooler, config *Config) (*Manager, error)
func NewPoolHook(baseDialer func(context.Context, string, string) (net.Conn, error), network string, config *Config, operationsManager OperationsManagerInterface) *PoolHook
func NewPoolHookWithPoolSize(baseDialer func(context.Context, string, string) (net.Conn, error), network string, config *Config, operationsManager OperationsManagerInterface, poolSize int) *PoolHook
HandoffRequest represents a request to handoff a connection to a new endpointConn*pool.Conn // Unique connection identifierEndpointstring // Pool to remove connection from on failureSeqIDint64
func (*PoolHook).GetHandoffQueue() chan HandoffRequest
LoggingHook is an example hook implementation that logs all notifications. // 0=Error, 1=Warn, 2=Info, 3=Debug PostHook logs the result after processing. PreHook logs the notification before processing and allows modification.
*LoggingHook : NotificationHook
func NewLoggingHook(logLevel int) *LoggingHook
Manager provides a simplified upgrade functionality with hooks and atomic state.(*Manager) AddNotificationHook(notificationHook NotificationHook) Close closes the manager. GetActiveMovingOperations returns active operations with composite keys.
WARNING: This method creates a new map and copies all operations on every call.
Use sparingly, especially in hot paths or high-frequency logging. GetActiveOperationCount returns the number of active operations.
Uses atomic counter for lock-free operation. GetState returns current state using atomic counter for lock-free operation. GetPoolHook creates a pool hook with a custom dialer. InitPoolHookForPool attaches a maintnotifications pool hook to an additional
pool (e.g. a client's dedicated pipeline connection pool). A fresh, independent
*PoolHook is created and bound to the given pool so that connections which fail
handoff are removed from the correct pool — the hook's removal target is its own
single pool field, so the primary hook cannot be reused for a second pool. The
new hook shares this Manager as its operations manager, so MOVING/MIGRATING
tracking and notification handling stay centralized across both pools. IsHandoffInProgress returns true if any handoff is in progress.
Uses atomic counter for lock-free operation. MarkSMigratedSeqIDProcessed attempts to mark a SMIGRATED SeqID as processed.
Returns true if this is the first time processing this SeqID (should process),
false if it was already processed (should skip).
This prevents duplicate processing when multiple connections receive the same notification. SetClusterStateReloadCallback sets the callback function that will be called when a SMIGRATED notification is received.
This allows node clients to notify their parent ClusterClient to reload cluster state. TrackMaintNotificationsConn records a connection that successfully enabled
maintnotifications so it can be retired if the feature is later disabled for
the pool. TrackMovingOperationWithConnID starts a new MOVING operation with a specific connection ID. TriggerClusterStateReload calls the cluster state reload callback if it's set.
This is called when a SMIGRATED notification is received. UntrackMaintNotificationsConn removes a connection from the enabled
maintnotifications set. UntrackOperationWithConnID completes a MOVING operation with a specific connection ID.
*Manager : OperationsManagerInterface
*Manager : github.com/prometheus/common/expfmt.Closer
*Manager : io.Closer
func NewManager(client interfaces.ClientInterface, pool pool.Pooler, config *Config) (*Manager, error)
func github.com/redis/go-redis/v9.(*Client).GetMaintNotificationsManager() *Manager
MetricsHook collects metrics about notification processing.ErrorCountsmap[string]int64 // Total handoffs initiated // Failed handoffs // Successful handoffsNotificationCountsmap[string]int64ProcessingTimesmap[string]time.Duration GetMetrics returns a summary of collected metrics. PostHook records processing completion and any errors. PreHook records the start time for processing metrics.
*MetricsHook : NotificationHook
func NewMetricsHook() *MetricsHook
Mode represents the maintenance notifications mode IsValid returns true if the maintenance notifications mode is valid String returns the string representation of the mode
Mode : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
Mode : github.com/pandatix/go-abnf.ElemItf
Mode : database/sql/driver.Validator
Mode : expvar.Var
Mode : fmt.Stringer
const ModeAuto
const ModeDisabled
const ModeEnabled
MovingOperationKey provides a unique key for tracking MOVING operations
that combines sequence ID with connection identifier to handle duplicate
sequence IDs across multiple connections to the same node. // Unique connection identifier // Sequence ID from MOVING notification String returns a string representation of the key for debugging
MovingOperationKey : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
MovingOperationKey : github.com/pandatix/go-abnf.ElemItf
MovingOperationKey : expvar.Var
MovingOperationKey : fmt.Stringer
func (*Manager).GetActiveMovingOperations() map[MovingOperationKey]*MovingOperation
NotificationHandler handles push notifications for the simplified manager. HandlePushNotification processes push notifications with hook support.
*NotificationHandler : github.com/redis/go-redis/v9/push.NotificationHandler
PoolHook implements pool.PoolHook for Redis-specific connection handling
with maintenance notifications support. GetCircuitBreakerStats returns circuit breaker statistics for monitoring GetCurrentWorkers returns the current number of active workers (for testing) GetHandoffQueue returns the handoff queue for testing purposes GetMaxWorkers returns the max workers for testing purposes GetPendingMap returns the pending map for testing purposes IsHandoffPending returns true if the given connection has a pending handoff OnGet is called when a connection is retrieved from the pool OnPut is called when a connection is returned to the pool(*PoolHook) OnRemove(_ context.Context, conn *pool.Conn, _ error) ResetCircuitBreakers resets all circuit breakers (useful for testing) SetPool sets the pool interface for removing connections on handoff failure Shutdown gracefully shuts down the processor, waiting for workers to complete
*PoolHook : github.com/redis/go-redis/v9/internal/pool.PoolHook
func NewPoolHook(baseDialer func(context.Context, string, string) (net.Conn, error), network string, config *Config, operationsManager OperationsManagerInterface) *PoolHook
func NewPoolHookWithPoolSize(baseDialer func(context.Context, string, string) (net.Conn, error), network string, config *Config, operationsManager OperationsManagerInterface, poolSize int) *PoolHook
func ExampleCircuitBreakerMonitor(poolHook *PoolHook)
State represents the current state of a maintenance operation String returns a string representation of the state.
State : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
State : github.com/pandatix/go-abnf.ElemItf
State : expvar.Var
State : fmt.Stringer
func (*Manager).GetState() State
const StateIdle
const StateMoving
Package-Level Functions (total 8)
DefaultConfig returns a Config with sensible defaults.
DetectEndpointType automatically detects the appropriate endpoint type
based on the connection address and TLS configuration.
TLS behaviour:
- If TLS is enabled: requests FQDN for proper certificate validation
(SNI / hostname verification).
- If TLS is disabled: always requests IP for better performance, even
when the configured address is a hostname. In that case the hostname
is resolved to determine whether it belongs to an internal or
external network range.
Internal vs External detection:
- For IPs: uses private IP range detection
- For hostnames: resolves the hostname to an IP address and uses the IP range detection
ExampleCircuitBreakerMonitor demonstrates how to monitor circuit breaker status
NewLoggingHook creates a new logging hook with the specified log level.
Log levels: 0=Error, 1=Warn, 2=Info, 3=Debug
NewManager creates a new simplified manager.
NewMetricsHook creates a new metrics collection hook.
NewPoolHook creates a new pool hook
NewPoolHookWithPoolSize creates a new pool hook with pool size for better worker defaults
Package-Level Variables (total 20)
ErrCircuitBreakerOpen is returned when the circuit breaker is open
ErrConnectionInvalidHandoffState is returned when a connection is in an invalid state for handoff
ErrConnectionMarkedForHandoff is returned when a connection is marked for handoff
and should not be used until the handoff is complete
ErrConnectionMarkedForHandoffWithState is returned when a connection is marked for handoff
and should not be used until the handoff is complete
ErrHandoffQueueFull is returned when the handoff queue is full
ErrInvalidCircuitBreakerFailureThreshold is returned when the circuit breaker failure threshold is invalid
ErrInvalidCircuitBreakerMaxRequests is returned when the circuit breaker max requests is invalid
ErrInvalidCircuitBreakerResetTimeout is returned when the circuit breaker reset timeout is invalid
ErrInvalidClient is returned when the client does not support push notifications
Configuration errors
Configuration errors
ErrInvalidHandoffRetries is returned when the number of handoff retries is invalid
Configuration errors
Configuration errors
Configuration errors
ErrInvalidNotification is returned when a notification is in an invalid format
Configuration errors
Configuration errors
Configuration errors
ErrShutdown is returned when the maintnotifications manager is shutdown
Package-Level Constants (total 22)
CircuitBreakerClosed - normal operation, requests allowed
CircuitBreakerHalfOpen - testing if service recovered
Constants for maintenance push notifications modes
Constants for maintenance push notifications modes
Constants for maintenance push notifications modes
Push notification type constants for maintenance
Push notification type constants for maintenance
Push notification type constants for maintenance
Push notification type constants for maintenance
Push notification type constants for maintenance
Push notification type constants for maintenance
Push notification type constants for maintenance
PoolNameMain is the name used for the main connection pool in metrics.
StateIdle indicates no upgrade is in progress
StateHandoff indicates a connection handoff is in progress
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.