0
# Client Management
1
2
Core functionality for creating Redis clients and managing connections, including support for single instances, clusters, and sentinel configurations with connection pooling and authentication.
3
4
## Capabilities
5
6
### Client Creation
7
8
Creates a Redis client with default modules pre-loaded and optional configuration.
9
10
```typescript { .api }
11
/**
12
* Creates a Redis client with default modules (bloom, json, search, time-series) pre-loaded
13
* @param options - Optional client configuration
14
* @returns Configured Redis client instance
15
*/
16
function createClient<M, F, S, RESP, TYPE_MAPPING>(
17
options?: RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>
18
): RedisClientType<RedisDefaultModules & M, F, S, RESP, TYPE_MAPPING>;
19
20
interface RedisClientOptions<M = RedisModules, F = RedisFunctions, S = RedisScripts, RESP = RespVersions, TYPE_MAPPING = TypeMapping> {
21
/** Connection URL in format redis://[username[:password]@]host[:port][/database] */
22
url?: string;
23
/** Socket configuration for fine-grained connection control */
24
socket?: RedisSocketOptions;
25
/** Username for authentication */
26
username?: string;
27
/** Password for authentication */
28
password?: string;
29
/** Credentials provider for dynamic authentication */
30
credentialsProvider?: CredentialsProvider;
31
/** Client name for identification */
32
name?: string;
33
/** Database number to select (0-15 typically) */
34
database?: number;
35
/** Maximum length of commands queue */
36
commandsQueueMaxLength?: number;
37
/** Disable offline queue behavior */
38
disableOfflineQueue?: boolean;
39
/** Enable readonly mode */
40
readonly?: boolean;
41
/** Ping interval for keep-alive (milliseconds) */
42
pingInterval?: number;
43
/** Default command options */
44
commandOptions?: CommandOptions;
45
/** Client-side cache configuration */
46
clientSideCache?: ClientSideCacheOptions;
47
/** Additional modules to load */
48
modules?: M;
49
/** Redis functions to register */
50
functions?: F;
51
/** Redis scripts to define */
52
scripts?: S;
53
}
54
55
interface RedisSocketOptions {
56
/** Host to connect to */
57
host?: string;
58
/** Port to connect to */
59
port?: number;
60
/** Connection path for Unix sockets */
61
path?: string;
62
/** Connection timeout in milliseconds */
63
connectTimeout?: number;
64
/** Command timeout in milliseconds */
65
commandTimeout?: number;
66
/** Enable TLS/SSL */
67
tls?: boolean;
68
/** Additional socket options */
69
[key: string]: any;
70
}
71
```
72
73
**Usage Examples:**
74
75
```typescript
76
import { createClient } from "redis";
77
78
// Basic connection
79
const client = createClient();
80
81
// Connection with URL
82
const client = createClient({
83
url: "redis://username:password@localhost:6379/0"
84
});
85
86
// Connection with detailed options
87
const client = createClient({
88
socket: {
89
host: "localhost",
90
port: 6379,
91
connectTimeout: 5000,
92
commandTimeout: 5000
93
},
94
username: "default",
95
password: "secret",
96
database: 0,
97
name: "my-client"
98
});
99
100
// Connection with TLS
101
const client = createClient({
102
url: "rediss://username:password@redis.example.com:6380",
103
socket: {
104
tls: true,
105
rejectUnauthorized: false
106
}
107
});
108
```
109
110
### Cluster Client Creation
111
112
Creates a Redis cluster client for distributed Redis setups.
113
114
```typescript { .api }
115
/**
116
* Creates a Redis cluster client for distributed Redis setups
117
* @param options - Cluster configuration including root nodes
118
* @returns Configured Redis cluster client instance
119
*/
120
function createCluster<M, F, S, RESP, TYPE_MAPPING>(
121
options: RedisClusterOptions<M, F, S, RESP, TYPE_MAPPING>
122
): RedisClusterType<RedisDefaultModules & M, F, S, RESP, TYPE_MAPPING>;
123
124
interface RedisClusterOptions<M = RedisModules, F = RedisFunctions, S = RedisScripts, RESP = RespVersions, TYPE_MAPPING = TypeMapping> {
125
/** Array of cluster root node configurations */
126
rootNodes: Array<RedisClusterNode>;
127
/** Default options applied to all nodes */
128
defaults?: Partial<RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>>;
129
/** Minimize connections by reusing existing connections */
130
minimizeConnections?: boolean;
131
/** Use replica nodes for read operations */
132
useReplicas?: boolean;
133
/** Maximum command redirections before giving up */
134
maxCommandRedirections?: number;
135
/** Node address mapping for NAT/proxy environments */
136
nodeAddressMap?: Record<string, RedisClusterNode>;
137
/** Additional modules to load */
138
modules?: M;
139
/** Redis functions to register */
140
functions?: F;
141
/** Redis scripts to define */
142
scripts?: S;
143
}
144
145
interface RedisClusterNode {
146
/** Node host */
147
host: string;
148
/** Node port */
149
port: number;
150
}
151
```
152
153
**Usage Examples:**
154
155
```typescript
156
import { createCluster } from "redis";
157
158
// Basic cluster setup
159
const cluster = createCluster({
160
rootNodes: [
161
{ host: "localhost", port: 7000 },
162
{ host: "localhost", port: 7001 },
163
{ host: "localhost", port: 7002 }
164
]
165
});
166
167
// Cluster with replica reads
168
const cluster = createCluster({
169
rootNodes: [
170
{ host: "redis-1.example.com", port: 6379 },
171
{ host: "redis-2.example.com", port: 6379 },
172
{ host: "redis-3.example.com", port: 6379 }
173
],
174
useReplicas: true,
175
maxCommandRedirections: 16,
176
defaults: {
177
username: "cluster-user",
178
password: "cluster-password"
179
}
180
});
181
```
182
183
### Sentinel Client Creation
184
185
Creates a Redis sentinel client for high availability setups.
186
187
```typescript { .api }
188
/**
189
* Creates a Redis sentinel client for high availability setups
190
* @param options - Sentinel configuration including sentinel nodes
191
* @returns Configured Redis sentinel client instance
192
*/
193
function createSentinel<M, F, S, RESP, TYPE_MAPPING>(
194
options: RedisSentinelOptions<M, F, S, RESP, TYPE_MAPPING>
195
): RedisSentinelType<RedisDefaultModules & M, F, S, RESP, TYPE_MAPPING>;
196
197
interface RedisSentinelOptions<M = RedisModules, F = RedisFunctions, S = RedisScripts, RESP = RespVersions, TYPE_MAPPING = TypeMapping> {
198
/** Sentinel service name */
199
name: string;
200
/** Array of sentinel node configurations */
201
sentinelRootNodes: Array<RedisSentinelNode>;
202
/** Maximum command rediscoveries before giving up */
203
maxCommandRediscovers?: number;
204
/** Default options for Redis master/replica nodes */
205
nodeClientOptions?: Partial<RedisClientOptions<M, F, S, RESP, TYPE_MAPPING>>;
206
/** Options for sentinel client connections */
207
sentinelClientOptions?: Partial<RedisClientOptions>;
208
/** Connection pool size for master nodes */
209
masterPoolSize?: number;
210
/** Connection pool size for replica nodes */
211
replicaPoolSize?: number;
212
/** Interval for scanning sentinel nodes (milliseconds) */
213
scanInterval?: number;
214
/** Additional modules to load */
215
modules?: M;
216
/** Redis functions to register */
217
functions?: F;
218
/** Redis scripts to define */
219
scripts?: S;
220
}
221
222
interface RedisSentinelNode {
223
/** Sentinel host */
224
host: string;
225
/** Sentinel port */
226
port: number;
227
}
228
```
229
230
**Usage Examples:**
231
232
```typescript
233
import { createSentinel } from "redis";
234
235
// Basic sentinel setup
236
const sentinel = createSentinel({
237
name: "mymaster",
238
sentinelRootNodes: [
239
{ host: "sentinel-1.example.com", port: 26379 },
240
{ host: "sentinel-2.example.com", port: 26379 },
241
{ host: "sentinel-3.example.com", port: 26379 }
242
]
243
});
244
245
// Sentinel with custom configuration
246
const sentinel = createSentinel({
247
name: "mymaster",
248
sentinelRootNodes: [
249
{ host: "localhost", port: 26379 },
250
{ host: "localhost", port: 26380 },
251
{ host: "localhost", port: 26381 }
252
],
253
nodeClientOptions: {
254
username: "redis-user",
255
password: "redis-password",
256
database: 0
257
},
258
masterPoolSize: 10,
259
replicaPoolSize: 5,
260
scanInterval: 30000
261
});
262
```
263
264
### Connection Management
265
266
Core methods for managing client connections and lifecycle.
267
268
```typescript { .api }
269
interface RedisClientType<M, F, S, RESP, TYPE_MAPPING> {
270
/** Connect to Redis server */
271
connect(): Promise<RedisClientType<M, F, S, RESP, TYPE_MAPPING>>;
272
/** Disconnect from Redis server (deprecated, use close/destroy) */
273
disconnect(): Promise<void>;
274
/** Graceful quit (deprecated, use close) */
275
quit(): Promise<string>;
276
/** Close client, wait for pending commands to complete */
277
close(): Promise<void>;
278
/** Destroy client immediately, reject pending commands */
279
destroy(): void;
280
281
/** Whether socket is open */
282
readonly isOpen: boolean;
283
/** Whether client is ready for commands */
284
readonly isReady: boolean;
285
/** Whether pub/sub is active */
286
readonly isPubSubActive: boolean;
287
/** Socket reconnection counter */
288
readonly socketEpoch: number;
289
/** Whether WATCH is active */
290
readonly isWatching: boolean;
291
/** Whether WATCH has been invalidated */
292
readonly isDirtyWatch: boolean;
293
}
294
```
295
296
**Usage Examples:**
297
298
```typescript
299
import { createClient } from "redis";
300
301
const client = createClient();
302
303
// Connect and check status
304
await client.connect();
305
console.log("Connected:", client.isOpen);
306
console.log("Ready:", client.isReady);
307
308
// Perform operations
309
await client.set("key", "value");
310
311
// Graceful shutdown
312
await client.close();
313
314
// Or immediate destruction
315
client.destroy();
316
```
317
318
### Client Utilities
319
320
Additional utility methods for client management and configuration.
321
322
```typescript { .api }
323
interface RedisClientType<M, F, S, RESP, TYPE_MAPPING> {
324
/** Create a duplicate client with optional overrides */
325
duplicate(overrides?: Partial<RedisClientOptions>): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
326
327
/** Create a proxy with command options */
328
withCommandOptions<OPTIONS>(options: CommandOptions<OPTIONS>): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
329
330
/** Create a proxy with type mapping */
331
withTypeMapping<NEW_TYPE_MAPPING>(typeMapping: NEW_TYPE_MAPPING): RedisClientType<M, F, S, RESP, NEW_TYPE_MAPPING>;
332
333
/** Create a proxy with abort signal */
334
withAbortSignal(signal: AbortSignal): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
335
336
/** Create a proxy that executes commands ASAP */
337
asap(): RedisClientType<M, F, S, RESP, TYPE_MAPPING>;
338
339
/** Reset client to default state */
340
reset(): Promise<void>;
341
342
/** Ref the underlying socket */
343
ref(): void;
344
345
/** Unref the underlying socket */
346
unref(): void;
347
}
348
```
349
350
**Usage Examples:**
351
352
```typescript
353
import { createClient } from "redis";
354
355
const client = createClient();
356
await client.connect();
357
358
// Create a duplicate with different database
359
const client2 = client.duplicate({ database: 1 });
360
await client2.connect();
361
362
// Create proxy with command options
363
const clientWithTimeout = client.withCommandOptions({
364
timeout: 5000
365
});
366
367
// Create proxy with abort signal
368
const controller = new AbortController();
369
const clientWithAbort = client.withAbortSignal(controller.signal);
370
371
// Reset client state
372
await client.reset();
373
```
374
375
### Connection Pool Management
376
377
Connection pooling functionality for high-performance applications.
378
379
```typescript { .api }
380
/**
381
* Creates a Redis client pool for connection pooling
382
* @param options - Pool configuration options
383
* @returns Redis client pool instance
384
*/
385
function createClientPool(options?: RedisPoolOptions): RedisClientPoolType;
386
387
interface RedisPoolOptions {
388
/** Minimum number of connections to maintain */
389
minimum?: number;
390
/** Maximum number of connections allowed */
391
maximum?: number;
392
/** Maximum time a connection can be idle (milliseconds) */
393
idleTimeout?: number;
394
/** Time between connection validation checks (milliseconds) */
395
validationInterval?: number;
396
/** Function to validate connections */
397
validate?: (client: RedisClientType) => Promise<boolean>;
398
}
399
400
interface RedisClientPoolType {
401
/** Execute function with a client from the pool */
402
use<T>(fn: (client: RedisClientType) => Promise<T>): Promise<T>;
403
/** Get pool statistics */
404
stats(): PoolStats;
405
/** Destroy the pool and all connections */
406
destroy(): Promise<void>;
407
}
408
409
interface PoolStats {
410
/** Total connections in pool */
411
total: number;
412
/** Available connections */
413
available: number;
414
/** Connections currently in use */
415
inUse: number;
416
/** Pending connection requests */
417
pending: number;
418
}
419
```
420
421
**Usage Examples:**
422
423
```typescript
424
import { createClient, createClientPool } from "redis";
425
426
// Create client and pool
427
const client = createClient();
428
const pool = createClientPool({
429
minimum: 2,
430
maximum: 10,
431
idleTimeout: 30000
432
});
433
434
// Use pool for operations
435
const result = await pool.use(async (client) => {
436
await client.set("key", "value");
437
return client.get("key");
438
});
439
440
// Check pool statistics
441
const stats = pool.stats();
442
console.log(`Pool: ${stats.inUse}/${stats.total} connections in use`);
443
444
// Cleanup
445
await pool.destroy();
446
```
447
448
## Error Handling
449
450
```typescript { .api }
451
// Connection errors
452
class ConnectionTimeoutError extends Error {
453
constructor(message?: string);
454
}
455
456
class ClientClosedError extends Error {
457
constructor(message?: string);
458
}
459
460
class ClientOfflineError extends Error {
461
constructor(message?: string);
462
}
463
464
// Redis errors
465
class ErrorReply extends Error {
466
constructor(message: string);
467
}
468
469
class ReconnectStrategyError extends Error {
470
constructor(message?: string);
471
}
472
```