Redis connection pool exhausted: new client created per request in serverless
Problem
The application returns 'ECONNREFUSED' or 'max number of clients reached' errors under moderate load. The root cause is creating a new ioredis client inside each API route handler or Lambda function invocation. Each new client opens a fresh TCP connection to Redis. In serverless environments with high concurrency, dozens of connections are opened simultaneously, exhausting the Redis server's client limit.
Error Output
Error: connect ECONNREFUSED 127.0.0.1:6379
at new Redis (/var/task/node_modules/ioredis/built/redis/index.js)Unverified for your environment
Select your OS to check compatibility.
1 Fix
Create a Redis singleton and reuse it across all requests
Creating a new ioredis client per request or Lambda invocation opens a new TCP connection each time. In serverless environments with high concurrency, this exhausts the Redis server client limit rapidly.
Trust Score
5 verifications
- 1
Create a module-level singleton
In lib/redis.ts:
typescriptimport Redis from 'ioredis' // Module-level โ created once, reused across requests const redis = new Redis(process.env.REDIS_URL!, { maxRetriesPerRequest: 3, connectTimeout: 5000, lazyConnect: true, }) export default redis - 2
For Next.js, use the global guard to survive hot reload
Prevent multiple instances during hot reload in development:
typescriptconst globalForRedis = globalThis as unknown as { redis: Redis | undefined } export const redis = globalForRedis.redis ?? new Redis(process.env.REDIS_URL!) if (process.env.NODE_ENV !== 'production') globalForRedis.redis = redis - 3
Monitor connection count
Check current connections:
bashredis-cli INFO clients | grep connected_clients
Validation
Under load, redis INFO clients shows a stable connection count, not growing unboundedly.
Verification Summary
Sign in to verify this fix
Environment
- Product
- Redis (ioredis) + Serverless
- Environment
- production
Submitted by
Alex Chen
2450 rep