0
# Configuration
1
2
ioredis provides comprehensive configuration options for customizing connection behavior, performance characteristics, and operational features. Configuration applies to both standalone Redis connections and cluster deployments.
3
4
## Capabilities
5
6
### Redis Options
7
8
Core configuration interface for Redis connections with extensive customization capabilities.
9
10
```typescript { .api }
11
interface RedisOptions {
12
// Connection settings
13
host?: string; // default: "localhost"
14
port?: number; // default: 6379
15
path?: string; // Unix socket path
16
username?: string; // Redis 6+ ACL username
17
password?: string; // Authentication password
18
db?: number; // Database index (default: 0)
19
20
// Network configuration
21
family?: 4 | 6; // IP version (default: 4)
22
keepAlive?: number; // TCP keep-alive (default: 0)
23
noDelay?: boolean; // Disable Nagle's algorithm (default: true)
24
connectTimeout?: number; // Connection timeout ms (default: 10000)
25
commandTimeout?: number; // Command timeout ms
26
socketTimeout?: number; // Socket timeout ms
27
28
// Retry and reconnection
29
retryStrategy?: (times: number) => number | void | null;
30
reconnectOnError?: (err: Error) => boolean | 1 | 2 | null;
31
lazyConnect?: boolean; // Delay connection (default: false)
32
maxRetriesPerRequest?: number | null; // Max retries per command (default: 20)
33
34
// Queue and performance
35
enableOfflineQueue?: boolean; // Queue when disconnected (default: true)
36
enableReadyCheck?: boolean; // Wait for server ready (default: true)
37
enableAutoPipelining?: boolean; // Auto batch commands (default: false)
38
autoPipeliningIgnoredCommands?: string[]; // Commands to exclude from autopipelining
39
40
// Pub/Sub behavior
41
autoResubscribe?: boolean; // Resubscribe on reconnect (default: true)
42
autoResendUnfulfilledCommands?: boolean; // Resend pending commands (default: true)
43
44
// Data handling
45
stringNumbers?: boolean; // Return numbers as strings (default: false)
46
47
// Advanced options
48
connectionName?: string; // Connection identifier
49
readOnly?: boolean; // Read-only mode (default: false)
50
monitor?: boolean; // Monitor mode (default: false)
51
52
// Custom commands and connectors
53
scripts?: Record<string, ScriptDefinition>;
54
Connector?: ConnectorConstructor;
55
}
56
57
interface ScriptDefinition {
58
lua: string;
59
numberOfKeys?: number;
60
readOnly?: boolean;
61
}
62
```
63
64
**Usage Examples:**
65
66
```typescript
67
import Redis from "ioredis";
68
69
// Basic configuration
70
const redis = new Redis({
71
host: "redis.example.com",
72
port: 6380,
73
password: "secret",
74
db: 1
75
});
76
77
// Advanced configuration
78
const redis2 = new Redis({
79
host: "redis.example.com",
80
port: 6379,
81
username: "app-user",
82
password: "secure-password",
83
84
// Network settings
85
connectTimeout: 5000,
86
commandTimeout: 2000,
87
keepAlive: 30000,
88
89
// Retry strategy
90
retryStrategy: (times) => {
91
const delay = Math.min(times * 50, 2000);
92
console.log(`Retrying connection in ${delay}ms (attempt ${times})`);
93
return delay;
94
},
95
96
// Performance optimization
97
enableAutoPipelining: true,
98
autoPipeliningIgnoredCommands: ["subscribe", "psubscribe"],
99
100
// Connection behavior
101
lazyConnect: true,
102
enableOfflineQueue: false,
103
maxRetriesPerRequest: 3
104
});
105
```
106
107
### Sentinel Configuration
108
109
Configuration options for Redis Sentinel deployments with high availability features.
110
111
```typescript { .api }
112
interface SentinelConnectionOptions extends RedisOptions {
113
sentinels: SentinelAddress[];
114
name: string; // Master name in Sentinel
115
role?: "master" | "slave"; // Preferred role (default: "master")
116
sentinelRetryStrategy?: (times: number) => number | void | null;
117
enableTLSForSentinelMode?: boolean; // TLS for Sentinel (default: false)
118
updateSentinels?: boolean; // Update Sentinel list (default: true)
119
failoverDetector?: boolean; // Active failover detection (default: false)
120
sentinelCommandTimeout?: number; // Sentinel command timeout
121
}
122
123
interface SentinelAddress {
124
host: string;
125
port: number;
126
username?: string;
127
password?: string;
128
}
129
```
130
131
**Usage Examples:**
132
133
```typescript
134
// Sentinel configuration
135
const redis = new Redis({
136
sentinels: [
137
{ host: "sentinel1.example.com", port: 26379 },
138
{ host: "sentinel2.example.com", port: 26379 },
139
{ host: "sentinel3.example.com", port: 26379 }
140
],
141
name: "mymaster",
142
role: "master",
143
144
// Sentinel-specific retry strategy
145
sentinelRetryStrategy: (times) => {
146
return times < 5 ? times * 1000 : null;
147
},
148
149
// Regular Redis options also apply
150
password: "redis-password",
151
db: 0,
152
connectTimeout: 10000
153
});
154
```
155
156
### TLS Configuration
157
158
Secure connections using TLS/SSL encryption for Redis and Sentinel connections.
159
160
```typescript { .api }
161
interface TLSOptions {
162
host?: string;
163
port?: number;
164
ca?: string | Buffer | Array<string | Buffer>;
165
cert?: string | Buffer;
166
key?: string | Buffer;
167
passphrase?: string;
168
servername?: string;
169
rejectUnauthorized?: boolean;
170
checkServerIdentity?: (servername: string, cert: any) => Error | undefined;
171
}
172
173
interface RedisOptions {
174
// ... other options
175
tls?: TLSOptions;
176
enableTLSForSentinelMode?: boolean;
177
}
178
```
179
180
**Usage Examples:**
181
182
```typescript
183
import * as fs from 'fs';
184
185
// TLS configuration
186
const redis = new Redis({
187
host: "redis.example.com",
188
port: 6380,
189
tls: {
190
ca: fs.readFileSync('/path/to/ca.crt'),
191
cert: fs.readFileSync('/path/to/client.crt'),
192
key: fs.readFileSync('/path/to/client.key'),
193
passphrase: 'key-passphrase',
194
rejectUnauthorized: true
195
}
196
});
197
198
// TLS with Sentinel
199
const redis2 = new Redis({
200
sentinels: [
201
{ host: "sentinel.example.com", port: 26379 }
202
],
203
name: "mymaster",
204
enableTLSForSentinelMode: true,
205
tls: {
206
rejectUnauthorized: false // For self-signed certificates
207
}
208
});
209
```
210
211
## Retry Strategies
212
213
### Connection Retry Strategy
214
215
Customize reconnection behavior when the connection is lost.
216
217
```typescript { .api }
218
type RetryStrategy = (times: number) => number | void | null;
219
220
interface RedisOptions {
221
retryStrategy?: RetryStrategy;
222
}
223
```
224
225
**Usage Examples:**
226
227
```typescript
228
const redis = new Redis({
229
host: "redis.example.com",
230
retryStrategy: (times) => {
231
// Exponential backoff with jitter
232
const delay = Math.min(times * 50, 2000) + Math.random() * 100;
233
234
// Give up after 10 attempts
235
if (times > 10) {
236
return null;
237
}
238
239
console.log(`Retrying connection in ${delay}ms (attempt ${times})`);
240
return delay;
241
}
242
});
243
244
// Fixed delay retry
245
const redis2 = new Redis({
246
retryStrategy: (times) => times < 5 ? 1000 : null
247
});
248
249
// No retry
250
const redis3 = new Redis({
251
retryStrategy: () => null
252
});
253
```
254
255
### Reconnect on Error Strategy
256
257
Control reconnection behavior for specific error conditions.
258
259
```typescript { .api }
260
type ReconnectOnError = (err: Error) => boolean | 1 | 2 | null;
261
262
interface RedisOptions {
263
reconnectOnError?: ReconnectOnError;
264
}
265
```
266
267
**Usage Examples:**
268
269
```typescript
270
const redis = new Redis({
271
reconnectOnError: (err) => {
272
const targetErrors = [
273
'READONLY',
274
'ECONNRESET',
275
'ETIMEDOUT'
276
];
277
278
// Reconnect for specific errors
279
return targetErrors.some(targetError =>
280
err.message.includes(targetErrors)
281
);
282
}
283
});
284
285
// Always reconnect on error (return 1 or 2)
286
const redis2 = new Redis({
287
reconnectOnError: () => 1 // 1 = reconnect, 2 = reconnect and resend
288
});
289
```
290
291
## Performance Configuration
292
293
### Auto Pipelining
294
295
Enable automatic command batching for improved performance.
296
297
```typescript { .api }
298
interface RedisOptions {
299
enableAutoPipelining?: boolean;
300
autoPipeliningIgnoredCommands?: string[];
301
}
302
```
303
304
**Usage Examples:**
305
306
```typescript
307
const redis = new Redis({
308
enableAutoPipelining: true,
309
310
// Commands that should not be auto-pipelined
311
autoPipeliningIgnoredCommands: [
312
'subscribe',
313
'psubscribe',
314
'monitor',
315
'ping'
316
]
317
});
318
319
// Check auto-pipeline queue size
320
console.log(`Queue size: ${redis.autoPipelineQueueSize}`);
321
```
322
323
### Command Timeouts
324
325
Configure timeouts for different operations.
326
327
```typescript { .api }
328
interface RedisOptions {
329
connectTimeout?: number; // Connection establishment timeout
330
commandTimeout?: number; // Individual command timeout
331
socketTimeout?: number; // Socket inactivity timeout
332
}
333
```
334
335
**Usage Examples:**
336
337
```typescript
338
const redis = new Redis({
339
connectTimeout: 5000, // 5 seconds to establish connection
340
commandTimeout: 2000, // 2 seconds per command
341
socketTimeout: 30000 // 30 seconds socket inactivity
342
});
343
```
344
345
## Custom Scripts
346
347
Define Lua scripts as custom Redis commands with proper typing support.
348
349
```typescript { .api }
350
interface RedisOptions {
351
scripts?: Record<string, ScriptDefinition>;
352
}
353
354
interface ScriptDefinition {
355
lua: string; // Lua script content
356
numberOfKeys?: number; // Number of Redis keys in script
357
readOnly?: boolean; // Script only reads data
358
}
359
```
360
361
**Usage Examples:**
362
363
```typescript
364
const redis = new Redis({
365
scripts: {
366
// Custom increment with limit script
367
incrementWithLimit: {
368
lua: `
369
local key = KEYS[1]
370
local limit = tonumber(ARGV[1])
371
local current = tonumber(redis.call('GET', key) or 0)
372
373
if current < limit then
374
return redis.call('INCR', key)
375
else
376
return current
377
end
378
`,
379
numberOfKeys: 1,
380
readOnly: false
381
},
382
383
// Read-only aggregation script
384
sumHash: {
385
lua: `
386
local key = KEYS[1]
387
local hash = redis.call('HGETALL', key)
388
local sum = 0
389
390
for i = 2, #hash, 2 do
391
sum = sum + tonumber(hash[i])
392
end
393
394
return sum
395
`,
396
numberOfKeys: 1,
397
readOnly: true
398
}
399
}
400
});
401
402
// Use custom scripts (TypeScript will provide typing)
403
const result = await redis.incrementWithLimit("counter", 100);
404
const sum = await redis.sumHash("stats");
405
```
406
407
## Types
408
409
```typescript { .api }
410
type Callback<T> = (err?: Error | null, result?: T) => void;
411
type ConnectorConstructor = new (options: any) => any;
412
413
interface StandaloneConnectionOptions {
414
host?: string;
415
port?: number;
416
path?: string;
417
}
418
419
interface CommonRedisOptions {
420
username?: string;
421
password?: string;
422
db?: number;
423
connectionName?: string;
424
readOnly?: boolean;
425
}
426
```