Skip to main contentSkip to main content
~/profileLIVE
Asad Saeed
Asad SaeedOpen to WorkSenior Software Engineer | Full Stack Developer
01

Identity

Residence
Lahore, Punjab
Nationality
Pakistani
City
Lahore
Age
26
02

Languages

  • English96%
  • Urdu100%
03

Expertise

React.js95%
Next.js95%
JavaScript / TypeScript95%
HTML5, CSS395%
Tailwind, Bootstrap, Shadcn UI95%
Material UI, SCSS, Styled Components90%
Redux Toolkit, React Query, Zustand92%
REST & GraphQL APIs92%
Git, GitHub, Bitbucket98%
Node.js, Express.js, NestJS85%
MongoDB, PostgreSQL, Prisma80%
WebSockets, Real-Time Systems82%
AI & Automation (n8n, OpenAI)78%
04

Stack

4949 technologies
ReactJSNextJSJavaScriptTypeScriptReact NativeNestJSNode.jsExpress.jsMongoDBPostgreSQLMySQLPrisma ORMFirebaseREST APIGraphQL APIApollo ClientWebSockets / Socket.ioReduxRedux ToolkitReact QueryZustandTailwind CSSShadcn UIMaterial UIBootstrapSCSSCSSModule.cssStyled ComponentsFramer MotionStripe Payment Integrationn8nOpenAI APIAWS LambdaDockerVercelNetlifyGitHub Actions (CI/CD)JestGitGitHubBitbucketPostmanSwaggerJira SoftwareStrapiSanityFigmaAdobe XD
05

Contact

Email
asadsaeed.dev@gmail.com
Phone
+92 3017631644·+92 478730644
Download Resume
HomeSkillsBackgroundPortfolioContact
Chat with Asad
All Posts
Why Node.js Servers Run Out of Memory: Debugging Memory Leaks and OOM Crashes

Why Node.js Servers Run Out of Memory: Debugging Memory Leaks and OOM Crashes

NODE.JSJAVASCRIPTSYSTEM DESIGNBACKEND DEVELOPMENTASAD SAEED
November 18, 202614 min readBy Asad Saeed

Learn why Node.js servers run out of memory, how to debug memory leaks with heap snapshots, and how to prevent production OOM crashes using streams, Redis, workers, Docker, and monitoring.

Introduction

Imagine deploying a Node.js application that works perfectly during development.

Initially, the server uses 200 MB of memory. After a few hours, memory usage increases to 500 MB. Later, it reaches 1 GB, then 2 GB. Eventually, the application becomes unresponsive or crashes completely.

Requests start failing. Background jobs stop processing. Users experience timeouts. In some environments, the operating system or container runtime terminates the process because it exceeds its memory limit.

This is a common production problem in Node.js applications.

The important thing to understand is that increasing memory usage does not always mean your application has a memory leak. It could be caused by large requests, unbounded caches, inefficient queries, excessive concurrency, external memory allocation, or simply a workload that requires more resources.

In this article, we'll explore:

  • How Node.js manages memory.

  • Why production applications run out of memory.

  • How to identify memory leaks.

  • How to inspect heap snapshots and memory usage.

  • How to fix common memory problems.

  • How to design a more reliable production architecture.

Let's understand this from a practical MERN Stack perspective.

1. Understanding How Node.js Manages Memory

Node.js runs JavaScript using the V8 JavaScript engine.

V8 manages JavaScript memory through a garbage collector. It allocates memory for objects, arrays, strings, functions, closures, and other JavaScript values.

At a high level, Node.js memory includes several important areas.

Heap Memory

The V8 heap stores JavaScript objects and other dynamically allocated JavaScript data.

For example:

const users = [];

for (let i = 0; i < 100000; i++) {
  users.push({
    id: i,
    name: `User ${i}`,
    email: `user${i}@example.com`,
  });
}

This creates thousands of objects that occupy heap memory.

If your application keeps references to objects that are no longer needed, garbage collection cannot reclaim them.

Stack Memory

The call stack manages function execution, local execution contexts, and references used during function calls.

Deep or uncontrolled recursion can cause a stack overflow, although this is different from a typical heap out-of-memory problem.

External Memory

Not all memory used by Node.js is part of the JavaScript heap.

Buffers, ArrayBuffers, and some native allocations can consume memory outside the V8 heap.

For example:

const buffer = Buffer.alloc(100 * 1024 * 1024);

This allocates a 100 MB buffer.

Your application can therefore consume significant memory even when V8 heap usage looks relatively low.

Important memory metrics

Node.js provides a built-in API for inspecting memory:

const memory = process.memoryUsage();

console.log({
  rss: memory.rss,
  heapTotal: memory.heapTotal,
  heapUsed: memory.heapUsed,
  external: memory.external,
  arrayBuffers: memory.arrayBuffers,
});

Here is what these metrics mean:

MetricMeaningRSSTotal resident memory occupied by the processheapTotalMemory allocated to the V8 heapheapUsedMemory currently used by JavaScript objectsexternalMemory associated with native objects outside the V8 heaparrayBuffersMemory used by ArrayBuffers and SharedArrayBuffers, including Node.js Buffers

Important: RSS includes more than the JavaScript heap. It can include native allocations, code, stacks, and other process memory.

This is why monitoring only heapUsed is not enough to understand production memory problems.

2. Why Node.js Applications Run Out of Memory

Let's look at some common causes.

2.1 Memory Leaks

A memory leak occurs when your application retains references to objects that are no longer needed.

JavaScript has automatic garbage collection, but garbage collection cannot remove objects that are still reachable.

