https://kotlinlang.org logo
#ktor
Title
# ktor
h

Helio

06/21/2022, 11:31 AM
Hello again, 👋🏽 I was doing a bit of research regarding the best approach to Gracefully Shutdown a Ktor server (Netty Engine - more specifically). Looking through the documentation, I thought that the recommended way would be through Application Monitoring Events (e.g getting SIGTERM signals). However, during my tests, I noticed that
onStopping, onPrepareStop and onStopped
ApplicationEvents are not triggered for Netty Engine? Is that expected? If so, do you have any suggestion to properly handle those Graceful Shutdowns? Thanks once again for your help.
a

Aleksei Tirman [JB]

06/21/2022, 12:13 PM
I cannot reproduce your problem:
Copy code
val server = embeddedServer(Netty, port = 3333) {
   environment.monitor.subscribe(ApplicationStopping) {
       println("Stopping")
   }

    environment.monitor.subscribe(ApplicationStopped) {
        println("Stopped")
    }

    environment.monitor.subscribe(ApplicationStopPreparing) {
        println("Preparing")
    }
}

server.start(wait = false)
server.stop()
h

Helio

06/21/2022, 12:24 PM
Did you try terminating the application with
kill -15 PID
? I'm afraid it won't print
This is how I was testing.
Copy code
fun main() {
    startKoin { modules(httpClientModule, serviceModule, useCaseModule, redisModule) }
    embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}

fun Application.module() {
    environment.monitor.subscribe(ApplicationStarting) { print("Starting") }
    environment.monitor.subscribe(ApplicationStarted) { print("Started") }
    environment.monitor.subscribe(ApplicationStopping) { print("Stopping") }
    environment.monitor.subscribe(ApplicationStopped)  { print("Stopped") }
    environment.monitor.subscribe(ApplicationStopPreparing)  { print("Preparing") }
}
Even the SIGINT signal sent by IntelliJ is not caught.
a

Andreas Scheja

06/21/2022, 2:42 PM
I believe you will have to add a shutdown hook in which you stop the server
Copy code
val server = embeddedServer(Netty, port = 8080) {
  ...
}
Runtime.getRuntime().addShutdownHook(
    thread(start = false) {
        server.stop()
    }
)
server.start(wait = true)
a

Aleksei Tirman [JB]

06/21/2022, 3:05 PM
Or you can use the
addShutdownHook
method:
Copy code
server.addShutdownHook {
    server.stop()
}
h

Helio

06/21/2022, 10:53 PM
Ohhh, I see! This is what I was missing I guess. Thanks for your help guys. 😃