java.net.SocketException: Connection reset
ID: java/socketexception-connection-reset
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 17 | active | — | — | — |
Root Cause
SocketException: Connection reset occurs when the remote peer abruptly closes the TCP connection by sending a RST packet. This can happen due to server crashes, load balancer timeouts, firewall killing idle connections, or the server rejecting the request.
genericWorkarounds
-
82% success Implement retry logic with exponential backoff and connection validation
1. Implement retry with exponential backoff: wait 1s, 2s, 4s between retries, with a maximum of 3-5 retries. 2. Use a circuit breaker pattern (Resilience4j, Failsafe) to stop retrying when failure rate is high. 3. Before retrying, validate the connection from the pool is still alive: use connection.isValid() or configure testOnBorrow in the connection pool. 4. For HTTP: use a library with built-in retry support (Spring WebClient with Reactor Retry, Apache HttpClient with ServiceUnavailableRetryStrategy).
-
80% success Configure connection pool keep-alive and validation to prevent stale connections
1. For HikariCP: set connectionTimeout, idleTimeout, and maxLifetime to values shorter than the load balancer/firewall idle timeout. 2. Enable connection validation: spring.datasource.hikari.connection-test-query=SELECT 1 or spring.datasource.hikari.validation-timeout=5000. 3. For HTTP connection pools (Apache HttpClient): set evictIdleConnections(30, TimeUnit.SECONDS). 4. Check if a load balancer or NAT gateway has an idle timeout shorter than your keep-alive interval.
Dead Ends
Common approaches that don't work:
-
Immediately retrying the request without any backoff or investigation
60% fail
If the connection reset is due to a server-side issue (crash, overload, deployment), immediate retry will likely hit the same problem or exacerbate server load. Without exponential backoff, rapid retries can cause cascading failures and make recovery harder.
-
Increasing socket timeout values to prevent the connection from being reset
80% fail
Connection reset is an active signal from the remote end — it is not a timeout. The RST packet arrives regardless of your timeout settings. Increasing timeouts helps with read timeouts (no response) but not with connection resets (explicit rejection).