Redis Connection Management, Security, and Performance Troubleshooting

Manage Node.js Redis connections, restrict access, and troubleshoot performance using common metrics.

🎯 Introduction

By the end of this article, you will be able to configure connection retries and restricted accounts for long-running services, and investigate Redis latency through connections, commands, and memory.

This article uses Node.js 22.9.0, redis 5.9.0, and Redis 7.4.2. The introduction covered establishing a connection; here we add reconnection, authentication, and diagnostic settings for long-running services.


🧱 Reusing Node.js Client Connections and Reconnecting

Connection reuse lets multiple operations share an established client connection, reducing connection setup overhead. Reconnection attempts to establish communication again after a disconnect. It restores communication, not necessarily previously failed operations.

Use cases: long-running Node.js services should reuse clients for ordinary reads and writes. Use dedicated connections for tasks with connection-specific state, such as subscriptions, blocking reads, and WATCH.

Create managed-redis.mjs and define a bounded reconnection strategy:

managed-redis.mjs
import { createClient } from 'redis';

function reconnectStrategy(retries) {
    if (retries >= 5) return false;
    return Math.min(100 * 2 ** retries, 3000) + Math.floor(Math.random() * 100);
}

The wait grows between retries, with a small random delay to avoid synchronized retries across instances. After five retries, it stops. Alert and restart or recover according to deployment policy; do not assume it will recover automatically afterward.

Create a reusable client:

managed-redis.mjs
export const managedRedis = createClient({
    url: process.env.REDIS_URL ?? 'redis://127.0.0.1:6379',
    username: process.env.REDIS_USERNAME,
    password: process.env.REDIS_PASSWORD,
    disableOfflineQueue: true,
    commandsQueueMaxLength: 1000,
    socket: { connectTimeout: 1000, reconnectStrategy },
});
managedRedis.on('error', error => console.error('Redis client error:', error.message));

disableOfflineQueue and connectTimeout retain the introductory settings. commandsQueueMaxLength adds a bound on pending commands; 1000 is only an example. Commands may still wait before a connection is recognized as disconnected. Reuse the deadline approach from the cache protection article to handle this.

Use a separate script, managed-check.mjs, to check whether this configuration can connect:

managed-check.mjs
import { managedRedis } from './managed-redis.mjs';

try {
    await managedRedis.connect();
    console.log('Redis connection established');
} catch (error) {
    console.error('Cannot connect to Redis:', error.message);
    process.exitCode = 1;
} finally {
    if (managedRedis.isOpen) managedRedis.destroy();
}
node --env-file=.env managed-check.mjs && echo 'Ready for subsequent operations'

On success, the script prints the connection message and the shell executes the next command. When retries are exhausted, the script exits with a nonzero code and the next command does not run. This checks connection configuration; it does not continuously monitor a running service.

Close the shared client when the service exits. Handle failures at each command call rather than relying only on client connection state.


🔐 Redis Authentication and ACL Permissions

Authentication verifies a client's identity. An ACL, or access control list, specifies which commands an account can execute and which keys it can access. Permission rules separate application reads and writes from administrative capabilities.

Use cases: give a read-only program access only to its required prefix, preventing accidental writes or deletion of another module's data. Application accounts should not inherit full administrator privileges.

On the local practice Redis instance only, create course_reader with read access to course:cache:*. Set a random COURSE_READER_PASSWORD in the local .env, then create acl-admin.mjs and run it once using a connection with ACL administration privileges:

acl-admin.mjs
import { redis } from './redis.mjs';

const password = process.env.COURSE_READER_PASSWORD;
if (!password || password.length < 32) throw new Error('Configure a random password for the practice account');
await redis.connect();

Set permissions:

acl-admin.mjs
console.log(await redis.sendCommand([
    'ACL', 'SETUSER', 'course_reader', 'reset', 'on', `>${password}`,
    '~course:cache:*', '+get', '+ping',
]));
await redis.close();

The output is OK. reset clears the practice account's old rules, on enables it, > sets its password, ~ restricts keys, and +get and +ping grant only those two commands.

node --env-file=.env acl-admin.mjs

This is runtime configuration. In production, persist rules through a controlled ACL file or service platform so they survive restarts. Do not reset an account currently used by a service. See Redis ACL.


🧰 Environment Variables and Connection Configuration

To test the restricted account, set REDIS_USERNAME to course_reader and REDIS_PASSWORD to its password in .env, keeping the local instance address. Do not put passwords in example source code or print complete connection URLs.