Consider this example:

const requestHistory = [];

app.post("/api/search", async (req, res) => {
  requestHistory.push({
    query: req.body.query,
    timestamp: Date.now(),
  });

  res.json({ success: true });
});

Every request adds another object to the array.

Nothing removes old entries.

As traffic increases, the array continues growing and consumes more memory.

A better implementation would avoid storing unnecessary request data globally. If request history is required, use a database or a deliberately bounded cache.

2.2 Unbounded Caching

Caching can improve performance, but an incorrectly designed cache can become a memory problem.

For example:

const cache = new Map();

function saveUser(userId, userData) {
  cache.set(userId, userData);
}

If your application serves millions of users, this Map can continue growing indefinitely.

A cache needs a defined lifecycle.

Possible solutions include:

  • Maximum cache size.

  • Time-to-live (TTL).

  • Least Recently Used (LRU) eviction.

  • Redis for shared distributed caching.

  • Explicit cache invalidation.

For example, using an LRU cache:

import { LRUCache } from "lru-cache";

const userCache = new LRUCache({
  max: 1000,
  ttl: 1000 * 60 * 5,
});

function saveUser(userId, userData) {
  userCache.set(userId, userData);
}

This limits the number of entries and gives them a five-minute expiration period.

The exact cache size and TTL should be selected based on the size of cached objects and the application's workload.

2.3 Event Listener Leaks

Event listeners can retain references to objects and prevent garbage collection.

Consider:

function startMonitoring() {
  const userData = {
    name: "Asad",
    preferences: new Array(100000).fill("data"),
  };

  process.on("data", () => {
    console.log(userData.name);
  });
}

If startMonitoring() is called repeatedly, it registers more listeners.

Each listener closes over its own userData reference.

A better approach is to register listeners once and remove them when they are no longer required.

function startMonitoring() {
  const handler = () => {
    console.log("Monitoring event");
  };

  process.on("SIGTERM", handler);

  return () => {
    process.off("SIGTERM", handler);
  };
}

Always manage listener lifecycles, especially in long-running services.

2.4 Loading Large Files into Memory

This is another common issue in production applications.

Consider an API that reads an entire file before processing it:

import fs from "node:fs/promises";

app.get("/download", async (req, res) => {
  const file = await fs.readFile("./large-file.csv");

  res.send(file);
});

If the file is several gigabytes, loading the entire file into memory can consume a significant amount of RAM.

If multiple users request large files simultaneously, memory consumption can increase dramatically.

Use streams instead:

import fs from "node:fs";

app.get("/download", (req, res) => {
  const stream = fs.createReadStream("./large-file.csv");

  stream.on("error", (error) => {
    console.error("File streaming failed:", error);

    if (!res.headersSent) {
      res.status(500).end("Unable to download file");
    } else {
      res.destroy(error);
    }
  });

  stream.pipe(res);
});

Streams process data in chunks rather than loading the entire file into memory.

For more complex pipelines, use Node.js stream.pipeline() to handle errors and stream cleanup more reliably.

2.5 Excessive Concurrent Requests

Suppose your backend receives 5,000 requests simultaneously.

Each request performs expensive operations:

  • Fetching large database records.

  • Creating large arrays.

  • Processing JSON.

  • Calling external APIs.

  • Generating reports.

Even if each request uses only a small amount of memory, thousands of concurrent operations can create substantial memory pressure.

For example:

app.get("/api/reports", async (req, res) => {
  const records = await Report.find();

  const result = records.map((record) => ({
    ...record.toObject(),
    processed: true,
  }));

  res.json(result);
});

This retrieves every record and creates another array containing transformed objects.

For large datasets, this approach can consume too much memory.

Better approaches include:

  • Database pagination.

  • Projection to retrieve only required fields.

  • Cursor-based processing.

  • Streaming where appropriate.

  • Limiting concurrent operations.

  • Moving expensive work into background workers.

3. How to Identify Memory Problems in Production

Before changing code, understand what is happening.

Node.js provides built-in tools for memory monitoring.

3.1 Monitor Memory Usage

You can periodically inspect process memory:

setInterval(() => {
  const memory = process.memoryUsage();

  console.log({
    rss: `${(memory.rss / 1024 / 1024).toFixed(2)} MB`,
    heapUsed: `${(memory.heapUsed / 1024 / 1024).toFixed(2)} MB`,
    heapTotal: `${(memory.heapTotal / 1024 / 1024).toFixed(2)} MB`,
    external: `${(memory.external / 1024 / 1024).toFixed(2)} MB`,
  });
}, 10000);

This gives you visibility into memory usage every ten seconds.

In production, send these measurements to a monitoring platform instead of relying only on console logs.

For example, you can use:

  • Prometheus.

  • Grafana.

  • AWS CloudWatch.

  • Datadog.

  • New Relic.

Monitor trends rather than reacting to a single memory reading.

3.2 Understand Garbage Collection

V8 uses garbage collection to reclaim memory occupied by objects that are no longer reachable.

If an application frequently allocates objects, garbage collection may run more often.

A memory leak can still exist because leaked objects remain reachable.

For debugging, Node.js can expose garbage collection information:

node --trace-gc server.js

This helps investigate garbage collection activity.

However, verbose GC output can be expensive and noisy. Use it carefully, preferably in a controlled environment or during a targeted diagnostic session.

3.3 Capture Heap Snapshots

Heap snapshots help you inspect which objects occupy JavaScript heap memory.

You can use Chrome DevTools with the Node.js inspector.

