Ktor server handler cleanup on client disconnect across engines
0 reputation · 07 May 2024, 22:33 UTC
I am designing a Ktor server with routes that may remain active for extended periods, such as streaming or long-polling endpoints, and I need to ensure that server-side work stops and resources are released when a client disconnects before the response completes. My uncertainty is whether Ktor provides a uniform contract across its server engines for cancelling the ApplicationCall coroutine on connection close, or whether this behavior is engine-specific and must be verified per deployment.
Because Ktor treats coroutine cancellation as cooperative, I expect suspending calls to react to cancellation, but I am unsure whether blocking operations inside a route are interrupted by any built-in mechanism. I also need to account for possible differences between Ktor 2.x and 3.x, and I do not want to rely on assumptions about Netty, Jetty, CIO, or the test engine without confirming current documented behavior.
Which Ktor server engines cancel the handler coroutine automatically on client disconnect, and which require explicit active-state checks? Does the HttpTimeout plugin interrupt blocking code inside a route, or is it effective only for suspending calls? What is the recommended way to verify cancellation semantics for a specific engine and Ktor version before production?