@digitalwalletcorp/redis-pooling
v1.4.1
Published
This is a library for redis connection pooling
Readme
Redis Pooling
A lightweight TypeScript/JavaScript library for managing Redis connections with pooling support. Designed for both server-side Node.js applications and cron-style background jobs, it wraps ioredis clients in a pool with safe acquire/release methods, connection validation, and optional custom utility functions like getKeys and deleteKeys.
✨ Features
- Connection Pooling: Efficiently manage multiple Redis connections with
minandmaxpool size configuration. - Safe Acquire/Release: Guaranteed handling of Redis client lifecycle with optional database selection (
SELECT dbIndex). - Custom Utilities: Built-in helper methods like
getKeys(pattern)anddeleteKeys(pattern)for convenient Redis key operations. - Connection Validation: PING-based validation with timeout before borrowing from the pool.
- TLS Support: Optional TLS configuration for secure Redis connections.
- Pluggable Logging: Pass your own logger (
debug/info/warn/error) to route logs into your application's logging. Without one,debug/infologs go to the console whendebugis enabled and warnings go throughprocess.emitWarning.
📦 Installation
npm install @digitalwalletcorp/redis-pooling
# or
yarn add @digitalwalletcorp/redis-pooling📖 Usage
Example 1: Pure NodeJS Style Instantiation
This pattern is ideal for short-lived Node.js scripts, such as cron jobs, where a pool is created, used, and destroyed within a single run.
import { RedisPool } from '@digitalwalletcorp/redis-pooling';
const redisPool = new RedisPool({
url: 'redis://localhost:6379',
dbIndex: 0,
max: 10,
min: 2
});
async function main() {
const client = await redisPool.acquire();
try {
await client.set('key', 'value');
const value = await client.get('key');
console.log('Redis value:', value);
} finally {
await redisPool.release(client);
}
}
main().catch(console.error);Example 2: Singleton Pool Instantiation using Web-App
For long-running web applications, a singleton Redis pool ensures efficient reuse of connections across requests.
@/server/singleton/redis-pooling
import { RedisPool } from '@digitalwalletcorp/redis-pooling';
export const redisPool = new RedisPool({
url: 'redis://localhost:6379',
dbIndex: 0,
max: 20,
min: 5
});@/server/api/some-rest-api
import { redisPool } from '@/server/singleton/redis-pooling';
async function handleRequest() {
const client = await redisPool.acquire();
try {
const value = await client.get('session:1234');
console.log('Session value:', value);
} finally {
await redisPool.release(client);
}
}Example 3: Using Custom Methods (getKeys, deleteKeys)
RedisClient extends the standard ioredis client with convenient helper methods.
getKeys and deleteKeys use SCAN and UNLINK internally to avoid blocking Redis with large datasets (unlike KEYS).
All other standard Redis commands remain available.
import { redisPool } from '@/server/singleton/redis-pooling';
async function manageCache() {
const client = await redisPool.acquire();
try {
// Get all keys matching a pattern using SCAN (avoids blocking Redis like KEYS does)
const keys = await client.getKeys('user:*');
console.log('Matching keys:', keys);
// Delete all matching keys using UNLINK
const delResults = await client.deleteKeys('cache:*');
const succeeded = delResults.filter(a => a.status === 'fulfilled');
const delCount = succeeded.reduce((acc, cur) => acc + (cur as PromiseFulfilledResult<number>).value, 0);
console.log(`Deleted ${delCount} keys`);
} finally {
await redisPool.release(client);
}
}📚 API Reference
new RedisPool(config: RedisConfig, options?: RedisPoolOptions)
Creates a Redis connection pool.
| Property | Type | Default | Description |
| ---------------- | ------- | -------- | -------------------------------------- |
| url | string | required | Redis connection URL. |
| dbIndex | number | 0 | Default Redis database index. |
| max | number | 10 | Maximum number of clients in the pool. |
| min | number | 0 | Minimum number of clients in the pool. |
| connectTimeout | number | 5000 | Connection timeout in milliseconds. |
| acquireTimeout | number | 10000 | Timeout in milliseconds to acquire a client from the pool. |
| testOnBorrow | boolean | true | Enable connection validate on borrow. |
| enableTls | boolean | false | Enable TLS for Redis connection. |
RedisPoolOptions:
| Property | Type | Default | Description |
| ----------------- | -------------------- | --------- | ------------------------------------------------------------------------------------------------------------- |
| logger | RedisPoolLogger | - | Destination of all logs. When given, the logger decides which levels are output (debug is ignored). |
| debug | boolean | false | Only used without logger. When true, debug / info logs are written to console.debug / console.info. |
| acquireLogLevel | 'debug' \| 'info' | 'debug' | Level used for client acquire / release logs. |
RedisPoolLogger:
interface RedisPoolLogger {
debug(...args: any[]): void;
info(...args: any[]): void;
warn(...args: any[]): void;
error(...args: any[]): void;
}Each log is called with the header '[RedisPooling]', a message, and optional details, e.g. logger.error('[RedisPooling]', 'detected error (on error)', error).
| Level | Messages |
| ---------------- | --------------------------------------------------------------------------------------------------------------- |
| debug / info | Redis client N has been acquired., Redis client released., Redis client destroyed due to invalid status. (chosen by acquireLogLevel) |
| info | Destroying Redis pool..., Redis pool destroyed. |
| debug | start validate, ping succeeded, retry strategy called ..., client quit, client disconnected |
| warn | ping failed, detected error (on reconnectOnError) |
| error | detected error (on error) |
RedisPool Methods
| Method | Signature | Description |
| ------------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------- |
| acquire(dbIndex?: number) | Promise<RedisClient> | Acquire a Redis client from the pool. Optionally switch to a different database index. |
| release(client: RedisClient) | Promise<void> | Release the Redis client back to the pool. |
| destroy() | Promise<void> | Drain and clear all connections in the pool. |
RedisClient Methods
Extends the standard ioredis Redis client with additional helpers:
| Method | Signature | Description |
| ----------------------------- | ------------------- | ----------------------------------------------------------------------------------------------- |
| getKeys(pattern: string) | Promise<string[]> | Scan and return all keys matching a pattern. |
| deleteKeys(pattern: string) | Promise<PromiseSettledResult<number>[]> | Scan and delete all keys matching a pattern using UNLINK. Returns an array of results, one for each batch processed by UNLINK. Each result contains the number of keys deleted in that batch. |
🗄 Database Index Handling
This library provides a Redis connection pool capable of managing Redis clients
connected to different database indexes (SELECT db).
All database indexes share a single pool, so max is the upper limit of connections to the Redis server.
The database index is selected every time a client is acquired.
Calling acquire(dbIndex):
When
dbIndexis specified, the acquired client will be connected to the specified database index.
Calling acquire() without dbIndex:
When
dbIndexis not specified, the acquired client will be connected to the default database index configured when the pool was created via createRedisPool({ dbIndex }).
// The default db index: 2
const pool = new RedisPool({ url, dbIndex: 2 });
// With dbIndex: connected to DB 1
const client1 = await pool.acquire(1);
// Without dbIndex: connected to DB 2 (default)
const client2 = await pool.acquire();💡 Notes
- Always release clients back to the pool using
release(client)to avoid connection leaks. - Use
acquire()andrelease()insidetry/finallyblocks for safe resource management. - Without
logger,warn/errorlogs are emitted viaprocess.emitWarningso that callers can suppress them with the--no-warningsflag (e.g.node --no-warnings app.js, orNODE_OPTIONS=--no-warnings) or handle them withprocess.on('warning').
📜 License
This project is licensed under the MIT License. See the LICENSE file for details.
