After upgrading to NestJS 12, two dependent providers in one module run onModuleInit in a different order; how does Nest 12 order lifecycle hooks?
answer
- two axes: modules, then components
- distance from the root module
- hierarchy level from constructor deps
- same level runs concurrently
- shutdown walks it backwards
basics
~20 sNestJS 12 orders hooks by module, deepest and global modules first and the root last, then by hierarchy level inside each module, so a provider's onModuleInit runs after those it constructor-injects. Shutdown hooks walk the same order backwards.
solid answer
~40 sNest 12 orders hooks on two axes. Modules are sorted by distance from the root module: global modules and the most deeply imported go first, the root module last, and each module's hooks are awaited before the next module starts. Inside a module, which is what changed in 12, each component gets a **hierarchy level**: 1 with no dependencies, otherwise one more than its deepest constructor dependency. `onModuleInit()` and `onApplicationBootstrap()` run level by level upward, so a provider initializes after what it injects; hooks on one level run concurrently, and the module class's own hook runs last. Shutdown hooks visit modules in reverse and levels downward. Only constructor injection sets the level, so a property-injected or runtime-looked-up dependency gets no ordering guarantee.
code
typescript · 33 linesimport { Injectable, Module, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
@Injectable()
export class CacheClient implements OnModuleInit, OnModuleDestroy {
onModuleInit() { console.log('onModuleInit CacheClient'); }
onModuleDestroy() { console.log('onModuleDestroy CacheClient'); }
}
@Injectable()
export class BrokerClient implements OnModuleInit, OnModuleDestroy {
onModuleInit() { console.log('onModuleInit BrokerClient'); }
onModuleDestroy() { console.log('onModuleDestroy BrokerClient'); }
}
@Injectable()
export class CacheWarmer implements OnModuleInit, OnModuleDestroy {
constructor(private readonly cache: CacheClient) {}
onModuleInit() { console.log('onModuleInit CacheWarmer'); }
onModuleDestroy() { console.log('onModuleDestroy CacheWarmer'); }
}
@Injectable()
export class OrdersConsumer implements OnModuleInit, OnModuleDestroy {
constructor(
private readonly broker: BrokerClient,
private readonly warmer: CacheWarmer,
) {}
onModuleInit() { console.log('onModuleInit OrdersConsumer'); }
onModuleDestroy() { console.log('onModuleDestroy OrdersConsumer'); }
}
@Module({ providers: [OrdersConsumer, CacheWarmer, BrokerClient, CacheClient] })
export class AppModule {}go deeper
Remember that NestJS 12 initializes a provider after the providers its constructor injects, and shuts down in reverse.
Explain the two axes: module distance with global modules first and the root last, then hierarchy levels inside a module, ascending at boot and descending at shutdown.
Show what the level cannot see, property injection, runtime lookups and cross-module links, and how you would make a hidden ordering dependency explicit after the upgrade.
Treat hook order as an upgrade risk to audit: require dependencies between hooks to be constructor-visible so the framework, not luck, guarantees the order.
## What changed in NestJS 12 The NestJS 11 to 12 migration guide states it in one line: lifecycle hooks are now called by **component hierarchy level**. It warns that this can change the execution order of `onModuleInit`, `onApplicationBootstrap` and the shutdown hooks when providers or modules depend on one another, and asks teams to review any flow, test or teardown that relied on the old order. So a reordering after the upgrade is expected behaviour, not a bug. ## Axis one: modules by distance Before Nest looks inside a module, it decides which module goes first: - Every module has a **distance** from the root module in the import graph. The scanner computes it once all modules are known. - **Global modules** are given the maximum distance, so their hooks run first. - For the boot hooks, modules run from the largest distance to the smallest: the most deeply imported modules first, the **root module last**. - Each module's hooks are **awaited** before Nest moves to the next module. - The full `onModuleInit()` pass across all modules finishes before the `onApplicationBootstrap()` pass starts. - The shutdown hooks visit modules in the **reverse** order: the root module first. ## Axis two: hierarchy levels inside a module Within one module, Nest 12 groups the controllers, providers, enhancers and middleware classes by a number it records while instantiating them: 1. A component whose constructor injects nothing gets **level 1**. 2. Otherwise its level is **one more than the highest level** among its constructor dependencies. 3. For `onModuleInit()` and `onApplicationBootstrap()`, Nest walks the levels in **ascending** order, awaiting each level before the next. 4. For `onModuleDestroy()`, `beforeApplicationShutdown()` and `onApplicationShutdown()`, it walks them in **descending** order. 5. The **module class's own hook** runs after all the components of its module, in both directions. Take one module with four providers, registered in any order: | Provider | Constructor injects | Level | |---|---|---| | `CacheClient` | nothing | 1 | | `BrokerClient` | nothing | 1 | | `CacheWarmer` | `CacheClient` | 2 | | `OrdersConsumer` | `BrokerClient`, `CacheWarmer` | 3 | At boot, `CacheClient` and `BrokerClient` initialize first, then `CacheWarmer`, then `OrdersConsumer`. At shutdown, `OrdersConsumer` is destroyed first and the two clients last, so nothing is torn down while a component above it still holds it. ## Concurrency and failures - **Same level, concurrently**: the hooks of one level are started together and awaited as a group. Two level-1 providers have no order between them, and an async hook in one does not delay the start of the other. - **Boot failures fail the boot**: a rejected boot hook rejects initialization, and `app.listen()` never binds. - **Shutdown failures are logged**: a rejected shutdown hook is logged and the remaining hooks still run. - **Request-scoped classes are skipped**: they never receive lifecycle hooks, at any level. ## What the level cannot see The level is computed from **constructor parameters only**. Several real dependencies are invisible to it: - A dependency injected through a **property** with `@Inject()` does not raise the level. A property-injected client can still be mid-`onModuleInit()` when its consumer's hook starts. - A dependency fetched at runtime through the module reference or a factory is invisible too. - A dependency on a provider **from another module** is ordered by module distance, not by level, because each module is processed on its own. If one hook truly needs another provider's hook to have finished, inject it through the constructor, or move the dependent step to `onApplicationBootstrap()`, which runs only after every module's `onModuleInit()` has completed. ## Upgrading safely 1. Search for hooks that read state another provider prepares in its own hook. 2. Make those dependencies constructor parameters, so the level reflects them. 3. Re-run the tests that assert hook order, and update the expected order instead of pinning the old one. 4. Check teardown: shutdown now visits dependents before their dependencies inside a module. 5. Prefer `onApplicationBootstrap()` for cross-module work, such as a warm-up that reads through a client from another module, instead of reasoning about distances. The upside of the change is that the common case now works without thought: a provider that receives a client from its own module in its constructor can use that client's prepared state in its own `onModuleInit()`, and can still rely on the client being open in its own `onModuleDestroy()`.
- In NestJS 12, does a provider's `onModuleInit()` wait for a dependency injected with `@Inject()` on a property?No. The hierarchy level comes from constructor parameters only, so a property-injected dependency can sit on the same level or higher, and its async `onModuleInit()` may still be running when the consumer's hook starts. Inject it through the constructor, or do the dependent work in `onApplicationBootstrap()`.
- In NestJS 12, how is a global module ordered against the root module for the boot hooks?Global modules are given the maximum distance, so their hooks run before every other module's, and the root module, with the smallest distance, runs last. On shutdown the order reverses: the root module's components are torn down first and global modules last, which suits shared infrastructure that everything else uses.
- Nest 12 calls hooks in the order providers are listed in @Module.
- Hooks on the same hierarchy level run one after another in a fixed order.
- A property-injected dependency also raises the consumer's hierarchy level.
- Shutdown hooks use the same order as the boot hooks.
- The root module's onModuleInit runs first because it is loaded first.
Assumes NestJS 12: since 12.0 hooks are called by component hierarchy level, which can reorder hooks between dependent providers compared with NestJS 11.