All posts

Fix MemoryError in NestJS in Production

Resolve memory errors in production NestJS applications from circular dependencies, large payload processing, and WebSocket accumulation.

NestJS Memory Errors in Production

NestJS apps can grow in memory due to dependency injection container overhead, circular references, and improper stream handling. Here's how to tackle each.

Circular Dependencies

NestJS's DI container can create reference cycles that prevent garbage collection:

// PROBLEM: circular dependency
@Injectable()
export class OrderService {
  constructor(private userService: UserService) {}
}

@Injectable()
export class UserService {
  constructor(private orderService: OrderService) {} // Circular!
}

// FIX: use forwardRef
@Injectable()
export class UserService {
  constructor(
    @Inject(forwardRef(() => OrderService))
    private orderService: OrderService
  ) {}
}

Large Payload Processing

// BAD — buffers entire body
@Post('upload')
async upload(@Body() body: Buffer) {
  // 500MB buffer in memory
}

// GOOD — use streams with Multer
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
async upload(@UploadedFile() file: Express.Multer.File) {
  // file.path points to disk, not memory
}

Configure Multer to use disk storage:

MulterModule.register({
  storage: diskStorage({
    destination: '/tmp/uploads',
  }),
  limits: { fileSize: 50 * 1024 * 1024 }, // 50MB max
}),

Node.js Heap Limit

CMD ["node", "--max-old-space-size=512", "dist/main.js"]

Pair this with container memory limits set 20-30% higher to account for native memory.

Bugsly's Node.js integration captures heap statistics alongside exceptions, showing you the memory state at the moment of failure.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free