How to fix JedisConnectionException: Broken pipe in Redis

RedisINTERMEDIATEHIGHUpdated Dec 29, 2025· 285 views

This error occurs when the Jedis Java client loses connection to Redis, usually due to idle timeout, network issues, or stale connection pool entries. The server closes the connection, but the client attempts to use it anyway.

Quick fix

Fixes JedisConnectionException: Broken pipe

JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setTestOnBorrow(true);    // Validate when borrowing from pool
poolConfig.setTestOnReturn(true);    // Validate when returning to pool
poolConfig.setTestWhileIdle(true);   // Validate idle connections
poolConfig.setMinEvictableIdleTimeMillis(300000); // Remove connections idle > 5 min
poolConfig.setTimeBetweenEvictionRunsMillis(30000); // Check every 30 seconds

JedisPool pool = new JedisPool(poolConfig, "localhost", 6379);
  1. Enable connection pool validation
  2. Set appropriate timeout values
  3. Configure Redis server timeout appropriately
  4. Implement proper connection usage pattern
redis — error
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setTestOnBorrow(true); // Validate when borrowing from pool
poolConfig.setTestOnReturn(true); // Validate when returning to pool
poolConfig.setTestWhileIdle(true); // Validate idle connections
poolConfig.setMinEvictableIdleTimeMillis(300000); // Remove connections idle > 5 min
poolConfig.setTimeBetweenEvictionRunsMillis(30000); // Check every 30 seconds
JedisPool pool = new JedisPool(poolConfig, "localhost", 6379);
JedisConnectionException: Broken pipe

What this error means

A "broken pipe" error indicates that the TCP connection between your Java application and Redis server has been terminated unexpectedly. When you try to read from or write to a closed connection, the operating system throws this error because the pipe (communication channel) is no longer valid. This typically happens in two scenarios: 1. **Server-side closure**: Redis closes an idle connection after the configured timeout period, but your client tries to reuse it. 2. **Network disruption**: The connection is interrupted by network issues, firewall rules, or server shutdown, but the client's connection pool still holds a stale reference. The Jedis library (Java Redis client) manages connections through a connection pool, and broken pipe errors indicate that a pooled connection is no longer usable.

Typical symptoms

  • Java application crashes with JedisConnectionException
  • Intermittent Redis operations fail after periods of inactivity
  • Connection errors increase under low traffic conditions
  • Stack trace mentions 'Broken pipe' or 'Socket closed'
  • Errors occur after the application has been running for several hours

Common causes

  1. Redis server closes idle connections due to timeout configuration (default 300 seconds or 5 minutes)
  2. Connection pool reuses connections that were closed by the server without validating them first
  3. Socket timeout is set too low, causing premature connection closure
  4. Network issues or firewall rules silently close connections
  5. Redis server restarts or maintenance events close client connections
  6. Connection pool is undersized, leading to connection starvation and reuse of stale connections

How to fix "JedisConnectionException: Broken pipe"

1Enable connection pool validation

Configure Jedis to validate connections before reusing them from the pool. This ensures stale connections are detected and discarded:

java
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setTestOnBorrow(true);    // Validate when borrowing from pool
poolConfig.setTestOnReturn(true);    // Validate when returning to pool
poolConfig.setTestWhileIdle(true);   // Validate idle connections
poolConfig.setMinEvictableIdleTimeMillis(300000); // Remove connections idle > 5 min
poolConfig.setTimeBetweenEvictionRunsMillis(30000); // Check every 30 seconds

JedisPool pool = new JedisPool(poolConfig, "localhost", 6379);

This prevents reuse of connections that Redis has already closed.

2Set appropriate timeout values

Configure connection and socket timeouts to balance responsiveness with reliability:

java
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxWaitMillis(3000); // Wait max 3 seconds for available connection

// Connection timeout and socket timeout in milliseconds
int timeout = 5000; // 5 seconds - must be less than Redis server timeout
JedisPool pool = new JedisPool(poolConfig, "localhost", 6379, timeout);

Ensure your timeout is significantly less than Redis's timeout setting to prevent server-side closure while operations are pending.

