Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A WebClient-based service logs 'PrematureCloseException: Connection prematurely closed BEFORE response' intermittently. What is a likely cause and how do you address it?

A likely cause is a stale pooled connection: the server or a load balancer closed a keep-alive connection after it had been idle for a while, and the client picked it from its pool and sent a request on it just as, or after, it was being closed. We fix it by setting the Reactor Netty ConnectionProvider's maxIdleTime below the idle timeout of the server and every proxy in between, adding maxLifeTime and background eviction, retrying idempotent requests once on this error, and checking gateways for their own idle timeouts and connection limits.

Why this question is asked

PrematureCloseException is one of those errors that appears a few times an hour, never in tests and never when we are looking. It is intermittent because it depends on timing: a connection sits idle in the pool for just long enough that the other side gives up on it. Interviewers ask about it because diagnosing it requires understanding connection pooling and keep-alive across several hops, which many engineers have never had to think about. In this answer, we will recap keep-alive and pooling, walk through the race that produces the error, configure the connection pool correctly, add a safe retry, and look at the proxies and gateways in between.

1A Quick Recap of Keep-Alive and Connection Pools

Opening a TCP connection, and for HTTPS a TLS session, takes several network round trips. To avoid paying that on every request, HTTP/1.1 keeps connections open after a response, called keep-alive, and clients keep these open connections in a pool. WebClient uses Reactor Netty, whose ConnectionProvider manages that pool: when a request starts, it takes an idle connection from the pool if there is one; when the response is complete, it returns the connection.

Both ends may close an idle connection whenever they like. Servers and load balancers do this to save resources, typically after 20 to 75 seconds of idleness, and a common cloud load balancer default is 60 seconds. By default, Reactor Netty's pool has no maximum idle time, so it keeps idle connections until the other side closes them.

2The Race That Produces the Error

Now picture a connection that served a request and has been idle in our pool for 59.9 seconds. The load balancer's idle timer fires at 60 seconds and it closes the connection. At the same moment, our client takes that connection from the pool, because from its point of view it is still open, and writes a new request. The close notification, a TCP FIN, arrives after the request was written but before any response. Reactor Netty reports exactly that: the connection was closed prematurely, before the response.

Step throughA stale pooled connection meets an idle timeout
WebClient poolLoad balancerServer
request 1 on connection C
forward request 1
response 1; C goes back to the pool idle
C idle for 60 s: close it
request 2 written on C at 59.9 s
FIN: connection closed, no response
PrematureCloseException BEFORE response

7 messages in order. Play them, or step through them one at a time.

Neither side did anything wrong; the client reused a connection the other side had just decided to close.

3Confirming the Diagnosis

A few signs point to this cause. The errors are intermittent and mostly happen after quiet periods, such as at night or on a low-traffic endpoint, because those are the times connections sit idle long enough. They happen in the first request on a reused connection, not in the middle of streaming a body. And the time since the connection was last used is close to a round number like 60 seconds.

Reactor Netty can log connection lifecycle events at debug level, and its pool exposes metrics such as idle and active connections when metrics are enabled on the provider. Comparing the idle time of failing connections with the idle timeouts configured on the load balancer and the server usually confirms the match. If the errors instead happen on requests that take a long time to answer, the more likely cause is a proxy read timeout cutting slow responses, which is a different fix.

4Fix 1: Expire Idle Connections Before the Other Side Does

The main fix is to make our pool close idle connections first. If every component in the path closes idle connections after 60 seconds or more, we set maxIdleTime to something clearly lower, for example 30 seconds. Then the client never reuses a connection that the other side might be closing.

Java
ConnectionProvider provider = ConnectionProvider.builder("downstream-pool")
.maxConnections(100)
.maxIdleTime(Duration.ofSeconds(30)) // below the 60 s load balancer idle timeout
.maxLifeTime(Duration.ofMinutes(5)) // recycle long-lived connections too
.pendingAcquireTimeout(Duration.ofSeconds(2)) // bounded wait for a free connection
.evictInBackground(Duration.ofSeconds(30)) // close expired idle connections proactively
.build();
HttpClient http = HttpClient.create(provider)
.responseTimeout(Duration.ofSeconds(5));
WebClient client = WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(http))
.baseUrl("https://inventory.internal")
.build();

Each setting has a reason. maxIdleTime is the direct fix. maxLifeTime closes connections after a fixed age even when busy, which also helps when the server limits connection age or when DNS changes should be picked up. evictInBackground runs a periodic check that closes expired connections in the pool, instead of only checking when a connection is taken, which keeps the pool clean during quiet periods. In Spring Boot, we can apply the same provider through a customizer of the auto-configured WebClient.Builder so all clients share it.