Start your application with:

node --inspect server.js

Then:

  1. Open Chrome.

  2. Navigate to chrome://inspect.

  3. Find your Node.js process.

  4. Open its DevTools session.

  5. Select the Memory tab.

  6. Capture a heap snapshot.

  7. Repeat after reproducing the workload.

  8. Compare retained objects and memory growth.

Look for:

  • Large arrays.

  • Unexpectedly growing Maps and Sets.

  • Retained closures.

  • Event listeners.

  • Cached objects.

  • Objects retained by global references.

A heap snapshot can reveal retaining paths, which show why an object is still reachable.

Production warning: Heap snapshots can consume substantial additional memory, pause application execution, and contain sensitive application data. Capture them only with appropriate access controls and preferably in a controlled reproduction environment.

3.4 Use the Node.js Inspector and Profiling Tools

Other useful tools include:

  • Chrome DevTools Memory and Performance panels.

  • Node.js built-in inspector.

  • Clinic.js profiling tools.

  • Heap profiling tools.

  • Application Performance Monitoring (APM) platforms.

A good debugging workflow is:

  1. Reproduce the problem.

  2. Record memory metrics.

  3. Capture a baseline snapshot.

  4. Run a representative workload.

  5. Capture another snapshot.

  6. Compare object counts and retaining paths.

  7. Identify the code responsible.

  8. Fix the issue and repeat the test.

The goal is to identify the source of memory retention rather than simply increasing the server's RAM.

4. How to Fix Common Memory Problems

Let's summarize the engineering solutions.

4.1 Avoid Unbounded Data Structures

Avoid storing unlimited data in global arrays, Maps, Sets, or in-memory caches.

Bad:

const cache = new Map();

function addToCache(key, value) {
  cache.set(key, value);
}

Better:

import { LRUCache } from "lru-cache";

const cache = new LRUCache({
  max: 500,
  ttl: 1000 * 60 * 10,
});

Define a clear retention policy for every in-memory data structure.

4.2 Use Streams for Large Data

Instead of reading or generating an entire file in memory, process it incrementally.

For example:

import fs from "node:fs";
import { pipeline } from "node:stream/promises";

await pipeline(
  fs.createReadStream("input.csv"),
  fs.createWriteStream("output.csv")
);

Real applications may include parsing and transformation streams between the source and destination.

The key is to avoid accumulating the entire dataset in memory.

4.3 Move Heavy Tasks to Background Workers

Not every operation should run inside the HTTP request lifecycle.

Consider:

  • PDF generation.

  • Image processing.

  • Large report generation.

  • Video transcoding.

  • Bulk email sending.

  • AI inference and document processing.

A better architecture is:

Client
  |
  v
Node.js API
  |
  v
Redis / Message Queue
  |
  v
Background Workers
  |
  v
Database / Object Storage

You can use BullMQ with Redis to process jobs in separate worker processes.

Example:

import { Queue } from "bullmq";

const reportQueue = new Queue("reports", {
  connection: {
    host: "localhost",
    port: 6379,
  },
});

await reportQueue.add("generate-report", {
  userId: "user-123",
  reportId: "report-456",
});

A separate worker processes the job.

This separates API responsiveness from expensive background processing.

However, workers also consume memory. Set appropriate concurrency limits and monitor their resource usage independently.

4.4 Limit Concurrency

Processing every task simultaneously can create memory pressure.

Use controlled concurrency for expensive operations.

For example, instead of launching thousands of asynchronous tasks at once, process a limited number at a time.

A production implementation can use a queue or a concurrency-control library.

The appropriate limit depends on:

  • Available memory.

  • CPU capacity.

  • Task size.

  • Database connection limits.

  • External service rate limits.

4.5 Clean Up Resources

Close resources when they are no longer required.

Examples include:

  • Database cursors.

  • File streams.

  • Event listeners.

  • Timers.

  • WebSocket connections.

  • Temporary buffers.

  • External client connections.

Use try/finally where necessary to guarantee cleanup.

const cursor = collection.find({});

try {
  for await (const document of cursor) {
    await processDocument(document);
  }
} finally {
  await cursor.close();
}

This is particularly important for long-running background processes.

5. Does Increasing Node.js Heap Size Fix the Problem?

Node.js allows you to configure the V8 old-space memory limit.

For example:

node --max-old-space-size=4096 server.js

This sets the V8 old-space limit to approximately 4 GB.

It can help when a legitimate workload needs more JavaScript heap memory.

However, it is not a permanent solution for a memory leak.

Consider this situation:

  • Application starts with 300 MB.

  • Memory grows to 1 GB.

  • You increase the heap limit.

  • Memory continues growing.

  • Eventually the application reaches the new limit.

You have delayed the crash, not fixed its cause.

Also remember:

The V8 heap limit is not the same as the total process memory limit.

Your process also uses memory outside the JavaScript heap. A container with a 2 GB memory limit cannot safely run a process configured with a 4 GB V8 heap limit.

Always consider the container or machine's total memory budget.

6. What Happens When a Node.js Application Runs Inside Docker?

Production Node.js applications commonly run inside Docker containers.

Containers can have memory limits.

For example:

docker run \
  --memory="1g" \
  --memory-swap="1g" \
  my-node-app

If the container exceeds its available memory, the operating system may terminate a process through the Out-Of-Memory (OOM) mechanism.

This can happen even when the V8 heap has not reached its own configured limit.

There are two important scenarios:

Scenario 1: V8 heap exhaustion

V8 cannot allocate more memory for JavaScript objects and may terminate the process with a fatal out-of-memory error.

