HttpRequestLifecycle
A plugin that manages the HTTP request lifecycle, particularly handling client disconnections.
The HttpRequestLifecycle plugin allows you to detect and respond to client connection closures during request processing. When configured with HttpRequestLifecycleConfig.cancelCallOnClose set to true, the plugin will automatically cancel the request handling coroutine if the client disconnects, preventing unnecessary processing and freeing up resources.
Remember, when the coroutine context is canceled, the next suspension point will throw CancellationException, but until that moment it doesn't stop any blocking operations, so call call.coroutineContext.ensureActive if needed. Plugin only works for CIO and Netty engines. Other implementations fail on closed connection only when trying to write some response.
This is particularly useful for:
Long-running requests where the client may disconnect before completion
Streaming responses where detecting disconnection allows early cleanup
Resource-intensive operations that should be canceled when the client is no longer waiting
Example
install(HttpRequestLifecycle) {
cancelCallOnClose = true
}
routing {
get("/long-process") {
try {
// Long-running operation
repeat(100) {
// throws an exception if the client disconnects during processing
call.coroutineContext.ensureActive()
// Process more data...
logger.info("Very important work.")
}
call.respond("Completed")
} catch (e: CancellationException) {
// Handle client disconnected, clean up resources
}
}
}