Video in progress

Strong Middle 🧩 Microservices

After the service sits idle for a while, the first requests fail with `Connection reset` or `NoHttpResponseException`. What is the cause and how do you fix it?

Most often an intermediate load balancer, NAT or the server itself has silently closed the pooled keep-alive connection after its idle timeout, while the client still thinks it is alive and reuses it. The fix: make the client's idle time shorter than the ones in between, evict idle connections, and add a single retry for idempotent requests.

📖 Answer

The chain: order-service → AWS ALB / nginx / NAT → payment-service. The device in the middle closes a connection that has been idle for 60 seconds. The client pool keeps the connection for 5 minutes. At night there was no traffic for 2 minutes, the first request writes to a dead connection and gets Connection reset by peer, or NoHttpResponseException in Apache HttpClient. If you retry, it works, so this looks like a "random" error.

The same thing happens on the server side: if Tomcat's keep-alive timeout (server.tomcat.keep-alive-timeout) is shorter than the client's, the server closes the connection, and the client manages to send a request on it at that exact moment.

The rule: the client must close the connection before everything in between does.

var http = HttpClients.custom()
        .setConnectionManager(pool)
        .evictIdleConnections(TimeValue.ofSeconds(20))   // a connection idle for 20 s is closed
        .evictExpiredConnections()
        .build();

In Apache HttpClient 5 there is also ConnectionConfig.custom().setValidateAfterInactivity(TimeValue.ofSeconds(5)), which checks a connection that sat idle for a long time before using it. For Reactor Netty (WebClient) it is ConnectionProvider.builder("payments").maxIdleTime(Duration.ofSeconds(20)).

Extra protection: for idempotent requests (GET), one quick retry on a connection error. Be careful with POST: you can't know whether the request reached the server.

For diagnosis, compare the error times with the traffic graph: they come right after a quiet period. The DEBUG log of HttpClient shows when a connection was opened and when it was reused.