Scenario 2: Container or operating-system OOM

The container exceeds its memory budget, and the operating system or container runtime may kill the process.

These are different failure mechanisms, so investigate both application memory metrics and container memory metrics.

In Kubernetes, define appropriate resource requests and limits for each workload.

Example:

resources:
  requests:
    memory: "256Mi"
    cpu: "250m"

  limits:
    memory: "1Gi"
    cpu: "1000m"

These values are examples, not universal production recommendations. Set them based on load testing and actual resource consumption.

7. How to Design a More Reliable Node.js Production Architecture

Let's put everything together.

A production application should not depend on a single Node.js process handling every request and every expensive task.

A more resilient architecture separates responsibilities.

                  Users
                    |
                    v
              Load Balancer
                    |
          +---------+---------+
          |                   |
          v                   v
      Node.js API 1       Node.js API 2
          |                   |
          +---------+---------+
                    |
          +---------+---------+
          |                   |
          v                   v
       Redis Cache        MongoDB
          |
          v
      Job Queue
          |
          v
   Background Workers
          |
          v
   Object Storage / External APIs


       Monitoring & Observability
                    |
                    v
       Prometheus / Grafana
       CloudWatch / APM

Responsibilities of each component

Load Balancer

Distributes incoming requests across multiple application instances.

Node.js API Instances

Handle HTTP requests, authentication, validation, and business logic.

Redis

Stores shared cache data and can support distributed job queues.

MongoDB

Persists application data.

Background Workers

Handle CPU-intensive or time-consuming operations outside the API request lifecycle.

Object Storage

Stores large files instead of keeping them in application memory.

Monitoring

Tracks memory usage, CPU consumption, request latency, errors, and container health.

This architecture helps isolate expensive operations and distribute workloads.

However, adding more servers does not automatically fix a memory leak. If every instance has the same leak, every instance can eventually crash.

Fix the underlying issue first, then scale the application according to its workload.

8. Production Monitoring: What Should You Track?

Memory problems are easier to solve when you detect them before users experience failures.

Important metrics include:

MetricWhy it mattersRSSTotal process memory consumptionHeap usedJavaScript heap consumptionExternal memoryMemory outside the V8 heapHeap growth over timeHelps identify possible leaksGC duration and frequencyShows garbage collection pressureCPU utilizationDetects expensive processingEvent loop lagIdentifies event-loop responsiveness problemsRequest latencyShows the impact on usersContainer memoryDetects approaching memory limitsOOM events and restartsIdentifies process or container failures

You can expose application metrics through Prometheus and visualize them with Grafana.

For AWS-hosted applications, CloudWatch can also help monitor EC2, ECS, and container-level resource usage.

A useful alerting strategy should warn you before the application reaches its memory limit.

Do not wait until the server crashes to investigate.

9. A Practical Production Debugging Checklist

When a Node.js application starts consuming too much memory, follow this process.

Step 1: Confirm the problem

  • Is RSS increasing continuously?

  • Is heap usage increasing?

  • Is external memory increasing?

  • Does memory stabilize after garbage collection?

  • Are containers approaching their memory limits?

Step 2: Identify the workload

  • Did traffic suddenly increase?

  • Did a new deployment introduce the problem?

  • Are large files being processed?

  • Are database queries returning too many records?

  • Are background jobs accumulating?

Step 3: Investigate memory retention

  • Compare heap snapshots.

  • Inspect large retained objects.

  • Check global Maps and arrays.

  • Inspect event listeners and closures.

  • Review cache expiration policies.

Step 4: Fix the root cause

  • Remove unnecessary references.

  • Introduce bounded caching.

  • Use streaming.

  • Limit concurrency.

  • Clean up resources.

  • Move expensive tasks into background workers.

Step 5: Validate the solution

  • Run load tests.

  • Monitor memory over time.

  • Compare before-and-after snapshots.

  • Check container memory usage.

  • Verify that memory stabilizes under representative workloads.

10. Final Thoughts

Memory management is not only a JavaScript programming concern. It is a production engineering responsibility.

A Node.js application can work perfectly during development and still fail when real traffic, large datasets, concurrent requests, and background workloads increase.

The most important lesson is that increasing server memory should not be your first response to an out-of-memory crash.

First, understand where memory is being consumed. Then identify whether the problem comes from JavaScript heap retention, external allocations, excessive concurrency, large data processing, or infrastructure limits.

A reliable production application combines:

  • Proper memory management.

  • Efficient database queries.

  • Bounded caching.

  • Streaming for large data.

  • Background job processing.

  • Controlled concurrency.

  • Resource monitoring.

  • Appropriate infrastructure limits.

Don't just increase RAM when your server crashes. Find out why your application needs that memory in the first place.

About the Author

Asad Saeed | Senior Software Engineer | Full Stack Developer

I share practical insights on backend engineering, MERN Stack development, distributed systems, database architecture, cloud computing, AI integration, and building reliable production applications.

Asad Saeed

Asad Saeed

Senior Software Engineer | Full Stack Developer

More posts →

Related Posts

Don't Stop Here

Docker for Full-Stack Developers: Complete Guide (2026)

Docker for Full-Stack Developers: Complete Guide (2026)

Learn Docker for full-stack development with practical examples covering Dockerfiles, images, containers, Docker Compose, networking, environment variables, volumes, and production deployment.

DOCKERDEVOPSSOFTWARE ENGINEERING
© 2026 · Asad Saeed
All Posts
Why Node.js Servers Run Out of Memory: Debugging Memory Leaks and OOM Crashes