5Fix 2: Retry Idempotent Requests Once

Even with the right idle time, a connection can still be closed at an unlucky moment, for example when a server restarts during a deploy. For idempotent requests, such as GET or a PUT that sets a value, retrying once on this specific error is safe, because the server never sent a response and repeating the request has the same effect. WebClient wraps the Netty exception, so we look at the cause.

Java
Mono<Stock> stock = client.get().uri("/stock/{sku}", sku)
.retrieve()
.bodyToMono(Stock.class)
.retryWhen(Retry.max(1)
.filter(e -> e instanceof WebClientRequestException
&& e.getCause() instanceof PrematureCloseException));
// first attempt: stale connection -> PrematureCloseException
// retry: fresh connection -> Stock[sku=A-17, available=12]

We do not retry a POST that creates an order this way, because the request may have reached the server and been processed before the connection closed. For non-idempotent calls, the safe options are an idempotency key that lets the server recognise the repeat, or surfacing the error.

6Fix 3: Check the Proxies and Gateways in Between

The path from client to server often has several hops: a sidecar proxy, an API gateway, a cloud load balancer, the server's own keep-alive settings. Each has its own idle timeout, and the shortest one wins. If a gateway closes idle upstream connections after 15 seconds, our 30-second maxIdleTime is still too long. So we list every hop, find the smallest idle timeout, and set the client below it.

Connection limits matter too. A proxy that allows only a certain number of connections per client may close the oldest ones when the limit is reached, producing the same error under load rather than after idle periods. And on the server side, a keep-alive limit on the number of requests per connection closes connections after, say, 100 requests; maxLifeTime and the retry handle that case as well.

Idle timeouts along one path (example values)
HopCloses idle connections afterImplication
WebClient pool (default)NeverReuses connections others closed
Sidecar proxyConfigured per meshCheck its setting
Cloud load balancer60 s by defaultClient must expire sooner
Server keep-aliveOften 20 to 75 sShortest hop wins
WebClient pool (fixed)30 s maxIdleTimeClient closes first, no race

7Follow-up questions

Why does this happen with WebClient and not with my old RestTemplate?

It can happen with any pooled client. Apache HttpClient has the same issue and offers similar settings, such as evicting idle connections and validating connections after inactivity. Services that used SimpleClientHttpRequestFactory with little pooling hit it less often, but they paid for a new connection on most requests.

Would HTTP/2 avoid the problem?

HTTP/2 multiplexes many requests over one connection and has its own way of announcing that a connection is closing, so the race is less frequent, but idle timeouts and connection closes still happen. The pool settings and a safe retry are still worth having.

8Conclusion

In this answer, we saw that an intermittent PrematureCloseException BEFORE response usually means the client reused a pooled keep-alive connection that the server or a load balancer had just closed for being idle. Because Reactor Netty keeps idle connections indefinitely by default, we set the ConnectionProvider's maxIdleTime below the shortest idle timeout on the path, add maxLifeTime and background eviction, retry idempotent requests once on this error, and check proxies and gateways for their own idle timeouts and connection limits.

What to say in the interviewAbout 80 seconds aloud

Open with

The most likely cause is a stale pooled connection. WebClient uses Reactor Netty, which keeps keep-alive connections in a pool, and by default it has no maximum idle time.

Then, if they want more

Meanwhile the server or a load balancer closes idle connections, say after 60 seconds, which is a common load balancer default.

If our client takes a connection that has been idle for almost exactly that long and writes a request just as the other side closes it, the close arrives before any response, and Reactor Netty reports Connection prematurely closed BEFORE response. That fits the pattern: intermittent, mostly after quiet periods, never in tests.

To fix it, I configure a ConnectionProvider with maxIdleTime clearly below the shortest idle timeout on the path, for example 30 seconds, plus maxLifeTime so connections are recycled, and evictInBackground so expired connections are cleaned out proactively, and plug it into WebClient through ReactorClientHttpConnector.

Then I add a single retry for idempotent requests, filtering on a WebClientRequestException caused by PrematureCloseException, but not for non-idempotent POSTs unless there is an idempotency key. And I check every hop, sidecar, gateway, load balancer and the server's keep-alive settings, because the shortest idle timeout wins, and a proxy's connection limits can cause the same error under load.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A WebClient-based service logs 'PrematureCloseException: Connection prematurely closed...": https://scrivio-interview-library.netlify.app/spring-boot/http-clients/e24d4c268f/