Nest
Nest

How can we solve memory leaks in dynamic modules with database providers?

March 18, 2026

Memory leaks in dynamic modules often arise when database connections or providers are repeatedly created without proper cleanup. To fix this, always close or release database clients during module shutdown and avoid creating multiple instances unnecessarily.

Implement the OnModuleDestroy or OnApplicationShutdown lifecycle hooks in your dynamic module services to clean up open connections or pooled resources. Also, cache or use singleton instances of your database providers to avoid redundant connections. This prevents memory from slowly creeping up as NestJS reloads or scales modules dynamically.

Code

@Injectable()
export class DatabaseService implements OnModuleDestroy {
  private client: PrismaClient;

  constructor() {
    this.client = new PrismaClient();
  }

  async onModuleDestroy() {
    await this.client.$disconnect(); // Close DB connection cleanly
  }
}

// Dynamic module setup (cache provider)
@Module({})
export class DatabaseModule {
  static forRoot(): DynamicModule {
    return {
      module: DatabaseModule,
      providers: [DatabaseService],
      exports: [DatabaseService],
    };
  }
}
      
Hire Now!

Need Help with Nest Development ?

Ready to leverage the power of conversational AI? Start your project with Zignuts expert AI developers.
bg-image
download-image
Company Deck
PDF, 3MB
© 2026 Zignuts Technolab. All Rights Reserved.
branch imagesbranch imagesbranch imagesbranch imagesbranch imagesbranch images