Backend
Backend Essentials
Heap Memory

Heap Memory

While the Stack handles fast, static primitive variables and function calls, the Heap Memory is the powerhouse behind complex data structures. In backend engineering, understanding the Heap is crucial for preventing memory leaks and optimizing Garbage Collection (GC) pauses in high-traffic applications.

What is the Heap Used For?

Unlike the rigid LIFO structure of the Stack, the Heap is a massive, unorganized pool of memory designed for one primary purpose:

  1. Dynamic Memory Allocation: When you write code, you often don't know exactly how much memory a variable will need until the program is actually running (e.g., fetching 10,000 records from a database).
  2. Objects: Any complex Object in Node.js/JavaScript is stored in the Heap.
  3. Arrays and Functions: Arrays and Functions are technically just Objects under the hood in JavaScript, so they also live in the Heap.

Characteristics of the Heap

  • Large but Slower: Because the Heap is unorganized, finding and allocating a free block of memory takes slightly longer than the Stack. However, it can hold vastly more data.
  • Dynamic Size: The Heap can grow and shrink during runtime as your application demands more memory.
  • Garbage Collected: In languages like C++, you must manually delete objects from the Heap. In Node.js, the V8 Engine uses a Garbage Collector that periodically scans the Heap and automatically deletes objects that are no longer being used.

Code Example: How the Heap Works

Consider the following Node.js code:

function createUser() {
   const user = {
      name: "Pratap"
   };
   return user;
}
 
const activeUser = createUser();

What happens in memory?

  1. You call createUser(). The function call goes onto the Stack.
  2. The JavaScript engine sees { name: "Pratap" }. Because this is an Object, it dynamically allocates space for it inside the Heap Memory.
  3. It then creates the user constant. This constant is placed on the Stack, but instead of holding the data itself, it holds a Memory Reference (Pointer) to the exact location of the object in the Heap.
  4. When the function finishes, the Stack frame is destroyed, but the object { name: "Pratap" } remains safely in the Heap because activeUser is still pointing to it.

[!WARNING] Memory Leaks: If you accidentally store millions of objects in a global array and never clear it, the Garbage Collector cannot delete them. Your Heap will grow infinitely until the OS runs out of RAM, resulting in an OOM (Out of Memory) crash. This is the #1 cause of Node.js server crashes in production.