Why Node.js Servers Run Out of Memory: Debugging Memory Leaks and OOM Crashes

NODE.JSJAVASCRIPTSYSTEM DESIGNBACKEND DEVELOPMENTASAD SAEED
November 18, 202614 min readBy Asad Saeed

Learn why Node.js servers run out of memory, how to debug memory leaks with heap snapshots, and how to prevent production OOM crashes using streams, Redis, workers, Docker, and monitoring.

Introduction

Imagine deploying a Node.js application that works perfectly during development.

Initially, the server uses 200 MB of memory. After a few hours, memory usage increases to 500 MB. Later, it reaches 1 GB, then 2 GB. Eventually, the application becomes unresponsive or crashes completely.

Requests start failing. Background jobs stop processing. Users experience timeouts. In some environments, the operating system or container runtime terminates the process because it exceeds its memory limit.

This is a common production problem in Node.js applications.

The important thing to understand is that increasing memory usage does not always mean your application has a memory leak. It could be caused by large requests, unbounded caches, inefficient queries, excessive concurrency, external memory allocation, or simply a workload that requires more resources.

In this article, we'll explore:

  • How Node.js manages memory.

  • Why production applications run out of memory.

  • How to identify memory leaks.

  • How to inspect heap snapshots and memory usage.

  • How to fix common memory problems.

  • How to design a more reliable production architecture.

Let's understand this from a practical MERN Stack perspective.

1. Understanding How Node.js Manages Memory

Node.js runs JavaScript using the V8 JavaScript engine.

V8 manages JavaScript memory through a garbage collector. It allocates memory for objects, arrays, strings, functions, closures, and other JavaScript values.

At a high level, Node.js memory includes several important areas.

Heap Memory

The V8 heap stores JavaScript objects and other dynamically allocated JavaScript data.

For example:

const users = [];

for (let i = 0; i < 100000; i++) {
  users.push({
    id: i,
    name: `User ${i}`,
    email: `user${i}@example.com`,
  });
}

This creates thousands of objects that occupy heap memory.

If your application keeps references to objects that are no longer needed, garbage collection cannot reclaim them.

Stack Memory

The call stack manages function execution, local execution contexts, and references used during function calls.

Deep or uncontrolled recursion can cause a stack overflow, although this is different from a typical heap out-of-memory problem.

External Memory

Not all memory used by Node.js is part of the JavaScript heap.

Buffers, ArrayBuffers, and some native allocations can consume memory outside the V8 heap.

For example:

const buffer = Buffer.alloc(100 * 1024 * 1024);

This allocates a 100 MB buffer.

Your application can therefore consume significant memory even when V8 heap usage looks relatively low.

Important memory metrics

Node.js provides a built-in API for inspecting memory:

const memory = process.memoryUsage();

console.log({
  rss: memory.rss,
  heapTotal: memory.heapTotal,
  heapUsed: memory.heapUsed,
  external: memory.external,
  arrayBuffers: memory.arrayBuffers,
});

Here is what these metrics mean:

MetricMeaningRSSTotal resident memory occupied by the processheapTotalMemory allocated to the V8 heapheapUsedMemory currently used by JavaScript objectsexternalMemory associated with native objects outside the V8 heaparrayBuffersMemory used by ArrayBuffers and SharedArrayBuffers, including Node.js Buffers

Important: RSS includes more than the JavaScript heap. It can include native allocations, code, stacks, and other process memory.

This is why monitoring only heapUsed is not enough to understand production memory problems.

2. Why Node.js Applications Run Out of Memory

Let's look at some common causes.

2.1 Memory Leaks

A memory leak occurs when your application retains references to objects that are no longer needed.

JavaScript has automatic garbage collection, but garbage collection cannot remove objects that are still reachable.

Consider this example:

const requestHistory = [];

app.post("/api/search", async (req, res) => {
  requestHistory.push({
    query: req.body.query,
    timestamp: Date.now(),
  });

  res.json({ success: true });
});

Every request adds another object to the array.

Nothing removes old entries.

As traffic increases, the array continues growing and consumes more memory.

A better implementation would avoid storing unnecessary request data globally. If request history is required, use a database or a deliberately bounded cache.

2.2 Unbounded Caching

Caching can improve performance, but an incorrectly designed cache can become a memory problem.

For example:

const cache = new Map();

function saveUser(userId, userData) {
  cache.set(userId, userData);
}

If your application serves millions of users, this Map can continue growing indefinitely.

A cache needs a defined lifecycle.

Possible solutions include:

  • Maximum cache size.

  • Time-to-live (TTL).

  • Least Recently Used (LRU) eviction.

  • Redis for shared distributed caching.

  • Explicit cache invalidation.

For example, using an LRU cache:

import { LRUCache } from "lru-cache";

const userCache = new LRUCache({
  max: 1000,
  ttl: 1000 * 60 * 5,
});

function saveUser(userId, userData) {
  userCache.set(userId, userData);
}

This limits the number of entries and gives them a five-minute expiration period.

The exact cache size and TTL should be selected based on the size of cached objects and the application's workload.

2.3 Event Listener Leaks

Event listeners can retain references to objects and prevent garbage collection.

Consider:

function startMonitoring() {
  const userData = {
    name: "Asad",
    preferences: new Array(100000).fill("data"),
  };

  process.on("data", () => {
    console.log(userData.name);
  });
}

If startMonitoring() is called repeatedly, it registers more listeners.

Each listener closes over its own userData reference.

A better approach is to register listeners once and remove them when they are no longer required.

