skip to content

In NestJS, should a boot-time cache warm-up go in onModuleInit or onApplicationBootstrap, and when do app.init() and app.listen() run them?

level: middleimportance: should knowfreq 45%

answer

  1. per module versus whole app
  2. all module inits finish first
  3. awaited before the port opens
  4. create() alone runs neither

basics

~10 s

Put it in onApplicationBootstrap when it needs other modules ready, because NestJS finishes every module's onModuleInit first. Both hooks run during app.init(), which app.listen() calls if needed, and are awaited before the port opens.

solid answer

~40 s

`onModuleInit()` runs module by module once a module's dependencies are resolved; `onApplicationBootstrap()` runs only after every module's `onModuleInit()` has completed, and still before the server listens. A warm-up that reads through another module's client, which may connect in its own `onModuleInit()`, is therefore safest in `onApplicationBootstrap()`. Both hooks are awaited, so a slow warm-up delays the port bind, and a rejected promise makes `app.init()` or `app.listen()` reject, so the app never starts serving. `NestFactory.create()` runs neither hook: `app.listen()` calls `app.init()` if it has not run, `app.init()` runs only once, and `NestFactory.createApplicationContext()` initializes for you. An e2e test that calls only `app.init()` gets both boot hooks without opening a port.

code

typescript · 6 lines
typescript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module.js';

const app = await NestFactory.create(AppModule); // no lifecycle hooks yet
await app.init(); // onModuleInit pass, then onApplicationBootstrap pass
await app.listen(process.env.PORT ?? 3000); // already initialized: only binds the port

go deeper

for a junior

Remember that onApplicationBootstrap comes after every module's onModuleInit has finished, and still before the server starts listening.

for a middle

Explain that create() only builds the app, init() runs both hook passes once, listen() initializes if needed, and that hooks are awaited and fail the boot on rejection.

for a senior

Show the boot-time trade-off: an awaited warm-up delays the port bind and blocks the start if it fails, so decide which warm-ups are mandatory.

for a principal

Set a team rule for boot work: what may block startup, what must degrade gracefully, and how long a boot may take before the platform gives up.

## The two boot hooks NestJS gives a class two places to run code while the application starts: - **`onModuleInit()`** is called once the **host module's** dependencies have been resolved. Nest walks the modules one at a time, and each module's `onModuleInit()` calls are awaited before the next module starts. - **`onApplicationBootstrap()`** is called once **all modules** have been initialized, but before the application listens for connections. Nest runs the `onApplicationBootstrap()` pass only after the whole `onModuleInit()` pass has finished. The interfaces are `OnModuleInit` and `OnApplicationBootstrap` from `@nestjs/common`. Neither method receives arguments. ## How a Nest application is initialized Building the application and initializing it are separate steps: 1. `NestFactory.create(AppModule)` scans the module graph and instantiates providers and controllers. No lifecycle hook runs yet. 2. `app.init()` registers the routes, runs the `onModuleInit()` pass, then the `onApplicationBootstrap()` pass, and logs `Nest application successfully started`. It runs only once; a second call returns immediately. 3. `app.listen(port)` calls `app.init()` if the application is not initialized yet, then binds the port. 4. `NestFactory.createApplicationContext(AppModule)` builds a standalone context with no HTTP server and initializes it before resolving, so the boot hooks have already run when you get it back. | Entry point | Runs boot hooks | Binds a port | |---|---|---| | `NestFactory.create()` | no | no | | `app.init()` | yes, once | no | | `app.listen()` | yes, if not yet initialized | yes | | `NestFactory.createApplicationContext()` | yes | no | This is why an end-to-end test that calls `app.init()` and then drives `app.getHttpServer()` still gets every boot hook: the hooks belong to initialization, not to listening. The same holds for a standalone context built with `createApplicationContext()` for a queue worker or a command-line script: there is no server, yet the boot hooks have run by the time the promise resolves, so a worker can rely on them exactly as an HTTP app does. Within each pass, Nest visits modules one at a time, starting with global modules and the most deeply imported ones and ending with the root module, and it awaits each module's hooks before moving on. A provider in the root module can therefore count on every other module's `onModuleInit()` having completed before its own runs. A provider in a feature module gets no such guarantee about modules at the same or a smaller distance, which is exactly the gap `onApplicationBootstrap()` closes: by then every module in the application has initialized. ## Choosing the hook for a cache warm-up Take a service that must fill an in-memory cache from a catalog client before it takes traffic. - If the warm-up only needs objects that are fully constructed, `onModuleInit()` works: by then the module's dependencies are injected. - If the warm-up depends on **another module having finished its own `onModuleInit()`**, for example a client that opens its connection in that hook, use `onApplicationBootstrap()`. Every module's `onModuleInit()` has completed by then. - Either way the warm-up finishes **before** `app.listen()` binds the port, so no request can arrive at a cold cache. ```typescript import { Injectable, OnApplicationBootstrap } from '@nestjs/common'; import { CatalogClient } from './catalog.client.js'; @Injectable() export class CatalogCache implements OnApplicationBootstrap { private readonly items = new Map<string, unknown>(); constructor(private readonly catalog: CatalogClient) {} async onApplicationBootstrap(): Promise<void> { for (const item of await this.catalog.listAll()) { this.items.set(item.id, item); } } } ``` ## Async, failure and timing - **Awaited**: returning a `Promise` or marking the method `async` defers initialization until it settles. A 20-second warm-up means a 20-second delay before the port is bound. - **Fail-fast**: if a boot hook throws or its promise rejects, `app.init()` rejects, so does `app.listen()`, and the server never binds. A standalone `createApplicationContext()` call rejects the same way. That is usually what you want for a warm-up that must succeed, and wrong for an optional one, which should catch its own errors. - **Readiness**: because boot hooks complete before the port opens, a port that answers already means the warm-up has finished; what to report to the platform during boot is a separate readiness-check subject. - **Not for request-scoped classes**: a request-scoped provider never receives either hook, so a warm-up placed there silently never runs. ## Mistakes interviewers listen for - Assuming `NestFactory.create()` runs `onModuleInit()`; nothing runs until initialization. - Putting a warm-up in `onApplicationBootstrap()` and believing the server is already listening. - Starting a warm-up without awaiting it, then wondering why the first requests miss the cache. - Letting an optional warm-up throw, which aborts the whole boot.

  • In a NestJS e2e test, why do boot hooks run even though the test never calls `app.listen()`?
    Because the boot hooks belong to initialization, not to listening. The test calls `app.init()`, which runs the `onModuleInit()` and `onApplicationBootstrap()` passes; the test client then talks to `app.getHttpServer()` without a bound port. Calling `app.close()` after the suite runs the shutdown hooks the same way.
  • What happens in NestJS if a boot hook rejects only in one environment, for example when an external catalog is unreachable?
    `app.init()` and `app.listen()` reject and the app never binds its port, so the process typically exits with the error. If the warm-up is optional, catch the error inside the hook and log it, so a degraded start is a decision you made rather than a crash.

  • NestFactory.create() runs onModuleInit as soon as the app object exists.
  • onApplicationBootstrap runs after app.listen() has bound the port.
  • Nest fires async boot hooks without waiting for them to settle.
  • A boot hook that throws is logged and the app starts anyway.
  • Calling app.init() before app.listen() runs the boot hooks twice.