Square CloudSquare Cloud

Redis: ECONNRESET, Socket closed unexpectedly and connection timeouts

These errors mean the connection to Redis dropped or didn't answer in time. Common causes are idle connections closed by the server, redis:// instead of rediss:// and too many clients; the fix is one client per process, with reconnection and PING.

Updated 6 min read

Learning objectives

After reading this article you will be able to:

  • Read node-redis, ioredis and redis-py error messages and know which layer each one points to
  • Diagnose idle timeouts, TLS, client limits and slow commands with redis-cli
  • Configure reconnection, periodic PING and timeouts with each client's current API
On this page

Your bot works all morning and, after a quiet stretch, the logs show Socket closed unexpectedly. Or your API boots, runs fine for hours and then spits out ECONNRESET and a few timeouts. With Redis, these errors rarely mean the server is down. Almost always the connection was closed, cut halfway, or never finished its handshake.

There are only a few causes, and each one leaves a signature: when the error shows up, the URL scheme and how many clients are connected. This guide shows how to read each message and how to configure node-redis, ioredis and redis-py so a dropped connection becomes a log line instead of an outage.

What do these errors look like?#

In node-redis, errors arrive through the client's error event:

text
Error: Socket closed unexpectedly
Error: read ECONNRESET
Error: Connection timeout

In ioredis, an error with no listener becomes a console warning, and pending commands fail after several attempts:

text
[ioredis] Unhandled error event: Error: read ECONNRESET
[ioredis] Unhandled error event: Error: connect ETIMEDOUT
MaxRetriesPerRequestError: Reached the max retries per request limit (which is 20). Refer to "maxRetriesPerRequest" option for details.

In redis-py, they are exceptions from redis.exceptions:

text
redis.exceptions.ConnectionError: Connection closed by server.
redis.exceptions.ConnectionError: Error 104 while writing to socket. Connection reset by peer.
redis.exceptions.TimeoutError: Timeout connecting to server

And from the server itself, in any client:

text
ERR max number of clients reached

What does each error mean?#

Each message points to a different layer, and knowing which one saves half the diagnosis:

Message What happened Most likely cause
Socket closed unexpectedly, Connection closed by server. The other side closed the connection cleanly Idle timeout, server restarting, wrong TLS scheme
ECONNRESET, Connection reset by peer The connection was cut with a TCP reset A proxy, NAT or firewall dropped it; a write to an already closed connection
Connection timeout, connect ETIMEDOUT, Timeout connecting to server No answer within the connect deadline Wrong host or port, firewall, stalled TLS handshake
Timeout reading from ..., slow commands Connected, but the reply took too long Server busy with a heavy command, saturated network
ERR max number of clients reached The server refused the new connection Too many clients, usually one per request

If the error is ECONNREFUSED, nothing is listening on that host and port: see ECONNREFUSED on a database.

What are the most common causes?#

From most to least frequent:

  1. Idle connection closed by the server. The Redis timeout directive closes clients that go N seconds without sending a command. The default is 0 (off), but a hosted server may use a fixed value. The tell is regularity: the error shows up after every silence, never in the middle of traffic. Network gear (NAT, load balancers) does the same to idle TCP connections, and then the symptom is usually ECONNRESET on the first command after the pause.
  2. Wrong scheme: redis:// against a server that requires TLS. The client sends plain text, the server expects a TLS handshake and closes the connection. The result is a loop of Socket closed unexpectedly or ECONNRESET, one per reconnection attempt. The reverse, rediss:// on a port without TLS, fails the handshake with an OpenSSL error such as wrong version number. If the scheme is right but the CA is missing, you get a certificate error instead: see self signed certificate in certificate chain.
  3. Too many clients. Creating a client inside every request, or on every bot message, opens connections until maxclients. The Redis default is 10,000, but a hosted server may accept far fewer.
  4. Slow commands blocking the server. Redis runs one command at a time. A KEYS * on a large database, or an LRANGE over a huge list, holds up every other client until they time out. The KEYS documentation says not to use it in application code; use SCAN.
  5. The server restarted. Maintenance, a deploy or running out of memory drops every connection at once. A well-configured client reconnects on its own within seconds.

How do you diagnose the cause?#

Start with redis-cli, outside your code, using the same URL and certificate:

bash
redis-cli --tls --cacert ca.pem -u "$REDIS_URL" PING

If it answers PONG, network, TLS and password are fine. If the same call with redis:// and no --tls drops at once, the server requires TLS and your app needs rediss://.

Once connected, these commands show the rest (on a hosted server, some may be blocked):

text
CONFIG GET timeout      # idle seconds before closing (0 = never)
CONFIG GET maxclients   # client limit
INFO clients            # connected_clients: how many are connected now
CLIENT LIST             # one client per line, with idle= and name=
SLOWLOG GET 10          # the slowest recently executed commands

Compare connected_clients with the number of app processes. If each process should open one connection and you see hundreds, something leaks. Name your clients (name in node-redis, connectionName in ioredis, client_name in redis-py) to tell them apart in CLIENT LIST.

Finally, look at the timestamps. An error always a few minutes after silence is the idle timeout; an error on every attempt since startup is TLS or the address; an error under load is the client limit or a slow command.

How do you fix it in node-redis, ioredis and redis-py?#

The rules apply to all three: one client per process, created at startup and shared; an error listener; rediss:// with the CA; reconnection with growing delays; and a periodic PING shorter than the idle timeout. TCP keepalive helps with NAT and firewalls, but it doesn't reset Redis's idle counter, because it isn't a command.

