Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
40 prioritized NestJS best practices across architecture, DI, security, performance, testing, and microservices.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/perf-lazy-loading.md
1---2title: Use Lazy Loading for Large Modules3impact: MEDIUM4impactDescription: Improves startup time for large applications5tags: performance, lazy-loading, modules, optimization6---78## Use Lazy Loading for Large Modules910NestJS supports lazy-loading modules, which defers initialization until first use. This is valuable for large applications where some features are rarely used, serverless deployments where cold start time matters, or when certain modules have heavy initialization costs.1112**Incorrect (loading everything eagerly):**1314```typescript15// Load everything eagerly in a large app16@Module({17imports: [18UsersModule,19OrdersModule,20PaymentsModule,21ReportsModule, // Heavy, rarely used22AnalyticsModule, // Heavy, rarely used23AdminModule, // Only admins use this24LegacyModule, // Migration module, rarely used25BulkImportModule, // Used once a month26],27})28export class AppModule {}2930// All modules initialize at startup, even if never used31// Slow cold starts in serverless32// Memory wasted on unused modules33```3435**Correct (lazy load rarely-used modules):**3637```typescript38// Use LazyModuleLoader for optional modules39import { LazyModuleLoader } from '@nestjs/core';4041@Injectable()42export class ReportsService {43constructor(private lazyModuleLoader: LazyModuleLoader) {}4445async generateReport(type: string): Promise<Report> {46// Load module only when needed47const { ReportsModule } = await import('./reports/reports.module');48const moduleRef = await this.lazyModuleLoader.load(() => ReportsModule);4950const reportsService = moduleRef.get(ReportsGeneratorService);51return reportsService.generate(type);52}53}5455// Lazy load admin features with caching56@Injectable()57export class AdminService {58private adminModule: ModuleRef | null = null;5960constructor(private lazyModuleLoader: LazyModuleLoader) {}6162private async getAdminModule(): Promise<ModuleRef> {63if (!this.adminModule) {64const { AdminModule } = await import('./admin/admin.module');65this.adminModule = await this.lazyModuleLoader.load(() => AdminModule);66}67return this.adminModule;68}6970async runAdminTask(task: string): Promise<void> {71const moduleRef = await this.getAdminModule();72const taskRunner = moduleRef.get(AdminTaskRunner);73await taskRunner.run(task);74}75}7677// Reusable lazy loader service78@Injectable()79export class ModuleLoaderService {80private loadedModules = new Map<string, ModuleRef>();8182constructor(private lazyModuleLoader: LazyModuleLoader) {}8384async load<T>(85key: string,86importFn: () => Promise<{ default: Type<T> } | Type<T>>,87): Promise<ModuleRef> {88if (!this.loadedModules.has(key)) {89const module = await importFn();90const moduleType = 'default' in module ? module.default : module;91const moduleRef = await this.lazyModuleLoader.load(() => moduleType);92this.loadedModules.set(key, moduleRef);93}94return this.loadedModules.get(key)!;95}96}9798// Preload modules in background after startup99@Injectable()100export class ModulePreloader implements OnApplicationBootstrap {101constructor(private lazyModuleLoader: LazyModuleLoader) {}102103async onApplicationBootstrap(): Promise<void> {104setTimeout(async () => {105await this.preloadModule(() => import('./reports/reports.module'));106}, 5000); // 5 seconds after startup107}108109private async preloadModule(importFn: () => Promise<any>): Promise<void> {110try {111const module = await importFn();112const moduleType = module.default || Object.values(module)[0];113await this.lazyModuleLoader.load(() => moduleType);114} catch (error) {115console.warn('Failed to preload module', error);116}117}118}119```120121Reference: [NestJS Lazy Loading Modules](https://docs.nestjs.com/fundamentals/lazy-loading-modules)122