function startMonitoring() {
  const handler = () => {
    console.log("Monitoring event");
  };

  process.on("SIGTERM", handler);

  return () => {
    process.off("SIGTERM", handler);
  };
}

Always manage listener lifecycles, especially in long-running services.

2.4 Loading Large Files into Memory

This is another common issue in production applications.

Consider an API that reads an entire file before processing it:

import fs from "node:fs/promises";

app.get("/download", async (req, res) => {
  const file = await fs.readFile("./large-file.csv");

  res.send(file);
});

If the file is several gigabytes, loading the entire file into memory can consume a significant amount of RAM.

If multiple users request large files simultaneously, memory consumption can increase dramatically.

Use streams instead:

import fs from "node:fs";

app.get("/download", (req, res) => {
  const stream = fs.createReadStream("./large-file.csv");

  stream.on("error", (error) => {
    console.error("File streaming failed:", error);

    if (!res.headersSent) {
      res.status(500).end("Unable to download file");
    } else {
      res.destroy(error);
    }
  });

  stream.pipe(res);
});

Streams process data in chunks rather than loading the entire file into memory.

For more complex pipelines, use Node.js stream.pipeline() to handle errors and stream cleanup more reliably.

2.5 Excessive Concurrent Requests

Suppose your backend receives 5,000 requests simultaneously.

Each request performs expensive operations:

  • Fetching large database records.

  • Creating large arrays.

  • Processing JSON.

  • Calling external APIs.

  • Generating reports.

Even if each request uses only a small amount of memory, thousands of concurrent operations can create substantial memory pressure.

For example:

app.get("/api/reports", async (req, res) => {
  const records = await Report.find();

  const result = records.map((record) => ({
    ...record.toObject(),
    processed: true,
  }));

  res.json(result);
});

This retrieves every record and creates another array containing transformed objects.

For large datasets, this approach can consume too much memory.

Better approaches include:

  • Database pagination.

  • Projection to retrieve only required fields.

  • Cursor-based processing.

  • Streaming where appropriate.

  • Limiting concurrent operations.

  • Moving expensive work into background workers.

3. How to Identify Memory Problems in Production

Before changing code, understand what is happening.

Node.js provides built-in tools for memory monitoring.

3.1 Monitor Memory Usage

You can periodically inspect process memory:

setInterval(() => {
  const memory = process.memoryUsage();

  console.log({
    rss: `${(memory.rss / 1024 / 1024).toFixed(2)} MB`,
    heapUsed: `${(memory.heapUsed / 1024 / 1024).toFixed(2)} MB`,
    heapTotal: `${(memory.heapTotal / 1024 / 1024).toFixed(2)} MB`,
    external: `${(memory.external / 1024 / 1024).toFixed(2)} MB`,
  });
}, 10000);

This gives you visibility into memory usage every ten seconds.

In production, send these measurements to a monitoring platform instead of relying only on console logs.

For example, you can use:

  • Prometheus.

  • Grafana.

  • AWS CloudWatch.

  • Datadog.

  • New Relic.

Monitor trends rather than reacting to a single memory reading.

3.2 Understand Garbage Collection

V8 uses garbage collection to reclaim memory occupied by objects that are no longer reachable.

If an application frequently allocates objects, garbage collection may run more often.

A memory leak can still exist because leaked objects remain reachable.

For debugging, Node.js can expose garbage collection information:

node --trace-gc server.js

This helps investigate garbage collection activity.

However, verbose GC output can be expensive and noisy. Use it carefully, preferably in a controlled environment or during a targeted diagnostic session.

3.3 Capture Heap Snapshots

Heap snapshots help you inspect which objects occupy JavaScript heap memory.

You can use Chrome DevTools with the Node.js inspector.

Start your application with:

node --inspect server.js

Then:

  1. Open Chrome.

  2. Navigate to chrome://inspect.

  3. Find your Node.js process.

  4. Open its DevTools session.

  5. Select the Memory tab.

  6. Capture a heap snapshot.

  7. Repeat after reproducing the workload.

  8. Compare retained objects and memory growth.

Look for:

  • Large arrays.

  • Unexpectedly growing Maps and Sets.

  • Retained closures.

  • Event listeners.

  • Cached objects.

  • Objects retained by global references.

A heap snapshot can reveal retaining paths, which show why an object is still reachable.

Production warning: Heap snapshots can consume substantial additional memory, pause application execution, and contain sensitive application data. Capture them only with appropriate access controls and preferably in a controlled reproduction environment.

3.4 Use the Node.js Inspector and Profiling Tools

Other useful tools include:

  • Chrome DevTools Memory and Performance panels.

  • Node.js built-in inspector.

  • Clinic.js profiling tools.

  • Heap profiling tools.

  • Application Performance Monitoring (APM) platforms.

A good debugging workflow is:

  1. Reproduce the problem.

  2. Record memory metrics.

  3. Capture a baseline snapshot.

  4. Run a representative workload.

  5. Capture another snapshot.

  6. Compare object counts and retaining paths.

  7. Identify the code responsible.

  8. Fix the issue and repeat the test.

The goal is to identify the source of memory retention rather than simply increasing the server's RAM.

4. How to Fix Common Memory Problems

Let's summarize the engineering solutions.

4.1 Avoid Unbounded Data Structures

Avoid storing unlimited data in global arrays, Maps, Sets, or in-memory caches.

Bad:

const cache = new Map();

function addToCache(key, value) {
  cache.set(key, value);
}

Better:

import { LRUCache } from "lru-cache";

