Fundamentals
Lifecycle events
Run code when the application starts and stops.
An application has a life: it starts (providers are created), runs, and stops (connections must close, work must finish). A lifecycle hook is a method the container calls at a moment you choose. You opt in by implementing an interface:
| Hook | Called | Typical use |
|---|---|---|
OnModuleInit | after the module's providers are built | warm a cache, validate configuration |
OnApplicationBootstrap | after every module has initialised | start background work that needs everything ready |
OnModuleDestroy | when shutdown begins | stop accepting new work |
BeforeApplicationShutdown(signal) | after destroy hooks, before listeners close | wait for in-flight work |
OnApplicationShutdown(signal) | last | release resources: close pools, flush buffers |
OnInit and OnShutdown are shorter variants with no module distinction.
@Injectable
class CacheWarmer(private val products: ProductRepository, private val cache: CacheService) : OnApplicationBootstrap, OnApplicationShutdown {
private val log = Logger("CacheWarmer")
override fun onApplicationBootstrap() {
log.log("warming caches")
products.popular().forEach { cache.put("product:${it.id}", it) }
}
override fun onApplicationShutdown(signal: String?) = log.log("bye ($signal)")
}Shutdown runs in reverse creation order: what was created last (usually the things that depend on others) is stopped first, so a service never loses its dependency while it still works.
Graceful shutdown
Kest.run registers a JVM shutdown hook: when the process gets SIGTERM (what Kubernetes and docker stop send), the container closes and the hooks above run with signal = "SIGTERM". The web server stops accepting new connections and lets running requests finish. Do your final work in BeforeApplicationShutdown and OnApplicationShutdown. Keep it short: the orchestrator kills the process after a grace period (30 s by default in Kubernetes).
In tests, module.close() (or container.close()) runs the same hooks.
Good practice
- Keep hooks fast and safe. A hook that throws stops start-up: fine for "database unreachable", not for optional work.
- Start threads and schedulers in
OnApplicationBootstrap, stop them inOnModuleDestroy, so nothing runs against half-started parts. - Do not rely on hook order between providers; rely on dependencies (a provider is created after what it needs).
- For slow essential setup before the first request see Asynchronous providers.