3Configure Redis server timeout appropriately

Check your Redis server configuration and adjust the idle connection timeout:

bash
# Connect to Redis and check current timeout
redis-cli CONFIG GET timeout
# Output: 1) "timeout"
#         2) "0"  (0 means disabled - connections never close due to idle)

If you see a timeout value (typically 300 seconds), consider:
- Setting timeout 0 to disable server-side timeout (if you have validation enabled)
- Or increasing it to a larger value if you prefer server-side cleanup
- Ensure your Jedis pool validation detects closed connections

bash
# In redis.conf or via CLI (persistent requires redis.conf update)
CONFIG SET timeout 0
4Implement proper connection usage pattern

Always use try-with-resources or explicit resource cleanup:

java
// Best practice: try-with-resources
try (Jedis jedis = pool.getResource()) {
    String value = jedis.get("key");
    jedis.set("key", "value");
} // Connection automatically returned to pool

// Alternative: explicit close
Jedis jedis = pool.getResource();
try {
    jedis.set("key", "value");
} finally {
    jedis.close(); // Returns connection to pool
}

Never hold connections beyond their use scope, as this prevents timely reuse and increases likelihood of timeout.

5Add retry logic with exponential backoff

Implement resilience for transient connection failures:

java
public static <T> T executeWithRetry(Supplier<T> operation) {
    int maxRetries = 3;
    long delayMs = 100;

    for (int attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            return operation.get();
        } catch (JedisConnectionException e) {
            if (attempt == maxRetries) {
                throw e;
            }
            try {
                Thread.sleep(delayMs);
                delayMs *= 2; // Exponential backoff
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(ie);
            }
        }
    }
    throw new RuntimeException("Max retries exceeded");
}

// Usage
String value = executeWithRetry(() -> jedis.get("key"));
6Upgrade Jedis and monitor pool metrics

Keep Jedis up to date and monitor pool health:

xml
<!-- Update to latest stable version in pom.xml -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>5.1.0</version>
</dependency>

Monitor connection pool metrics to catch issues early:

java
if (pool instanceof JedisPool) {
    int active = pool.getNumActive();
    int idle = pool.getNumIdle();
    System.out.println("Active: " + active + ", Idle: " + idle);
}

High idle counts with frequent broken pipe errors suggest your timeout is too aggressive.

Advanced notes

Connection Pool Eviction: Jedis uses Apache Commons Pool2, which can evict idle connections. The minEvictableIdleTimeMillis and timeBetweenEvictionRunsMillis settings control this behavior. Set these to values less than your Redis server timeout to proactively clean up stale connections before they cause errors.

keepalive vs timeout: Redis's tcp-keepalive setting (default 300 seconds) keeps TCP connections alive at the OS level, while timeout closes idle connections at the Redis application level. These work independently—keepalive prevents TCP-level disconnection, but doesn't prevent Redis from closing the connection.

Cluster Mode: If using Redis Cluster with Jedis, ensure all nodes have consistent timeout configurations and that your client's pool settings account for node-level failures.

Monitoring: Use Redis CLIENT LIST to see active connections and their idle times:

bash
redis-cli CLIENT LIST
# Look for 'idle' column—if close to your timeout, broken pipe errors will follow

Frequently asked questions

What does "JedisConnectionException: Broken pipe" mean?
A "broken pipe" error indicates that the TCP connection between your Java application and Redis server has been terminated unexpectedly. When you try to read from or write to a closed connection, the operating system throws this error because the pipe (communication channel) is no longer valid. This typically happens in two scenarios: 1.
How do I fix "JedisConnectionException: Broken pipe"?
This error occurs when the Jedis Java client loses connection to Redis, usually due to idle timeout, network issues, or stale connection pool entries. The server closes the connection, but the client attempts to use it anyway.
What causes "JedisConnectionException: Broken pipe"?
Redis server closes idle connections due to timeout configuration (default 300 seconds or 5 minutes) Connection pool reuses connections that were closed by the server without validating them first Socket timeout is set too low, causing premature connection closure
Is the "JedisConnectionException: Broken pipe" error serious?
Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.

Official resources & further reading