Skip to content

Fix WebClient response cancellation race - #37205

Open
jonathansp wants to merge 1 commit into
spring-projects:mainfrom
jonathansp:fix/webclient-response-body-cancellation-leak
Open

Fix WebClient response cancellation race#37205
jonathansp wants to merge 1 commit into
spring-projects:mainfrom
jonathansp:fix/webclient-response-body-cancellation-leak

Conversation

@jonathansp

@jonathansp jonathansp commented Aug 27, 2026

Copy link
Copy Markdown

This fixes a race in WebClient when the exchange is cancelled exactly while the response is being delivered to the subscriber. In that window the connector already called releaseAfterCancel(...), so the response state becomes 2 (cancelled). If the caller then subscribes to the body as part of the same delivery, getBody() sees state 2 and throws:

java.lang.IllegalStateException: The client response body has been released already due to cancellation.

The connection is also not released, so the next request can not reuse it.

The fix delivers the response through Mono.create(clientResponse::deliver) and tracks a responseDeliveryInProgress flag. When cancellation happens during delivery, the body completes empty instead of throwing, and the connection is released. The old error stays for the real misuse case: subscribing to the body after delivery already finished.

Closes gh-37204

Keep track while the response is being delivered. When cancellation
happens during that call, allow WebClient to finish without subscribing
again to a body that Spring is already draining.

Keep the existing error when code subscribes to the body after response
delivery is complete.

Closes spring-projectsgh-37204

Signed-off-by: Jonathan Prates <jonathan.prates@transferwise.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: waiting-for-triage An issue we've not yet triaged or decided on

Projects

None yet

Development

Successfully merging this pull request may close these issues.

WebClient throws IllegalStateException on response body when cancelled during response delivery

2 participants