node-redis#

js
import { readFileSync } from "node:fs";
import { createClient } from "redis";

const redis = createClient({
  url: process.env.REDIS_URL, // rediss://user:password@host:port
  name: "api",
  pingInterval: 60_000, // one PING a minute keeps the connection active
  socket: {
    tls: true,
    ca: readFileSync(process.env.REDIS_CA_PATH, "utf8"),
    connectTimeout: 10_000,
    reconnectStrategy: (retries) => Math.min(retries * 200, 5_000),
  },
});

// without an "error" listener, the first network error kills the process
redis.on("error", (err) => console.error("Redis:", err.message));
redis.on("reconnecting", () => console.log("Redis: reconnecting"));

await redis.connect();
await redis.setEx("health", 60, "ok");
console.log(await redis.get("health"));

The error listener is mandatory: the node-redis docs warn that without one, the error is thrown and the Node.js process exits. With it, the client logs the drop and reconnects following reconnectStrategy.

ioredis#

js
import { readFileSync } from "node:fs";
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL, {
  tls: { ca: readFileSync(process.env.REDIS_CA_PATH, "utf8") },
  connectionName: "api",
  connectTimeout: 10_000,
  keepAlive: 30_000,
  maxRetriesPerRequest: 3,
  retryStrategy: (times) => Math.min(times * 200, 5_000),
});

redis.on("error", (err) => console.error("Redis:", err.message));

// ioredis doesn't PING on its own; one a minute avoids the idle close
setInterval(() => redis.ping().catch(() => {}), 60_000);

await redis.set("health", "ok", "EX", 60);
console.log(await redis.get("health"));

maxRetriesPerRequest sets how many reconnections a command waits through before failing with MaxRetriesPerRequestError. For BullMQ queues, its docs ask for null on Worker connections; see how to run background jobs.

redis-py#

python
import os

import redis
from redis.backoff import ExponentialBackoff
from redis.retry import Retry

r = redis.from_url(
    os.environ["REDIS_URL"],  # rediss://user:password@host:port
    ssl_ca_certs=os.environ["REDIS_CA_PATH"],
    client_name="api",
    socket_connect_timeout=10,
    socket_timeout=5,
    socket_keepalive=True,
    health_check_interval=60,  # PING before reusing a connection idle for over 60 s
    retry=Retry(ExponentialBackoff(cap=5, base=0.2), 3),
)

r.set("health", "ok", ex=60)
print(r.get("health"))

health_check_interval makes redis-py send a PING before reusing a connection that has been idle longer than the interval. If it was closed, the failure shows up in that PING and Retry reconnects before your command runs.

How do you keep it from coming back?#

  • Create the client once, in a shared module, never inside a handler.
  • Count connections: processes × clients per process, plus Pub/Sub connections and the ones queue libraries open on their own. Add up every app that uses the same Redis. It is the same reasoning as too many connections on SQL databases.
  • Replace KEYS with SCAN and avoid reading huge structures in one go.
  • Log reconnections. One per pause is expected noise; dozens a minute point to TLS, the address or the limit.
  • Give cache keys a TTL, so memory doesn't grow without a ceiling. The trade-offs of Redis as a cache versus a database are in Redis as a cache or a database, and the engine basics in what is Redis.

How to do this on Square Cloud#

On Square Cloud's Redis hosting, available from the Standard plan, you don't have to discover the idle timeout: idle clients are disconnected after 5 minutes. Set a pingInterval or health_check_interval well below that, like the one-minute value in the examples, and keep automatic reconnection on.

The connection requires TLS. The URL uses rediss://, and the client must trust the CA of the certificate you download from the dashboard: socket.ca in node-redis, tls.ca in ioredis, ssl_ca_certs in redis-py. Each database accepts up to 256 connections, with no pooler in front, so use one client per process and add up the connections of every app that points at the same Redis.

The database sits in the same datacenter as your apps, with about 1 ms of average latency, and it also accepts connections from outside: run redis-cli on your machine with the same URL and certificate to tell a network problem from a code problem. It has persistence, supports PUBLISH/SUBSCRIBE and offers a single logical database.

See limits and plans on the Redis hosting page.

Database hosting

MongoDB, PostgreSQL, MySQL and Redis next to your app

Redis hosting

FAQs

Why does Redis disconnect after a few idle minutes?

Because the server has an idle timeout: the timeout directive closes clients that send no commands for N seconds. Redis defaults to 0 (off), but a hosted server may use a fixed value. A periodic PING shorter than that window keeps the connection alive.

Does TCP keepalive prevent the Redis idle timeout?

No. Keepalive sends TCP control packets that keep firewalls and NAT aware of the connection, but they aren't commands. To Redis, the client is still idle. Only a command, such as PING, resets that counter.

Do I need a connection pool for Redis?

Usually not. node-redis and ioredis queue commands on a single connection, and one per process is enough. Extra connections are only for Pub/Sub, blocking commands such as BLPOP, or queue libraries that open their own.

What does ERR max number of clients reached mean?

The server hit its connected-client limit (maxclients) and refused the new connection. Almost always the code creates a new client on every request or never closes the old ones.

Next articleWhat is a database index and when to create oneAn index is a sorted structure, usually a B-tree, that finds rows without a full table read. When to add one, composite indexes and EXPLAIN in Postgres and MySQL.

More in Databases

See all 32 articles