Skip to main content

ConnectionPool

Struct ConnectionPool 

Source
pub struct ConnectionPool<S> { /* private fields */ }
Expand description

A pool of Redis connections that dispatches commands across them.

Generic over S: RedisExecutor, so it works with:

  • RedisConnection (standalone)
  • ClusterConnection (cluster – each entry manages its own topology)
  • SentinelConnection (sentinel – each entry discovers its own master)
  • ResilientConnection (standalone with auto-reconnect)
  • Any custom type implementing RedisExecutor

The pool implements Clone via Arc for cross-task sharing and implements RedisExecutor itself for composability.

§Concurrency

ConnectionPool<S> is Clone + Send + Sync when S: Send. All clones share the same pool via Arc. Each individual connection is protected by its own Mutex, so up to N commands can execute in parallel (one per pooled connection). The dispatch strategy controls which connection handles each command.

Implementations§

Source§

impl<S> ConnectionPool<S>
where S: Send + 'static,

Source

pub async fn connect<F, Fut>( size: usize, factory: F, ) -> Result<Self, RedisError>
where F: Fn() -> Fut, Fut: Future<Output = Result<S, RedisError>>,

Create a pool by calling a factory function size times.

Each call to factory should return a new, independent connection. For cluster connections, each entry will discover its own topology.

Source

pub async fn connect_with_config<F, Fut>( config: PoolConfig, factory: F, ) -> Result<Self, RedisError>
where F: Fn() -> Fut, Fut: Future<Output = Result<S, RedisError>>,

Create a pool with custom configuration.

Source

pub async fn connect_with_factory<Fact>( config: PoolConfig, factory: Fact, ) -> Result<Self, RedisError>
where Fact: PoolFactory<Connection = S>, S: RedisExecutor,

Create a pool with custom configuration and a PoolFactory.

The factory is used both to build the initial connections and to replace any connection slot that fails a health-check PING. This ensures that a single dead connection does not permanently degrade pool capacity.

Source

pub fn connect_lazy<Fact>(config: PoolConfig, factory: Fact) -> Self
where Fact: PoolFactory<Connection = S>, S: RedisExecutor,

Create a factory-backed pool without opening a connection.

The first command creates the first slot; later acquisition contention grows the pool up to config.max_size (or config.size when omitted). The lazy pool’s effective minimum is zero, regardless of config.min_size, so an explicitly spawned idle reaper may return it to zero while the application is inactive.

Source

pub fn from_connections( connections: Vec<S>, config: PoolConfig, ) -> Result<Self, RedisError>

Build a pool from pre-created connections using the given PoolConfig.

Sizing fields are ignored here because a pool without a retained factory cannot restore reaped capacity. The pool is fixed at the number of supplied connections. Dispatch, health-check, acquisition-timeout, name, and metrics settings are applied normally.

§Errors

Returns an error if connections is empty.

Source

pub fn size(&self) -> usize

Returns the number of connections in the pool.

Source

pub fn name(&self) -> &str

Returns the stable name used to identify this pool in metrics.

Source

pub fn dispatch_strategy(&self) -> DispatchStrategy

Returns the dispatch strategy.

Source

pub fn stats(&self) -> PoolStats

Returns a snapshot of current pool utilization.

Reads the per-connection in-flight atomic counters to compute idle and active connection counts. This is a non-blocking, snapshot-in- time read — values may have changed by the time the caller acts on them.

Useful for emitting redis_pool_connections_active / redis_pool_connections_idle Prometheus metrics.

Source

pub async fn reap_idle_connections(&self) -> usize

Remove idle connections above the configured minimum immediately.

This is a one-shot operation and does not spawn a task. It returns zero when no idle_timeout is configured or no eligible slot exists.

Source

pub fn spawn_idle_reaper(&self, interval: Duration) -> IdleReaperHandle

Explicitly spawn periodic idle-connection reaping.

Pool construction never starts this task. The first sweep runs immediately, then every interval. Dropping the returned handle stops the task.

§Panics

Panics when interval is zero, no idle timeout is configured, or this method is called outside a Tokio runtime.

Source

pub fn is_closed(&self) -> bool

Returns true once close has been called on this pool or any of its clones.

Source

pub async fn close(self)

Gracefully close the pool, draining in-flight commands.

Flips a shared “closed” bit so that every clone of this pool rejects new commands with RedisError::ConnectionClosed, then waits for all in-flight commands to finish before returning. Each accepted command atomically increments a pool-wide operation count while confirming the pool is open, so closing and admission have one unambiguous order.

This is the SIGTERM drain path: stop accepting work, let outstanding commands complete, then exit. It does not itself close the underlying connections – dropping the pool (and its last clone) releases them – but it guarantees no command is mid-flight when the connections are dropped.

Because the state is shared through the pool’s Arc, calling close on one clone drains and closes the pool seen by every clone. Commands admitted before the close transition finish normally; commands racing after it are rejected.

