What is the Node.js memory model and how does garbage collection work?
Answer
Node.js memory is divided into several regions. The V8 heap stores JavaScript objects and is where most memory management occurs. The heap has two main areas: New Space (Young Generation) — small (1-8MB), short-lived objects; collected frequently by the fast Scavenge algorithm (minor GC). Objects that survive multiple collections are promoted to Old Space (Old Generation) — larger, longer-lived objects; collected less frequently by the Mark-Sweep-Compact algorithm (major GC). Large Object Space — objects exceeding 256KB; never moved by GC. Code Space — JIT-compiled code. Memory outside the V8 heap includes Buffer allocations (C++ layer) and native bindings. Garbage collection pauses JavaScript execution (stop-the-world). V8 uses incremental marking and concurrent sweeping to minimize pause times. Monitor memory: process.memoryUsage() returns heapTotal, heapUsed, rss, external. Common leaks: forgotten event listeners, closures holding references, unbounded caches, circular references in pre-modern V8. Use Chrome DevTools heap snapshots or clinic.js to diagnose leaks.
Previous
How does Node.js handle concurrency without multiple threads?
Next
What are memory leaks in Node.js and how do you detect them?
More Node.js Questions
View all →- Advanced How does Node.js handle concurrency without multiple threads?
- Advanced What are memory leaks in Node.js and how do you detect them?
- Advanced What is the difference between process.exit() and throwing an uncaught exception?
- Advanced What is the N+1 query problem and how do you solve it in Node.js?
- Advanced What is circuit breaking pattern in Node.js microservices?