0
0
NestJSframework~8 mins

Global modules in NestJS - Performance & Optimization

Choose your learning style9 modes available
Performance: Global modules
MEDIUM IMPACT
Global modules affect the initial load time and memory usage by making services available app-wide without repeated imports.
Sharing a service across multiple modules in a NestJS app
NestJS
import { Global, Module } from '@nestjs/common';

@Global()
@Module({
  providers: [SharedService],
  exports: [SharedService],
})
export class SharedModule {}

@Module({
  imports: [SharedModule],
})
export class AppModule {}
Declaring a module as global makes its providers available app-wide without repeated imports, reducing bundle size and initialization overhead.
📈 Performance GainSingle service instantiation and smaller initial bundle, improving startup speed.
Sharing a service across multiple modules in a NestJS app
NestJS
import { ModuleA } from './module-a';
import { ModuleB } from './module-b';
@Module({
  imports: [ModuleA, ModuleB],
})
export class AppModule {}
Repeatedly importing the same service in multiple modules causes redundant initialization and larger bundle size.
📉 Performance CostIncreases initial bundle size and triggers multiple service instantiations, blocking startup longer.
Performance Comparison
PatternModule ImportsService InstantiationsBundle Size ImpactVerdict
Repeated imports of shared servicesMultipleMultipleLarger[X] Bad
Global module with shared servicesSingle global importSingleSmaller[OK] Good
Rendering Pipeline
Global modules affect the server-side initialization phase before rendering, impacting how fast the app can start and serve content.
Module Initialization
Dependency Injection
Server Response Preparation
⚠️ BottleneckModule Initialization due to repeated imports and service instantiations
Core Web Vital Affected
LCP
Global modules affect the initial load time and memory usage by making services available app-wide without repeated imports.
Optimization Tips
1Use @Global decorator to share services app-wide without repeated imports.
2Avoid making too many services global to prevent large bundle sizes and memory overhead.
3Monitor server startup time to detect performance issues from module initialization.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using a global module in NestJS?
AIt reduces repeated service instantiations across modules
BIt automatically caches HTTP responses
CIt decreases client-side rendering time
DIt eliminates the need for dependency injection
DevTools: Network and Performance panels
How to check: Use Network panel to check initial bundle size and Performance panel to measure server response time and initialization duration.
What to look for: Look for smaller bundle sizes and shorter startup times when using global modules.