FG
๐Ÿ—„๏ธ DatabasesAmazonproduction

Redis connection pool exhausted: new client created per request in serverless

Fresh2 months ago
Mar 14, 20260 views
Confidence Score71%
71%

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

Canonical Fix
High Confidence Fix
69% confidence88% success rate5 verificationsLast verified Mar 14, 2026

Create a Redis singleton and reuse it across all requests

Medium Risk

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.

69

Trust Score

5 verifications

88% success
  1. 1

    Create a module-level singleton

    In lib/redis.ts:

    typescript
    import 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. 2

    For Next.js, use the global guard to survive hot reload

    Prevent multiple instances during hot reload in development:

    typescript
    const 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. 3

    Monitor connection count

    Check current connections:

    bash
    redis-cli INFO clients | grep connected_clients

Validation

Under load, redis INFO clients shows a stable connection count, not growing unboundedly.

Verification Summary

Worked: 5
Partial: 2
Failed: 1
Last verified Mar 14, 2026

Sign in to verify this fix

Environment

Product
Redis (ioredis) + Serverless
Environment
production

Submitted by

AC

Alex Chen

2450 rep

Tags

redisioredisconnection-poolserverlesssingleton