const cache = new LRUCache({
  max: 500,
  ttl: 1000 * 60 * 10,
});

Define a clear retention policy for every in-memory data structure.

4.2 Use Streams for Large Data

Instead of reading or generating an entire file in memory, process it incrementally.

For example:

import fs from "node:fs";
import { pipeline } from "node:stream/promises";

await pipeline(
  fs.createReadStream("input.csv"),
  fs.createWriteStream("output.csv")
);

Real applications may include parsing and transformation streams between the source and destination.

The key is to avoid accumulating the entire dataset in memory.

4.3 Move Heavy Tasks to Background Workers

Not every operation should run inside the HTTP request lifecycle.

Consider:

  • PDF generation.

  • Image processing.

  • Large report generation.

  • Video transcoding.

  • Bulk email sending.

  • AI inference and document processing.

A better architecture is:

Client
  |
  v
Node.js API
  |
  v
Redis / Message Queue
  |
  v
Background Workers
  |
  v
Database / Object Storage

You can use BullMQ with Redis to process jobs in separate worker processes.

Example:

import { Queue } from "bullmq";

const reportQueue = new Queue("reports", {
  connection: {
    host: "localhost",
    port: 6379,
  },
});

await reportQueue.add("generate-report", {
  userId: "user-123",
  reportId: "report-456",
});

A separate worker processes the job.

This separates API responsiveness from expensive background processing.

However, workers also consume memory. Set appropriate concurrency limits and monitor their resource usage independently.

4.4 Limit Concurrency

Processing every task simultaneously can create memory pressure.

Use controlled concurrency for expensive operations.

For example, instead of launching thousands of asynchronous tasks at once, process a limited number at a time.

A production implementation can use a queue or a concurrency-control library.

The appropriate limit depends on:

  • Available memory.

  • CPU capacity.

  • Task size.

  • Database connection limits.

  • External service rate limits.

4.5 Clean Up Resources

Close resources when they are no longer required.

Examples include:

  • Database cursors.

  • File streams.

  • Event listeners.

  • Timers.

  • WebSocket connections.

  • Temporary buffers.

  • External client connections.

Use try/finally where necessary to guarantee cleanup.

const cursor = collection.find({});

try {
  for await (const document of cursor) {
    await processDocument(document);
  }
} finally {
  await cursor.close();
}

This is particularly important for long-running background processes.

5. Does Increasing Node.js Heap Size Fix the Problem?

Node.js allows you to configure the V8 old-space memory limit.

For example:

node --max-old-space-size=4096 server.js

This sets the V8 old-space limit to approximately 4 GB.

It can help when a legitimate workload needs more JavaScript heap memory.

However, it is not a permanent solution for a memory leak.

Consider this situation:

  • Application starts with 300 MB.

  • Memory grows to 1 GB.

  • You increase the heap limit.

  • Memory continues growing.

  • Eventually the application reaches the new limit.

You have delayed the crash, not fixed its cause.

Also remember:

The V8 heap limit is not the same as the total process memory limit.

Your process also uses memory outside the JavaScript heap. A container with a 2 GB memory limit cannot safely run a process configured with a 4 GB V8 heap limit.

Always consider the container or machine's total memory budget.

6. What Happens When a Node.js Application Runs Inside Docker?

Production Node.js applications commonly run inside Docker containers.

Containers can have memory limits.

For example:

docker run \
  --memory="1g" \
  --memory-swap="1g" \
  my-node-app

If the container exceeds its available memory, the operating system may terminate a process through the Out-Of-Memory (OOM) mechanism.

This can happen even when the V8 heap has not reached its own configured limit.

There are two important scenarios:

Scenario 1: V8 heap exhaustion

V8 cannot allocate more memory for JavaScript objects and may terminate the process with a fatal out-of-memory error.

Scenario 2: Container or operating-system OOM

The container exceeds its memory budget, and the operating system or container runtime may kill the process.

These are different failure mechanisms, so investigate both application memory metrics and container memory metrics.

In Kubernetes, define appropriate resource requests and limits for each workload.

Example:

resources:
  requests:
    memory: "256Mi"
    cpu: "250m"

  limits:
    memory: "1Gi"
    cpu: "1000m"

These values are examples, not universal production recommendations. Set them based on load testing and actual resource consumption.

7. How to Design a More Reliable Node.js Production Architecture

Let's put everything together.

A production application should not depend on a single Node.js process handling every request and every expensive task.

A more resilient architecture separates responsibilities.

                  Users
                    |
                    v
              Load Balancer
                    |
          +---------+---------+
          |                   |
          v                   v
      Node.js API 1       Node.js API 2
          |                   |
          +---------+---------+
                    |
          +---------+---------+
          |                   |
          v                   v
       Redis Cache        MongoDB
          |
          v
      Job Queue
          |
          v
   Background Workers
          |
          v
   Object Storage / External APIs


       Monitoring & Observability
                    |
                    v
       Prometheus / Grafana
       CloudWatch / APM

Responsibilities of each component

Load Balancer

Distributes incoming requests across multiple application instances.

Node.js API Instances

Handle HTTP requests, authentication, validation, and business logic.

Redis

Stores shared cache data and can support distributed job queues.

MongoDB

Persists application data.

Background Workers

Handle CPU-intensive or time-consuming operations outside the API request lifecycle.

Object Storage

Stores large files instead of keeping them in application memory.

Monitoring

Tracks memory usage, CPU consumption, request latency, errors, and container health.

This architecture helps isolate expensive operations and distribute workloads.

