Ktor 3.4.0 Help

HTTP request lifecycle

By default, Ktor continues processing a request even if the client disconnects. The HttpRequestLifecycle plugin allows you to cancel request processing as soon as the client disconnects.

This is useful for long-running or resource-intensive requests that should stop executing when the client is no longer waiting for a response.

Install and configure HttpRequestLifecycle

To enable the HttpRequestLifecycle plugin, install it in your application module using the install function and set the cancelCallOnClose property:

import io.ktor.server.application.* import io.ktor.server.http.HttpRequestLifecycle fun Application.module() { install(HttpRequestLifecycle) { cancelCallOnClose = true } }

When the cancelCallOnClose property is enabled, the HttpRequestLifecycle plugin installs a cancellation handler per request. When a client disconnects, only the coroutine handling that specific route is canceled.

Cancellation propagates through structured concurrency, so any child coroutines started from the request coroutine (for example, using launch or async) are also canceled. A CancellationException is thrown at the next suspension point.

Handling cancellation

You can catch CancellationException to perform cleanup operations, such as releasing resources or stopping background work:

fun Application.module() { install(HttpRequestLifecycle) { cancelCallOnClose = true } routing { get("/long-process") { try { while (isActive) { delay(10_000) log.info("Very important work.") } call.respond("Completed") } catch (e: CancellationException) { log.info("Cleaning up resources.") } } } }

Limitations

This plugin is only fully supported on CIO and Netty engines. Engines based on servlets (or other unsupported engines) cannot detect client disconnects reliably. Cancellation can only be detected when the server attempts to write a response.

19 December 2025