Create acl-check.mjs, reusing the production client configuration above:

acl-check.mjs
import { managedRedis } from './managed-redis.mjs';

await managedRedis.connect();
console.log(await managedRedis.get('course:cache:user:v1:1'));

Returning cached text or null confirms read access to this prefix. A write attempt is rejected:

acl-check.mjs
try {
    await managedRedis.set('course:cache:user:v1:1', 'blocked');
} catch (error) {
    console.log(error.message);
} finally {
    await managedRedis.close();
}

Running it should produce an error containing NOPERM:

node --env-file=.env acl-check.mjs

For remote connections, use rediss:// to enable TLS transport encryption as required by the provider, and validate certificates. Passwords do not replace network isolation; restrict which sources can access the instance.


🛠 INFO, SLOWLOG, and Large Keys

The memory management article used INFO to inspect capacity. This section adds hit metrics and command diagnostics. SLOWLOG records commands whose execution time reaches a configured threshold. A large key has an unusually large value or number of elements, which can increase read, transfer, and processing costs.

Use cases: when queries slow down, inspect metrics for overall changes, locate commands with the slow log, and check the sizes of related keys. These provide clues; no single observation establishes the cause. Such diagnostics usually require separate operational permissions.

Create diagnostics.mjs using the local administrative connection. First, read cache hit and miss counts:

diagnostics.mjs
import { redis } from './redis.mjs';

await redis.connect();
const stats = await redis.info('stats');
const names = ['keyspace_hits:', 'keyspace_misses:'];
console.log(stats.split('\r\n').filter(line => names.some(name => line.startsWith(name))).join('\n'));

keyspace_hits counts successful key lookups; keyspace_misses counts lookups where no key was found. Compare their increments over the same interval to observe the hit ratio. These metrics do not distinguish individual application features.

Read the five most recent slow log entries:

diagnostics.mjs
console.log(await redis.sendCommand(['SLOWLOG', 'GET', '5']));

The result is empty if no commands met the threshold. Execution durations are in microseconds and do not include all network transfer and client wait time. If an endpoint is slow but the slow log is empty, also inspect the network, connection queues, and application processing.

Finally, inspect memory usage for a known cache key:

diagnostics.mjs
console.log(await redis.memoryUsage('course:cache:user:v1:1'));
await redis.close();

This returns an estimated byte count, or null if the key is missing. For collections, also use commands such as LLEN, HLEN, and SCARD to inspect element counts. Do not retrieve an entire large collection just to diagnose it.

node diagnostics.mjs

Run this directly for the local unauthenticated exercise. Elsewhere, use a diagnostic connection supplied by the administrator. Slow logs may contain application arguments; do not expose their full output to ordinary users. See SLOWLOG GET for execution-time fields.


💡 Common Performance Issues and Diagnostics

SymptomCheck firstTypical response
Lower hit rate and more database readsTTLs, key format, eviction incrementsCheck write and invalidation rules; assess capacity
Some commands take much longerSLOWLOG, collection sizes, script lengthBound scans and results; split large values
Fast server commands but slow endpointsNetwork round trips, connection count, application queuesReuse connections, use bounded batches, limit concurrency
Writes report insufficient memoryMemory limits and eviction candidatesRemove unused data; adjust capacity and policy
Frequent reconnectionsNetwork, accounts, server restarts, resource limitsIdentify the cause before tuning retries

Retest under the same request conditions after making changes. Simply increasing connections, timeouts, or retry counts can turn a brief problem into longer queues.


❓ Questions and Answers

Q1: Is a new client per request safer?

Ordinary reads and writes usually do not need it. Frequent handshakes add connection and resource overhead. Reserve dedicated connections for special tasks.

Q2: If an ACL allows GET, can the account read every key?

Key-pattern rules also apply. This account can read only course:cache:*; other prefixes are still rejected.

Q3: Does an empty SLOWLOG prove the Redis request path is healthy?

No. It covers only server-side command execution meeting the threshold. Network delays, connection waits, and application processing can still be slow.


🧪 Exercise

Use the read-only account to read a key under the allowed prefix and one under another prefix, and compare the results. In the practice environment, run the connection check against an unreachable Redis address and observe how failure is reported when retries are exhausted.

// Write your code here

🎉 You now know the basics of connection reuse, permission checks, and Redis troubleshooting!