However, adding more servers does not automatically fix a memory leak. If every instance has the same leak, every instance can eventually crash.

Fix the underlying issue first, then scale the application according to its workload.

8. Production Monitoring: What Should You Track?

Memory problems are easier to solve when you detect them before users experience failures.

Important metrics include:

MetricWhy it mattersRSSTotal process memory consumptionHeap usedJavaScript heap consumptionExternal memoryMemory outside the V8 heapHeap growth over timeHelps identify possible leaksGC duration and frequencyShows garbage collection pressureCPU utilizationDetects expensive processingEvent loop lagIdentifies event-loop responsiveness problemsRequest latencyShows the impact on usersContainer memoryDetects approaching memory limitsOOM events and restartsIdentifies process or container failures

You can expose application metrics through Prometheus and visualize them with Grafana.

For AWS-hosted applications, CloudWatch can also help monitor EC2, ECS, and container-level resource usage.

A useful alerting strategy should warn you before the application reaches its memory limit.

Do not wait until the server crashes to investigate.

9. A Practical Production Debugging Checklist

When a Node.js application starts consuming too much memory, follow this process.

Step 1: Confirm the problem

  • Is RSS increasing continuously?

  • Is heap usage increasing?

  • Is external memory increasing?

  • Does memory stabilize after garbage collection?

  • Are containers approaching their memory limits?

Step 2: Identify the workload

  • Did traffic suddenly increase?

  • Did a new deployment introduce the problem?

  • Are large files being processed?

  • Are database queries returning too many records?

  • Are background jobs accumulating?

Step 3: Investigate memory retention

  • Compare heap snapshots.

  • Inspect large retained objects.

  • Check global Maps and arrays.

  • Inspect event listeners and closures.

  • Review cache expiration policies.

Step 4: Fix the root cause

  • Remove unnecessary references.

  • Introduce bounded caching.

  • Use streaming.

  • Limit concurrency.

  • Clean up resources.

  • Move expensive tasks into background workers.

Step 5: Validate the solution

  • Run load tests.

  • Monitor memory over time.

  • Compare before-and-after snapshots.

  • Check container memory usage.

  • Verify that memory stabilizes under representative workloads.

10. Final Thoughts

Memory management is not only a JavaScript programming concern. It is a production engineering responsibility.

A Node.js application can work perfectly during development and still fail when real traffic, large datasets, concurrent requests, and background workloads increase.

The most important lesson is that increasing server memory should not be your first response to an out-of-memory crash.

First, understand where memory is being consumed. Then identify whether the problem comes from JavaScript heap retention, external allocations, excessive concurrency, large data processing, or infrastructure limits.

A reliable production application combines:

  • Proper memory management.

  • Efficient database queries.

  • Bounded caching.

  • Streaming for large data.

  • Background job processing.

  • Controlled concurrency.

  • Resource monitoring.

  • Appropriate infrastructure limits.

Don't just increase RAM when your server crashes. Find out why your application needs that memory in the first place.

About the Author

Asad Saeed | Senior Software Engineer | Full Stack Developer

I share practical insights on backend engineering, MERN Stack development, distributed systems, database architecture, cloud computing, AI integration, and building reliable production applications.

Asad Saeed

Asad Saeed

Senior Software Engineer | Full Stack Developer

More posts →

Related Posts

Don't Stop Here

Docker for Full-Stack Developers: Complete Guide (2026)

Docker for Full-Stack Developers: Complete Guide (2026)

Learn Docker for full-stack development with practical examples covering Dockerfiles, images, containers, Docker Compose, networking, environment variables, volumes, and production deployment.

DOCKERDEVOPSSOFTWARE ENGINEERING
© 2026 · Asad Saeed
Oct 19, 202612 min read
Read
Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Learn how Dependency Injection works in NestJS, including Providers, the IoC Container, Constructor Injection, Injection Tokens, Custom Providers, and best practices for building scalable, testable, and enterprise-ready Node.js applications.

NESTJSDEPENDENCY INJECTIONNODEJS
Oct 19, 20265 min read
Read
NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

Master the NestJS architecture by understanding Modules, Controllers, Providers, Dependency Injection, Middleware, Guards, Pipes, Interceptors, and Exception Filters. Learn the complete NestJS request lifecycle and build scalable, production-ready backend applications.

NESTJSNODEJSSOFTWARE ARCHITECTURE
Aug 5, 20266 min read
Read
F
Made with ❤️ by Asad Saeed
© 2026 · Asad Saeed
Made with ❤️ by Asad Saeed
F
Oct 19, 202612 min read
Read
Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Dependency Injection in NestJS Explained: Providers, IoC Container, Injection Tokens & Custom Providers (2026 Guide)

Learn how Dependency Injection works in NestJS, including Providers, the IoC Container, Constructor Injection, Injection Tokens, Custom Providers, and best practices for building scalable, testable, and enterprise-ready Node.js applications.

NESTJSDEPENDENCY INJECTIONNODEJS
Oct 19, 20265 min read
Read
NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

NestJS Architecture Explained: Controllers, Providers, Modules, Middleware, Guards & Interceptors (2026 Guide)

Master the NestJS architecture by understanding Modules, Controllers, Providers, Dependency Injection, Middleware, Guards, Pipes, Interceptors, and Exception Filters. Learn the complete NestJS request lifecycle and build scalable, production-ready backend applications.

NESTJSNODEJSSOFTWARE ARCHITECTURE
Aug 5, 20266 min read
Read
F
Made with ❤️ by Asad Saeed
© 2026 · Asad Saeed
Made with ❤️ by Asad Saeed
F