CheckForData reports whether the socket has data ready and surfaces a
detected closed or failed socket. ClearHandoffState clears the handoff state after successful handoff.
Makes the connection usable again. ClearPreparedFieldsets forgets all HIMPORT fieldsets prepared on this
connection and records the discard-all epoch the wipe corresponds to. ClearRelaxedTimeout removes one holder that SetRelaxedTimeout added. When the
last holder is gone and no unexpired deadline remains, it drops the whole
window. The count has a lower bound of zero. So a second clear, or a clear after
a deadline expiry already emptied the window, does nothing and cannot block a
later relaxation. This method is lock-free.(*Conn) Close() error CloseOnPutReason returns a non-empty reason when the connection should be
removed instead of pooled on Put. CompareAndSwapUsable atomically compares and swaps the usable flag (lock-free).
This is used by background operations (handoff, re-auth) to acquire exclusive
access to a connection. The operation sets usable to false, preventing the pool
from returning the connection to clients.
Returns true if the swap was successful (old value matched), false otherwise.
Implementation note: This is a compatibility wrapper around the state machine.
It checks if the current state is "usable" (IDLE or IN_USE) and transitions accordingly.
Deprecated: Use GetStateMachine().TryTransition() directly for better state management. CompareAndSwapUsed atomically compares and swaps the used flag (lock-free).
This method is kept for backwards compatibility.
This is the preferred method for acquiring a connection from the pool, as it
ensures that only one goroutine marks the connection as used.
Implementation: Uses state machine transitions IDLE ⇄ IN_USE
Returns true if the swap was successful (old value matched), false otherwise.
Deprecated: Use GetStateMachine().TryTransition() directly for better state management. EffectiveReadTimeout reports the read timeout that a read on this connection
uses now. It returns the active relaxed timeout when the window is set and
unexpired. Otherwise it returns normalTimeout. A caller that bounds how long a
blocked read may take (for example, the CSC full-duplex drain backstop) must use
this method, not the configured ReadTimeout. With ReadTimeout, a relaxed read
ends too soon.
It is safe to call from several goroutines at once (the reader, the writer, and
the drain backstop of a full-duplex connection). It reads one atomic snapshot.
The only change it makes is the deadline safety net: when the deadline has
passed, it removes the deadline holder once (see expireRelaxedTimeout). It never
removes an active, unexpired window. If a notification holder survives that
expiry, it returns that holder's relaxed timeout, not normalTimeout. EffectiveWriteTimeout is the write side of EffectiveReadTimeout. Use it to bound
how long a blocked write may take. It has the same snapshot behavior. ExecuteInitConn runs the stored connection initialization function if available. ExpiresAt returns the connection's absolute lifetime expiry (zero when no
ConnMaxLifetime applies; jitter included). Set once at dial, so a plain read
is safe. Long-holding callers bound their hold by the REMAINING lifetime. FieldsetEpoch returns the discard-all epoch this connection's prepared
fieldsets belong to (0 when none were ever prepared on the session). FieldsetPreparedVersion returns the client-side registry version at which
the named HIMPORT fieldset was prepared on this connection's current server
session, or 0 if it was not prepared on it (registry versions start at 1). GetDialStartNs returns the time when the dial started (in nanoseconds since epoch).
This is used to calculate the full connection creation time (TCP + handshake). GetHandoffEndpoint returns the new endpoint for handoff (lock-free). GetHandoffInfo returns all handoff information atomically (lock-free).
This method prevents race conditions by returning all handoff state in a single atomic operation.
Returns (shouldHandoff, endpoint, seqID). GetID returns the unique identifier for this connection. GetMovingSeqID returns the sequence ID from the MOVING notification (lock-free). GetNetConn safely returns the current network connection using atomic load (lock-free).
This method is used by the pool for health checks and provides better performance. GetStateMachine returns the connection's state machine for advanced state management.
This is primarily used by internal packages like maintnotifications for handoff processing. HandoffRetries returns the current handoff retry count (lock-free). HasBufferedData safely checks if the connection has buffered data.
This method is used to avoid data races when checking for push notifications. HasPreparedFieldsets reports whether any HIMPORT fieldset is prepared on
this connection's current server session. HasRelaxedTimeout returns true when the relaxed timeouts are active on this
connection. Active means a holder is present, a timeout is set, and any deadline
is still in the future. When the deadline has passed it removes the deadline holder
once (like getEffective*) and re-reads the snapshot: a surviving non-deadline holder
keeps the window active. Before this, an expired deadline made it report false even
while another holder was still active, contradicting the surviving-holder semantics.
This reports the boolean only; the timeout VALUE it would relax to may still be the
expired holder's, since all holders share one (readNs, writeNs) pair — see the
per-holder timeout follow-up. IncrementAndGetHandoffRetries atomically increments and returns handoff retries (lock-free).(*Conn) IsClosed() bool IsInited returns true if the connection has been initialized.
This is a backward-compatible wrapper around the state machine. IsPooled returns true if the connection is managed by a pool and will be pooled on Put. IsPubSub returns true if the connection is used for PubSub. IsUsable returns true if the connection is safe to use for new commands (lock-free).
A connection is "usable" when it's in a stable state and can be returned to clients.
It becomes unusable during:
- Handoff operations (network connection replacement)
- Re-authentication (credential updates)
- Other background operations that need exclusive access
Note: CREATED state is considered usable because new connections need to pass OnGet() hook
before initialization. The initialization happens after OnGet() in the client code. IsUsed returns true if the connection is currently in use (lock-free).
Deprecated: Use GetStateMachine().GetState() == StateInUse directly for better clarity.
This method is kept for backwards compatibility.
A connection is "used" when it has been retrieved from the pool and is
actively processing a command. Background operations (like re-auth) should
wait until the connection is not used before executing commands.(*Conn) LastPutAtNs() int64 MarkCloseOnPut marks the connection for removal when it is returned to the pool. MarkCscReadPending requests one conservative CSC drain after a command read
when the transport may retain data that MaybeHasData cannot observe. MarkFieldsetPrepared records that the named HIMPORT fieldset was prepared
on this connection's current server session at the given registry version.
A session acquiring its first fieldset adopts the given discard-all epoch
(fieldsets prepared after an HIMPORT DISCARDALL are not subject to it);
the epoch never moves backwards, so a mark carrying an older snapshot
cannot regress a session already wiped at a newer epoch. MarkForHandoff marks the connection for handoff due to MOVING notification.
Returns an error if the connection is already marked for handoff.
Note: This only sets metadata - the connection state is not changed until OnPut.
This allows the current user to finish using the connection before handoff. MarkQueuedForHandoff marks the connection as queued for handoff processing.
This makes the connection unusable until handoff completes.
This is called from OnPut hook, where the connection is typically in IN_USE state.
The pool will preserve the UNUSABLE state and not overwrite it with IDLE. MaybeHasData tries to peek at the next byte in the socket without consuming it
This is used to check if there are push notifications available
Important: This will work on Linux, but not on Windows PeekReplyTypeForCheck peeks at the reply type while holding readerMu, so it is
safe against a concurrent SetNetConn resetting the reader during handoff.
Unlike PeekReplyTypeSafe it does not require the data to already be buffered:
the pool health check calls it after connCheck reports unexpected socket data,
and connCheck only MSG_PEEKs, so the byte still has to be pulled from the
socket into the reader here. PeekReplyTypeSafe safely peeks at the reply type.
This method is used to avoid data races when checking for push notifications. PoolName returns the name of the pool this connection belongs to.
This is used for metrics to identify which pool a connection is from. PreparedFieldsetNames returns the names of the HIMPORT fieldsets prepared
on this connection's current server session. Release releases the connection back to the pool.
This is an optimized inline method for the hot path (Put operation).
It tries to transition from IN_USE -> IDLE.
Returns true if the connection was successfully released, false otherwise.
Performance: This is faster than calling GetStateMachine() + TryTransitionFast().
NOTE: We directly access cn.stateMachine.state here instead of using the state machine's
methods. This breaks encapsulation but is necessary for performance.
Waiters parked in AwaitAndTransition for IDLE (re-auth, handoff) are notified
after a successful transition; notifyWaiters costs one atomic load when nobody waits.(*Conn) RemoteAddr() net.Addr SetInitConnFunc sets the connection initialization function to be called on reconnections.(*Conn) SetLastPutAtNs(ns int64)(*Conn) SetNetConn(netConn net.Conn) SetNetConnAndInitConn replaces the underlying connection and executes the initialization.
This method ensures only one initialization can happen at a time by using atomic state transitions.
If another goroutine is currently initializing, this will wait for it to complete. SetOnClose installs fn as the callback invoked exactly once when this
connection is closed (via Conn.Close).
IMPORTANT: SetOnClose OVERWRITES any previously installed callback — it
does not compose, chain, or deduplicate. A Conn has room for a single
onClose hook by design, because its lifecycle is bounded (a Conn is
created, optionally re-initialized on its own net.Conn, and then closed
once) and the pool's OnRemove hooks handle any registry-level cleanup
that must survive the net.Conn being swapped.
This has a subtle implication for per-connection subscriptions such as
the unsubscribe function returned by StreamingCredentialsProvider
(e.g. EntraID token rotation): if SetOnClose is called twice on the
same Conn with DIFFERENT unsubscribe closures — for example because
initConn ran a second time and obtained a fresh Subscribe() —
the previous unsubscribe is dropped and will NEVER run, leaking a
subscription on the provider. Callers must therefore ensure either:
- the provider's Subscribe is idempotent for the same listener (the
streaming credentials Manager deduplicates listeners by connection
id, so re-Subscribe returns an equivalent unsubscribe), OR
- the previous callback has already been invoked before SetOnClose is
called again.
Design note: unlike the client-level onCloseHooks registry (see
redis.baseClient), there is intentionally NO named-hook dedup or
multi-callback support on Conn. This is a deliberate trade-off to keep
the Conn object slim — a pool can hold thousands of Conn values and
each one is a hot allocation, so paying for a sync.Mutex plus a
map[string]func() error per connection to support a feature that would
only be used by at most one subsystem today (streaming credentials) is
not worth the per-connection memory and allocation cost. For a single
Conn there is at most one meaningful close callback at any point in
time, and a richer registry here would not even solve the "stale
closure" hazard described above. SetOnCscClose sets the client-side-caching close hook, overwriting any
previous one. It runs on Close in addition to the SetOnClose callback. SetOnCscReinit sets the client-side-caching pre-reinitialization hook,
overwriting any previous one. SetPoolName sets the name of the pool this connection belongs to.
This should be called when the connection is added to a pool. SetRelaxedTimeout sets the relaxed timeouts for this connection during a
maintenance-notification upgrade. They apply to every later command until an
equal number of ClearRelaxedTimeout calls remove this holder. This method is
lock-free. It installs a new snapshot with a compare-and-swap and keeps any
deadline that is already in effect.
Note: the caller (the notification handler) records the metrics, because it
knows the notification type and the pool name. SetRelaxedTimeoutWithDeadline sets the relaxed timeouts and a deadline. After
the deadline the window reverts on its own, because handoff never calls Clear.
Only the first deadline window takes a holder slot. An overlapping handoff
re-arms the window: it replaces the deadline in place and does not add a holder.
So the later expiry removes exactly one holder and the window clears. The
connection does not stay relaxed forever. This method is lock-free. SetUsable sets the usable flag for the connection (lock-free).
Deprecated: Use GetStateMachine().Transition() directly for better state management.
This method is kept for backwards compatibility.
This should be called to mark a connection as usable after initialization or
to release it after a background operation completes.
Prefer CompareAndSwapUsable() when acquiring exclusive access to avoid race conditions.
Deprecated: Use GetStateMachine().Transition() directly for better state management. SetUsed sets the used flag for the connection (lock-free).
This should be called when returning a connection to the pool (set to false)
or when a single-connection pool retrieves its connection (set to true).
Prefer CompareAndSwapUsed() when acquiring from a multi-connection pool to
avoid race conditions.
Deprecated: Use GetStateMachine().Transition() directly for better state management.(*Conn) SetUsedAt(tm time.Time)(*Conn) SetUsedAtNs(ns int64) ShouldHandoff returns true if connection needs handoff (lock-free). TakeCscPeriodicReadPending schedules a throttled conservative read for
transports with no readiness mechanism. It returns true at most once per
interval, including when several drainer passes race. TakeCscReadPending consumes the post-command conservative-drain request. TryAcquire attempts to acquire the connection for use.
This is an optimized inline method for the hot path (Get operation).
It tries to transition from IDLE -> IN_USE or CREATED -> CREATED.
Returns true if the connection was successfully acquired, false otherwise.
The CREATED->CREATED is done so we can keep the state correct for later
initialization of the connection in initConn.
Performance: This is faster than calling GetStateMachine() + TryTransitionFast()
NOTE: We directly access cn.stateMachine.state here instead of using the state machine's
methods. This breaks encapsulation but is necessary for performance.
The IDLE->IN_USE and CREATED->CREATED transitions don't need
waiter notification, and benchmarks show 1-3% improvement. If the state machine ever
needs to notify waiters on these transitions, update this to use TryTransitionFast(). UnmarkFieldsetPrepared forgets that the named HIMPORT fieldset was prepared
on this connection, forcing a replay before the next HIMPORT SET using it.(*Conn) UsedAt() time.Time(*Conn) UsedAtNs() int64(*Conn) WithReader(ctx context.Context, timeout time.Duration, fn func(rd *proto.Reader) error) error WithReaderHardDeadline runs fn under a HARD read deadline of now+timeout,
bypassing getEffectiveReadTimeout so a relaxed maintenance timeout can't extend
it (used by the CSC drainer). Takes no context: an expired cycle ctx must not
become the socket deadline, or the read surfaces context.DeadlineExceeded, which
isBadConn treats as fatal.(*Conn) WithWriter(ctx context.Context, timeout time.Duration, fn func(wr *proto.Writer) error) error(*Conn) Write(b []byte) (int, error)
*Conn : github.com/redis/go-redis/v9.ConnInfo
*Conn : github.com/imroc/req/v3/internal/bisect.Writer
*Conn : github.com/prometheus/common/expfmt.Closer
*Conn : internal/bisect.Writer
*Conn : io.Closer
*Conn : io.WriteCloser
*Conn : io.Writer
func NewConn(netConn net.Conn) *Conn
func NewConnWithBufferSize(netConn net.Conn, readBufSize, writeBufSize int) *Conn
func (*ConnPool).Get(ctx context.Context) (*Conn, error)
func (*ConnPool).NewConn(ctx context.Context) (*Conn, error)
func (*ConnPool).TryGet(ctx context.Context) (*Conn, error)
func Pooler.Get(context.Context) (*Conn, error)
func Pooler.NewConn(context.Context) (*Conn, error)
func (*PubSubPool).NewConn(ctx context.Context, network string, addr string, channels []string) (*Conn, error)
func (*SingleConnPool).Get(_ context.Context) (*Conn, error)
func (*SingleConnPool).NewConn(ctx context.Context) (*Conn, error)
func (*StickyConnPool).Get(ctx context.Context) (*Conn, error)
func (*StickyConnPool).NewConn(ctx context.Context) (*Conn, error)
func NewSingleConnPool(pool Pooler, cn *Conn) *SingleConnPool
func (*ConnPool).CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
func (*ConnPool).Put(ctx context.Context, cn *Conn)
func (*ConnPool).Remove(ctx context.Context, cn *Conn, reason error)
func (*ConnPool).RemoveWithoutTurn(ctx context.Context, cn *Conn, reason error)
func (*ConnPool).RetireConns(ctx context.Context, conns []*Conn, reason string)
func ConnRetirer.RetireConns(ctx context.Context, conns []*Conn, reason string)
func Pooler.CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
func Pooler.Put(context.Context, *Conn)
func Pooler.Remove(context.Context, *Conn, error)
func Pooler.RemoveWithoutTurn(context.Context, *Conn, error)
func PoolHook.OnGet(ctx context.Context, conn *Conn, isNewConn bool) (accept bool, err error)
func PoolHook.OnPut(ctx context.Context, conn *Conn) (shouldPool bool, shouldRemove bool, err error)
func PoolHook.OnRemove(ctx context.Context, conn *Conn, reason error)
func (*PoolHookManager).ProcessOnGet(ctx context.Context, conn *Conn, isNewConn bool) (acceptConn bool, err error)
func (*PoolHookManager).ProcessOnPut(ctx context.Context, conn *Conn) (shouldPool bool, shouldRemove bool, err error)
func (*PoolHookManager).ProcessOnRemove(ctx context.Context, conn *Conn, reason error)
func (*PubSubPool).TrackConn(cn *Conn)
func (*PubSubPool).UntrackConn(cn *Conn)
func (*SingleConnPool).CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
func (*SingleConnPool).Put(_ context.Context, cn *Conn)
func (*SingleConnPool).Remove(_ context.Context, cn *Conn, reason error)
func (*SingleConnPool).RemoveWithoutTurn(ctx context.Context, cn *Conn, reason error)
func (*StickyConnPool).CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error
func (*StickyConnPool).Put(ctx context.Context, cn *Conn)
func (*StickyConnPool).Remove(ctx context.Context, cn *Conn, reason error)
func (*StickyConnPool).RemoveWithoutTurn(ctx context.Context, cn *Conn, reason error)
func github.com/redis/go-redis/v9/internal/auth/streaming.(*Manager).Listener(poolCn *Conn, reAuth func(*Conn, auth.Credentials) error, onErr func(*Conn, error)) (auth.CredentialsListener, error)
func github.com/redis/go-redis/v9/internal/auth/streaming.(*Manager).MarkForReAuth(poolCn *Conn, reAuthFn func(error))
func github.com/redis/go-redis/v9/internal/auth/streaming.(*ReAuthPoolHook).OnGet(_ context.Context, conn *Conn, _ bool) (accept bool, err error)
func github.com/redis/go-redis/v9/internal/auth/streaming.(*ReAuthPoolHook).OnPut(_ context.Context, conn *Conn) (bool, bool, error)
func github.com/redis/go-redis/v9/internal/auth/streaming.(*ReAuthPoolHook).OnRemove(_ context.Context, conn *Conn, _ error)
func github.com/redis/go-redis/v9/internal/otel.RecordConnectionCreateTime(ctx context.Context, duration time.Duration, cn *Conn)
func github.com/redis/go-redis/v9/internal/otel.RecordOperationDuration(ctx context.Context, duration time.Duration, cmd otel.Cmder, attempts int, err error, cn *Conn, dbIndex int)
func github.com/redis/go-redis/v9/internal/otel.RecordPipelineOperationDuration(ctx context.Context, duration time.Duration, operationName string, cmdCount int, attempts int, err error, cn *Conn, dbIndex int)
func github.com/redis/go-redis/v9/internal/otel.RecordPubSubMessage(ctx context.Context, cn *Conn, direction, channel string, sharded bool)
func github.com/redis/go-redis/v9/internal/otel.RecordStreamLag(ctx context.Context, lag time.Duration, cn *Conn, streamName, consumerGroup, consumerName string)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordConnectionClosed(ctx context.Context, cn *Conn, reason string, err error)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordConnectionCount(ctx context.Context, delta int, cn *Conn, state string, isPubSub bool)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordConnectionCreateTime(ctx context.Context, duration time.Duration, cn *Conn)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordConnectionHandoff(ctx context.Context, cn *Conn, poolName string)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordConnectionRelaxedTimeout(ctx context.Context, delta int, cn *Conn, poolName, notificationType string)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordConnectionWaitTime(ctx context.Context, duration time.Duration, cn *Conn)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordError(ctx context.Context, errorType string, cn *Conn, statusCode string, isInternal bool, retryAttempts int)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordMaintenanceNotification(ctx context.Context, cn *Conn, notificationType string)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordOperationDuration(ctx context.Context, duration time.Duration, cmd otel.Cmder, attempts int, err error, cn *Conn, dbIndex int)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordPendingRequests(ctx context.Context, delta int, cn *Conn, poolName string)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordPipelineOperationDuration(ctx context.Context, duration time.Duration, operationName string, cmdCount int, attempts int, err error, cn *Conn, dbIndex int)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordPubSubMessage(ctx context.Context, cn *Conn, direction, channel string, sharded bool)
func github.com/redis/go-redis/v9/internal/otel.Recorder.RecordStreamLag(ctx context.Context, lag time.Duration, cn *Conn, streamName, consumerGroup, consumerName string)
func github.com/redis/go-redis/v9/maintnotifications.(*Manager).TrackMaintNotificationsConn(cn *Conn)
func github.com/redis/go-redis/v9/maintnotifications.(*PoolHook).IsHandoffPending(conn *Conn) bool
func github.com/redis/go-redis/v9/maintnotifications.(*PoolHook).OnGet(_ context.Context, conn *Conn, _ bool) (accept bool, err error)
func github.com/redis/go-redis/v9/maintnotifications.(*PoolHook).OnPut(ctx context.Context, conn *Conn) (shouldPool bool, shouldRemove bool, err error)
func github.com/redis/go-redis/v9/maintnotifications.(*PoolHook).OnRemove(_ context.Context, conn *Conn, _ error)
AddPoolHook adds a pool hook to the pool.(*ConnPool) Close() error CloseConn closes a connection and records metrics.
Parameters:
- ctx: context for metric callbacks (enables trace-to-metric correlation)
- cn: the connection to close
- reason: why the connection is being closed (use CloseReason* constants)
- fromState: the metric state the connection was in (use MetricState* constants) DrainIdleConns runs one pass of the CSC invalidation drainer over the current
round, holding AT MOST ONE connection and its pool turn at a time (ctx is the
per-cycle deadline). A round = idle conn ids snapshotted at start; mid-round
arrivals are deferred. Each member is drainerPop'd and drained by fn, or — if no
longer a claimable idle conn — reconciled (marked visited) so it can't hang the
round. The drainer yields when no turn is immediately available, giving command
traffic priority. Handles at least one member before honoring ctx (so a tiny
DrainInterval can't stall it). No-ops if the pool is closed.(*ConnPool) Filter(fn func(*Conn) bool) error Get returns existed connection from the pool or creates a new one. HasFreeCapacity reports whether the pool can likely serve another Get without
blocking — a best-effort probe for the autopipeline straggler-hold gate (a
false positive only costs a spill / short hold, never correctness). Checks,
in order: a truly servable idle conn (usableIdleLen — plain IdleLen counts
not-usable and handoff-marked entries an OnGet hook would divert); a free
pool turn (accounts for in-use conns AND in-flight dials); room under
PoolSize and MaxActiveConns (newConn's hard dial gate); a free dial slot
(MaxConcurrentDials below PoolSize can saturate slots while a turn is free);
and the dial circuit breaker not being open (a saturated dialErrorsNum makes
the Get fail fast rather than serve). IdleLen returns number of idle connections. Len returns total number of connections. Name returns the pool's configured name, which is stamped on every
connection it creates (Conn.PoolName). Callers holding a Pooler can type
assert to interface{ Name() string } to find which pool owns a connection —
used by maintnotifications to route a handoff to the hook that owns the
conn's pool rather than always the primary one. NewConn creates a new connection and returns it to the user.
This will still obey MaxActiveConns but will not include it in the pool and won't increase the pool size.
NOTE: If you directly get a connection from the pool, it won't be pooled and won't support maintnotifications upgrades.(*ConnPool) Put(ctx context.Context, cn *Conn)(*ConnPool) Remove(ctx context.Context, cn *Conn, reason error) RemovePoolHook removes a pool hook from the pool. RemoveWithoutTurn removes a connection from the pool without freeing a turn.
This should be used when removing a connection from a context that didn't acquire
a turn via Get() (e.g., background workers, cleanup tasks).
For normal removal after Get(), use Remove() instead.(*ConnPool) RetireConns(ctx context.Context, conns []*Conn, reason string) Size returns the maximum pool size (capacity).
This is used by the streaming credentials manager to size the re-auth worker pool,
ensuring that re-auth operations don't exhaust the connection pool.(*ConnPool) Stats() *Stats SupportsPoolHooks reports that AddPoolHook and RemovePoolHook are functional.
Pooler adapters with no-op hook methods intentionally do not expose this
optional capability. TryGet returns a connection only if a pool turn is free now. A free turn is an
open slot or room to dial a new connection. TryGet never waits out PoolTimeout
for a full pool. It returns ErrPoolTryFull at once instead. This lets a caller
with a fallback (the pipeline pool) spill without a stall. ErrPoolTryFull is
different from ErrPoolTimeout: no wait happened, so getConn does not count the
spill as a pool timeout. A hard MaxActiveConns ceiling still returns
ErrPoolExhausted. TryGet still dials a new connection under an acquired turn.
*ConnPool : ConnRetirer
*ConnPool : Pooler
*ConnPool : github.com/polarsignals/frostdb/query/logicalplan.Named
*ConnPool : github.com/prometheus/common/expfmt.Closer
*ConnPool : io.Closer
func NewConnPool(opt *Options) *ConnPool
ConnStateMachine manages connection state transitions with FIFO waiting queue.
Optimized for:
- Lock-free reads (hot path)
- Minimal allocations
- Fast state transitions
- FIFO fairness for waiters
Note: Handoff metadata (endpoint, seqID, retries) is managed separately in the Conn struct. AwaitAndTransition waits for the connection to reach one of the valid states,
then atomically transitions to the target state.
Returns the current state after the transition attempt and an error if the operation failed.
The returned state is the CURRENT state (after the attempt), not the previous state.
Returns error if timeout expires or context is cancelled.
This method implements FIFO fairness - the first caller to wait gets priority
when the state becomes available.
Performance notes:
- If already in a valid state, this is very fast (no allocation, no waiting)
- If waiting is required, allocates one waiter struct and one channel GetState returns the current state (lock-free read).
This is the hot path - optimized for zero allocations and minimal overhead.
Note: Zero allocations applies to state reads; converting the returned state to a string
(via String()) may allocate if the state is unknown. Transition unconditionally transitions to the target state.
Use with caution - prefer AwaitAndTransition or TryTransition for safety.
This is useful for error paths or when you know the transition is valid. TryTransition attempts an immediate state transition without waiting.
Returns the current state after the transition attempt and an error if the transition failed.
The returned state is the CURRENT state (after the attempt), not the previous state.
This is faster than AwaitAndTransition when you don't need to wait.
Uses compare-and-swap to atomically transition, preventing concurrent transitions.
This method does NOT wait - it fails immediately if the transition cannot be performed.
Performance: Zero allocations on success path (hot path). TryTransitionFast is an optimized version for the hot path (Get/Put operations).
It only handles simple state transitions without waiter notification.
This is safe because:
1. Get/Put don't need to wait for state changes
2. Background operations (handoff/reauth) use UNUSABLE state, which this won't match
3. If a background operation is in progress (state is UNUSABLE), this fails fast
Returns true if transition succeeded, false otherwise.
Use this for performance-critical paths where you don't need error details.
Performance: Single CAS operation - as fast as the old atomic bool!
For multiple from states, use: sm.TryTransitionFast(State1, Target) || sm.TryTransitionFast(State2, Target)
The || operator short-circuits, so only 1 CAS is executed in the common case.
func NewConnStateMachine() *ConnStateMachine
func (*Conn).GetStateMachine() *ConnStateMachine
DrainState carries the cross-pass round bookkeeping for the CSC drainer.
It is owned by one drainer goroutine, so no synchronization is needed.
func (*ConnPool).DrainIdleConns(ctx context.Context, st *DrainState, fn func(cn *Conn) error)
HandoffState represents the atomic state for connection handoffs
This struct is stored atomically to prevent race conditions between
checking handoff status and reading handoff parameters // New endpoint for handoff // Sequence ID from MOVING notification // Whether connection should be handed off
MetricCallbacks holds all metric callback functions.
Use SetAllMetricCallbacks to register all callbacks atomically. ConnectionClosed is called when a connection is closed ConnectionCount is called when connection count changes (UpDownCounter)
delta: +1 when connection added, -1 when connection removed
state: connection state (e.g., "idle", "used")
isPubSub: true if this is a PubSub connection ConnectionCreateTime is called when a new connection is created ConnectionHandoff is called when a connection is handed off to another node ConnectionRelaxedTimeout is called when connection timeout is relaxed/unrelaxed
delta: +1 for relaxed, -1 for unrelaxed ConnectionWaitTime is called to record time spent waiting for a connection Error is called when an error occurs MaintenanceNotification is called when a maintenance notification is received PendingRequests is called when pending requests count changes (UpDownCounter)
delta: +1 when request starts waiting, -1 when request stops waiting
poolName is passed explicitly because we may not have a connection yet when request starts
func SetAllMetricCallbacks(callbacks *MetricCallbacks)
PoolHook defines the interface for connection lifecycle hooks. OnGet is called when a connection is retrieved from the pool.
It can modify the connection or return an error to prevent its use.
The accept flag can be used to prevent the connection from being used.
On Accept = false the connection is rejected and returned to the pool.
The error can be used to prevent the connection from being used and returned to the pool.
On Errors, the connection is removed from the pool.
It has isNewConn flag to indicate if this is a new connection (rather than idle from the pool)
The flag can be used for gathering metrics on pool hit/miss ratio. OnPut is called when a connection is returned to the pool.
It returns whether the connection should be pooled and whether it should be removed. OnRemove is called when a connection is removed from the pool.
This happens when:
- Connection fails health check
- Connection exceeds max lifetime
- Pool is being closed
- Connection encounters an error
Implementations should clean up any per-connection state.
The reason parameter indicates why the connection was removed.
*github.com/redis/go-redis/v9/internal/auth/streaming.ReAuthPoolHook
*github.com/redis/go-redis/v9/maintnotifications.PoolHook
func (*PoolHookManager).GetHooks() []PoolHook
func github.com/redis/go-redis/v9/internal/auth/streaming.(*Manager).PoolHook() PoolHook
func (*ConnPool).AddPoolHook(hook PoolHook)
func (*ConnPool).RemovePoolHook(hook PoolHook)
func Pooler.AddPoolHook(hook PoolHook)
func Pooler.RemovePoolHook(hook PoolHook)
func (*PoolHookManager).AddHook(hook PoolHook)
func (*PoolHookManager).RemoveHook(hook PoolHook)
func (*SingleConnPool).AddPoolHook(_ PoolHook)
func (*SingleConnPool).RemovePoolHook(_ PoolHook)
func (*StickyConnPool).AddPoolHook(hook PoolHook)
func (*StickyConnPool).RemovePoolHook(hook PoolHook)
PoolHookManager manages multiple pool hooks. AddHook adds a pool hook to the manager.
Hooks are called in the order they were added. Clone creates a copy of the hook manager with the same hooks.
This is used for lock-free atomic updates of the hook manager. GetHookCount returns the number of registered hooks (for testing). GetHooks returns a copy of all registered hooks. ProcessOnGet calls all OnGet hooks in order.
If any hook returns an error, processing stops and the error is returned. ProcessOnPut calls all OnPut hooks in order.
The first hook that returns shouldRemove=true or shouldPool=false will stop processing. ProcessOnRemove calls all OnRemove hooks in order. RemoveHook removes a pool hook from the manager.
func NewPoolHookManager() *PoolHookManager
func (*PoolHookManager).Clone() *PoolHookManager
PubSubStats contains pub/sub connection pool stats.
TODO(cxl): the uint32 fields below will be changed to atomic.Uint32 in v10,
which is a breaking API change.Activeuint32Createduint32Untrackeduint32
func (*PubSubPool).Stats() *PubSubStats
func github.com/redis/go-redis/v9/internal/otel.PubSubPooler.Stats() *PubSubStats
func github.com/redis/go-redis/v9.PubSubPooler.Stats() *PubSubStats
Stats contains pool state information and accumulated stats.
TODO(cxl): the uint32/int64 fields below will be changed to atomic value
types (atomic.Uint32/atomic.Int64) in v10, which is a breaking API change. // number of times free connection was found in the pool // number of idle connections in the pool // number of times free connection was NOT found in the pool // number of pending requests waiting for a connection PipelineStats holds the stats of the separate pipeline connection pool
when one is configured (PipelineReadBufferSize/PipelineWriteBufferSize).
nil when pipelines share the main pool.PubSubStatsPubSubStats // number of stale connections removed from the pool // number of times a wait timeout occurred // number of total connections in the pool // number of times a connection was found to be unusable // number of times a connection was waited // total time spent for waiting a connection in nanoseconds
func (*ConnPool).Stats() *Stats
func Pooler.Stats() *Stats
func (*SingleConnPool).Stats() *Stats
func (*StickyConnPool).Stats() *Stats
func github.com/redis/go-redis/v9.Pooler.PoolStats() *Stats
(*StickyConnPool) AddPoolHook(hook PoolHook)(*StickyConnPool) Close() error(*StickyConnPool) CloseConn(ctx context.Context, cn *Conn, reason string, fromState string) error DiscardOnClose configures the pool to remove the claimed connection from
the parent pool on Close instead of returning it. It must be called before
the pool is used.(*StickyConnPool) Get(ctx context.Context) (*Conn, error)(*StickyConnPool) IdleLen() int(*StickyConnPool) Len() int(*StickyConnPool) NewConn(ctx context.Context) (*Conn, error)(*StickyConnPool) Put(ctx context.Context, cn *Conn)(*StickyConnPool) Remove(ctx context.Context, cn *Conn, reason error)(*StickyConnPool) RemovePoolHook(hook PoolHook) RemoveWithoutTurn has the same behavior as Remove for StickyConnPool
since StickyConnPool doesn't use a turn-based queue system.(*StickyConnPool) Reset(ctx context.Context) error SetOnFirstConn configures a callback that runs when the sticky pool first
claims a parent connection. It must be called before the pool is used. Size returns the maximum pool size, which is always 1 for StickyConnPool.(*StickyConnPool) Stats() *Stats
*StickyConnPool : Pooler
*StickyConnPool : github.com/prometheus/common/expfmt.Closer
*StickyConnPool : io.Closer
func NewStickyConnPool(pool Pooler) *StickyConnPool
Package-Level Functions (total 17)
GetCachedTimeNs returns the current time in nanoseconds.
Exported for use by other packages that need fast time access.
GetMetricConnectionCreateTimeCallback returns the metric callback for connection creation time.
GetMetricConnectionHandoffCallback returns the metric callback for connection handoffs.
This is used by maintnotifications to record handoff metrics.
GetMetricConnectionRelaxedTimeoutCallback returns the metric callback for connection relaxed timeout changes.
This is used by maintnotifications to record relaxed timeout metrics.
GetMetricErrorCallback returns the metric callback for error tracking.
This is used by cluster and client code to record error metrics.
GetMetricMaintenanceNotificationCallback returns the metric callback for maintenance notifications.
This is used by maintnotifications to record notification metrics.
NewPoolHookManager creates a new pool hook manager.
NewPubSubPool implements a pool for PubSub connections.
It intentionally does not implement the Pooler interface
NewSingleConnPool creates a new single connection pool.
The pool will always return the same connection.
The pool will not:
- Close the connection
- Reconnect the connection
- Track the connection in any way
SetAllMetricCallbacks sets all metric callbacks atomically.
Pass nil to clear all callbacks (disable metrics).
This ensures all callbacks are set together under a single lock,
preventing inconsistent state during registration.
Note on thread safety: After returning, there is a small window where
concurrent getMetric* calls may return the old callback value. This is
acceptable for metrics - at most one event may go to the old recorder
or be missed during the transition. The callbacks themselves are immutable
function pointers, so calling an "old" callback is safe.
ValidFromCreatedIdleOrUnusable returns a predefined slice for initialization transitions.
Use this to avoid allocations when calling AwaitAndTransition or TryTransition.
ValidFromIdle returns a predefined slice containing only StateIdle.
Use this to avoid allocations when calling AwaitAndTransition or TryTransition.
Package-Level Variables (total 8)
ErrClosed performs any operation on the closed client will return this error.
ErrConnUnusableTimeout is returned when a connection is not usable and we timed out trying to mark it as unusable.
ErrInvalidStateTransition is returned when a state transition is not allowed
ErrPoolExhausted is returned from a pool connection method
when the maximum number of database connections in the pool has been reached.
ErrPoolTimeout timed out waiting to get a connection from the connection pool.
ErrPoolTryFull is the result of TryGet (the non-waiting acquire) when the
pool has no free turn now. It is not a timeout, because nothing waited. A
caller with a fallback uses it to spill at once. The pipeline pool spills to
the main pool this way. ErrPoolTryFull is different from ErrPoolTimeout on
purpose. Thus getConn does not record a false pool timeout (Stats.Timeouts or
POOL_TIMEOUT) for a non-wait. A real wait still returns ErrPoolTimeout.
ErrStateMachineClosed is returned when operating on a closed state machine
ErrTimeout is returned when a state transition times out
Package-Level Constants (total 14)
CloseReasonAuthError indicates the connection was closed due to an
authentication error during re-authentication.
CloseReasonFailover indicates the connection was closed due to a failover event.
CloseReasonHookError indicates the connection was closed due to an error
in a pool hook (OnGet or OnPut).
CloseReasonMaintNotificationsDisabled indicates the connection enabled
maintenance notifications, but the client later downgraded and disabled
maintenance notification handling for the pool.
CloseReasonStale indicates the connection was closed because it exceeded
the idle timeout or max lifetime.
CloseReasonTest is used in tests when closing connections.
MetricStateIdle indicates the connection is idle in the pool,
ready to be acquired.
MetricStateUsed indicates the connection is currently being used
by a client operation.
StateClosed - Connection closed
StateCreated - Connection just created, not yet initialized
StateIdle - Connection initialized and idle in pool, ready to be acquired
StateInitializing - Connection initialization in progress
StateInUse - Connection actively processing a command (retrieved from pool)
StateUnusable - Connection temporarily unusable due to background operation
(handoff, reauth, etc.). Cannot be acquired from pool.
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.