Kest

Search

Search the documentation

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:

HookCalledTypical use
OnModuleInitafter the module's providers are builtwarm a cache, validate configuration
OnApplicationBootstrapafter every module has initialisedstart background work that needs everything ready
OnModuleDestroywhen shutdown beginsstop accepting new work
BeforeApplicationShutdown(signal)after destroy hooks, before listeners closewait for in-flight work
OnApplicationShutdown(signal)lastrelease 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)")
}
Loading diagram…

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 in OnModuleDestroy, 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.

Read more