§Example
use redis_tower::{ConnectionPool, RedisConnection};

let pool =
    ConnectionPool::connect(4, || RedisConnection::connect("127.0.0.1:6379")).await?;

// On shutdown (SIGTERM, ctrl-c, ...): stop accepting new work and drain
// the pool before exit.
pool.close().await;
Source§

impl<S> ConnectionPool<S>
where S: RedisExecutor + Send + 'static,

Source

pub fn spawn_health_prober( &self, config: HealthProberConfig, ) -> HealthProberHandle

Explicitly spawn active PING probing with an owned lifecycle handle.

Pool construction never starts a prober. The first sweep runs immediately. Dropping the returned handle stops the task.

Source

pub fn spawn_health_prober_with<P>( &self, config: HealthProberConfig, probe: P, ) -> HealthProberHandle
where P: HealthProbe<S>,

Explicitly spawn active probing with a custom HealthProbe.

Results are observational: they update PoolStats and MetricsRecorder without silently changing dispatch policy.

§Panics

Panics when the interval or timeout is zero, or when called outside a Tokio runtime.

Source§

impl ConnectionPool<RedisConnection>

Source

pub async fn reauthenticate_all( &self, credentials: &Credentials, ) -> Result<(), RedisError>

Send AUTH with credentials to every active pool connection.

Slots are locked one at a time, so a credential update never races a command on the same socket. Other slots remain available while the update progresses. A connection created concurrently through a provider-backed factory fetches the provider’s current credentials and therefore does not need to be revisited by this pass.

If a slot rejects the replacement, this method returns the first error after attempting every active slot but leaves failed slots installed with their previous Redis identity. Call Self::close and rebuild the pool through its provider-backed factory when rotation must fail closed.

Source

pub fn spawn_credential_reauthentication( &self, provider: Arc<dyn StreamingCredentialProvider>, ) -> CredentialReauthenticationHandle

Apply every credential emitted by provider to all active slots.

Dropping the returned handle stops future updates without closing the pool. Use the same provider in the pool’s CredentialConnectionFactory so replacement and newly grown slots authenticate with current material. Rejected updates are logged without their error text and later updates are still consumed; failed slots are not automatically removed. A fail-closed owner must close and rebuild the pool before routing more application traffic.

Source§

impl<S> ConnectionPool<S>
where S: RedisExecutor + Send + 'static,

Source

pub async fn execute<Cmd: Command>( &self, cmd: Cmd, ) -> Result<Cmd::Response, RedisError>

Execute a command through the pool.

This is the primary API. The pool selects a connection via the configured dispatch strategy and executes the command on it. To avoid head-of-line blocking, if the strategy-selected connection is currently busy the pool first scans for any idle connection (via try_lock) and uses that instead, only awaiting a busy slot when every connection is in use.

If health_check_interval is configured and the selected connection has been idle longer than the interval, a PING is sent first to verify the connection is alive. If the PING fails and the pool was built with a PoolFactory (via ConnectionPool::connect_with_factory), the dead slot is replaced with a fresh connection before the actual command is executed. If no factory is available, the PING error is returned to the caller.

If cmd is wrapped in redis_tower_core::WithDeadline, pool acquisition observes that same absolute deadline. The request deadline and PoolConfig::acquisition_timeout do not add together: whichever expires first determines the error.

Source

pub async fn health_check(&self) -> Result<(), RedisError>

Send a PING to every connection in the pool.

Acquires each connection sequentially and sends PING. Returns Ok(()) if all connections respond successfully. Returns the first error encountered if any connection is unhealthy.

Useful for Kubernetes readiness probes and /health endpoints. For a fast single-connection liveness check, call execute with Ping directly.

Trait Implementations§

Source§

impl<S> Clone for ConnectionPool<S>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<S> RedisExecutor for ConnectionPool<S>
where S: RedisExecutor + Send + 'static,

Source§

fn execute<Cmd: Command>( &mut self, cmd: Cmd, ) -> impl Future<Output = Result<Cmd::Response, RedisError>> + Send

Execute a Redis command and return its typed response.

Auto Trait Implementations§

§

impl<S> !RefUnwindSafe for ConnectionPool<S>

§

impl<S> !UnwindSafe for ConnectionPool<S>

§

impl<S> Freeze for ConnectionPool<S>
where Arc<PoolInner<S>>: Freeze,

§

impl<S> Send for ConnectionPool<S>
where Arc<PoolInner<S>>: Send,

§

impl<S> Sync for ConnectionPool<S>
where Arc<PoolInner<S>>: Sync,

§

impl<S> Unpin for ConnectionPool<S>
where Arc<PoolInner<S>>: Unpin,

§

impl<S> UnsafeUnpin for ConnectionPool<S>
where Arc<PoolInner<S>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more