Memory leaks in Node.js applications cause gradual memory growth until containers crash or restart. Heap snapshots provide detailed dumps of JavaScript memory at specific moments, revealing which objects consume memory and why they aren't garbage collected. The article demonstrates capturing snapshots using Node.js V8 API, triggering them on app start, via SIGUSR2 signals, and automatically during OOM events. Analysis involves comparing multiple snapshots in Chrome DevTools to identify growing objects, examining retained sizes, and tracing retainer chains to find root causes. Common leak patterns include lingering timers, unremoved event listeners, unclosed RxJS subscriptions, and closures retaining large objects. The solution includes storing snapshots securely in S3 with encryption and automatic expiry, enabling systematic debugging of production memory issues.

12m read timeFrom blogs.halodoc.io
Post cover image
Table of contents
The Problem: Gradual Memory GrowthWhat Is a Heap Snapshot?How to Take Heap Snapshots in Node.jsStep-by-Step: Analyzing Heap SnapshotsExample: Closure Leak in SSRCommon Memory Leak PatternsBest PracticesSummary: Your Memory Debugging ChecklistConclusion🔗 ReferencesJoin usAbout Halodoc

Sort: