In a Spring WebFlux application, request processing is reactive, meaning that when a client cancels a request (e.g., due to a timeout or manual cancellation), Spring immediately stops execution by propagating a cancel signal in the reactive stream.
However, in some cases, we want to ensure that processing continues, even if the client disconnects. This is especially important when:
- Database updates or external API calls must be completed to avoid an inconsistent state.
- Long-running operations should not be interrupted.
- Logging, auditing, or side effects must still be processed.
How to Keep Processing After a Cancel Signal
To decouple HTTP request processing from the application logic, we can use the .cache()
operator. This ensures that the execution continues, even if the client drops the connection.
Understanding .cache()
in Reactor
The .cache()
operator buffers elements emitted by the source Flux
or Mono
, allowing re-subscription without re-executing the original operation.
Source cannot be cancelled, so by applying .cache()
, we can ensure that our logic continues even if the subscriber (HTTP client) disconnects.
Spring WebFlux Example
Explanation of the Code:
performLongRunningTask(taskId)
simulates a time-consuming operation..cache()
ensures that the operation continues even if the client cancels the request.subscribeOn(Schedulers.boundedElastic())
moves blocking work to an appropriate thread pool.
Final Thoughts
By using .cache()
, we effectively decouple the HTTP request lifecycle from our business logic, ensuring that processing continues in the background even if the client disconnects.
Comments
Post a Comment