Kest

Search

Search the documentation

Fundamentals

Lazy-loading modules

Load a module after start-up, when it is first needed.

By default every module is loaded when the application starts. A rarely used part (an admin report, an import tool) can instead be loaded on demand, which keeps start-up fast and memory small.

@Injectable
class ReportController(private val loader: LazyModuleLoader, private val container: Container) {
 
    @Get("/reports/{id}")
    fun report(@Param id: String): String {
        loader.load(ReportsModule::class)                        // registers the module and its imports, runs their lifecycle hooks
        return container.get(ReportService::class).build(id)
    }
}

LazyModuleLoader.load(ReportsModule::class) (or container.load(...)) registers the module and its imports after start-up and runs their lifecycle hooks (onModuleInit...). Loading twice does nothing, so it is safe to call on every request.

Loading diagram…

What works, and what does not

WorksDoes not happen automatically
the module's providers become available and are createdHTTP routes of its controllers: routes are read when the server starts
lifecycle hooks runhandlers found at start-up: @OnEvent, @Cron, @MessagePattern, @Processor

So a lazily loaded module is for services and logic you call from code that exists already (as above), not for adding endpoints. A module that must serve routes or listen for events belongs in the normal imports.

Practical advice

  • Measure first. JVM start-up is rarely dominated by module loading; lazy loading mostly helps rarely used, heavy modules (big libraries, large caches).
  • Do not use it to hide missing imports: the build-time checks do not cover lazily loaded modules, so a wrong wiring shows up when the module is first loaded.

Read more