Troubleshooting Node.js Memory Use | Heroku Dev Center (2024)

Last updated February 22, 2024

Table of Contents

  • What is a memory leak?
  • Why are memory leaks a problem?
  • Heroku memory limits
  • Tuning the Garbage Collector
  • Running multiple processes
  • Debugging a memory leak
  • A practical example
  • Inspecting locally
  • Inspecting remotely

When your Node application uses more memory than is available on the Dyno, an R14 - Memory quota exceeded error message will be emitted to your application’s logs. This article is intended to help you understand your application’s memory use and give you the tools to run your application without memory errors.

What is a memory leak?

Every Node.js program allocates memory for new objects and periodically runs a garbage collector (GC) to reclaim the memory consumed by objects that aren’t used anymore. If the GC cannot deallocate memory, the amount of RAM taken up by your application will grow over time.

Why are memory leaks a problem?

Memory leaks become a problem when they grow large enough to slow your application down. For example, a small leak on each request can quickly become a problem when your application receives a sudden influx of traffic. Once your application exhausts all available RAM, it begins using the slower swap file, which will in turn slow down your server. Very large memory use might even crash the Node process, leading to dropped requests and downtime.

If a memory leak is small and only happens on a rarely used code path, then it’s often not worth the effort of tracking down. A small amount of extra memory builds up which gets reset every time your application is restarted, but it doesn’t slow down your application or impact users.

Heroku memory limits

The amount of physical memory available to your application depends on your dyno type. Memory use over these limits writes to disk at much slower speeds than direct RAM access. You will see R14 errors in your application logs when this paging starts to happen.

Tuning the Garbage Collector

In Node < 12, it sets a limit of 1.5 GB for long-lived objects by default. If this exceeds the memory available to your dyno, Node could allow your application to start paging memory to disk.

Gain more control over your application’s garbage collector with flags to the underlying V8 JavaScript engine in your Procfile:

web: node --optimize_for_size --max_old_space_size=920 server.js

If you’d like to tailor Node to a 512 MB dyno, try:

web: node --optimize_for_size --max_old_space_size=460 server.js

Versions of Node that are >= 12 may not need to use the --optimize_for_size and --max_old_space_size flags because JavaScript heap limit will be based on available memory.

Running multiple processes

If you are clustering your app to take advantage of extra compute resources, then you can run into a problem where the different Node processes compete with each other for your Dyno’s memory.

A common mistake is to determine the number of Node processes to run based on the number of CPUs, but the number of physical CPUs is not the best mechanism for scaling within a virtualized Linux container. The total amount of memory used by all Node processes should remain within dyno memory limits.

// Don't do thisconst CPUS = os.cpus().length;for (let i = 0; i < CPUS; i++) { cluster.fork();}

To determine the appropriate number of processes to run, we recommend setting the WEB_MEMORY environment variable to the amount of memory your application requires in megabytes. If your application runs best with a gigabyte of RAM then you can set it with the following command in your application directory.

$ heroku config:set WEB_MEMORY=1024

Based on the value of WEB_MEMORY and the dyno type, we calculate an appropriate number of processes and provide a WEB_CONCURRENCY environment variable that you can use to spin up workers without exceeding the dyno’s memory limits.

const WORKERS = process.env.WEB_CONCURRENCY || 1;for (let i = 0; i < WORKERS; i++) { cluster.fork();}

Learn more about Optimizing Node.js Application Concurrency

Debugging a memory leak

When facing a memory leak there are a number of steps you should take to attempt to find the problem.

Review recent changes

If your application suddenly exhibits large spikes in memory usage without similar spikes in throughput, a bug has likely been introduced in a recent code change. Try to narrow down when this might have happened and review the changes to your application during that time.

Update your dependencies

In modern applications, your code is often the tip of an iceberg. Even a small application could have thousands of lines of JavaScript hidden in node_modules, not to mention the millions of lines of code that make up the V8 JavaScript engine and all of the native libraries on which your application is built. It is a good idea to make sure that your memory issue is not lurking in one of your dependencies by updating to the latest stable versions and checking whether that resolves the issue.

  • Update to the latest version of Node.
  • Check which of your Node dependencies have updates available by running npm outdated or yarn outdated in your application’s directory.
  • Make sure your application is running on the latest Heroku stack, and if not, upgrade to the latest stack to use the latest stable version of Ubuntu with more recent system libraries.

Inspect the environment

Even if your application hasn’t changed, something in its dependency tree might have if you have not locked them down to exact versions using yarn or an npm lockfile. We also recommend explicitly specifying which version of Node that your application depends on.

A practical example

If you check all of the above and your application’s memory consumption continues to grow without limit, then it’s likely that there is a memory leak to find. Let’s take a look at an example.

A typical memory leak might retain a reference to an object that’s expected to only last during one request cycle by accidentally storing a reference to it in a global object that cannot be garbage collected. This example generates a random object using the dummy-json module to imitate an application object that might be returned from an API query and purposefully “leaks” it by storing it in a global array.

const http = require('http');const dummyjson = require('dummy-json');const leaks = [];function leakyServer(req, res) { const response = dummyjson.parse(` { "id": {{int 1000 9999}}, "name": "{{firstName}} {{lastName}}", "work": "{{company}}", "email": "{{email}}" } `); leaks.push(JSON.parse(response)); res.end(response);}const server = http.createServer(leakyServer) .listen(process.env.PORT || 3000);

Inspecting locally

If you can reproduce the leak while running your application locally, it’s simpler to get access to useful runtime information and will be easier to track down the error.

If you are running Node >= 7.5.0, start your server by passing the –inspect flag and open the the provided URL in Chrome to open up the Chrome DevTools for your Node process.

If you are unfamiliar with the Chrome DevTools, Addy Osmani has a guide to using them to hunt down memory issues.

$ node --inspect index.jsDebugger listening on port 9229.Warning: This is an experimental feature and could change at any time.To start debugging, open the following URL in Chrome: chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/dfd0036a-d3bd-4321-9e4b-f8e5ff70287a

If you are using Node < 7.5.0, then you can get access to the same functionality via node-inspector.

The tool you need is under the Profiles tab. Select Take Heap Snapshot and press the Take Snapshot button.

Troubleshooting Node.js Memory Use | Heroku Dev Center (1)

If you look at the captured snapshot you can see every data structure that has been allocated in your Node process, but it’s a bit overwhelming. To make it easier to see what’s leaking, gather some more snapshots so that you can compare them with each other.

Troubleshooting Node.js Memory Use | Heroku Dev Center (2)

However you will only be able to observe the leak if there is traffic being sent to the server. Run this cURL command to quickly make a large number of requests to build up some leaked objects.

$ for i in {1..1000}; do curl -s http://localhost:3000 > /dev/null; done

After running the command, capture another heap snapshot. Repeat this cycle a couple of times to get multiple snapshots. Then select the last snapshot and switch from the “Summary” view to the “Comparison” view in the drop down.

Troubleshooting Node.js Memory Use | Heroku Dev Center (3)

This will substantially cut down on the number of objects that you see. A good rule of thumb is to first ignore the items wrapped in parenthesis as those are built-in structures. The next item in the list in this case is Object. Looking at a couple of the retained Object’s you can see some examples of the data that has been leaked, which you can use to track down the leak in your application.

Troubleshooting Node.js Memory Use | Heroku Dev Center (4)

Inspecting remotely

Similar to using Chrome DevTools, you can set up port forwarding to inspect memory usage in a Heroku dyno with Heroku Exec.

It’s recommended to debug using a staging environment because Heroku Exec will connect to running dynos, so you may disrupt production traffic.

If your start script is in the package.json, add the --inspect flag to it. (The default port is 9229. In order to customize the port, you can assign a port number, such as --inspect=8080.) The package.json‘s script will look something like this:

"scripts": { "start": "node --inspect=8080 index.js"}

If you’re using a Procfile, you can add the flag to your web process:

web: node --inspect=8080 index.js

Deploy these changes to Heroku. Next, set up port forwarding from a local port. Make sure use the port that is specified in the Node process.

$ heroku ps:forward 8080

You should see the following:

SOCKSv5 proxy server started on port 1080Listening on 8080 and forwarding to web.1:8080Use CTRL+C to stop port fowarding

You can now use Chrome DevTools to take a snapshot of memory usage in your web process.

Keep reading

  • Node.js

Feedback

Log in to submit feedback.

Troubleshooting Node.js Memory Use | Heroku Dev Center (2024)

FAQs

How to check how much memory is allocated to Node js? ›

Using process. memoryUsage() Node. js API
  1. rss: Resident Set Size - the amount of memory allocated in the V8 context.
  2. heapTotal: Total size of the allocated heap.
  3. heapUsed: Memory used during the execution of the process.
  4. External: Memory usage of C++ objects bound to JavaScript objects managed by V8.
Apr 19, 2022

How to solve the process out of memory exception error in nodejs? ›

Increase memory allocation

If the memory usage is consistently high, we may need to allocate more memory to the Node. js process by setting the --max-old-space-size option when starting our Node. js application.

Why is Node taking up so much memory? ›

Every Node. js program allocates memory for new objects and periodically runs a garbage collector (GC) to reclaim the memory consumed by objects that aren't used anymore. If the GC cannot deallocate memory, the amount of RAM taken up by your application will grow over time.

How do I allocate more RAM to Node JS? ›

To increase the memory limit for your Node. js application, use the `--max-old-space-size` flag when starting your script. The value following this flag denotes the maximum memory allocation in megabytes.

How do I know how much RAM I have allocated? ›

Method 1– ctrl, shift, esc
  1. Press the following keys: Ctrl + Shift + Esc.
  2. The Task Manager should appear.
  3. Click on the “Performance” tab and check the section titled “Memory”

How do you check how much RAM you can allocate? ›

Press Ctrl + Shift + Esc to launch Task Manager. Or, right-click the Taskbar and select Task Manager. Select the Performance tab to see current RAM usage displayed in the Memory box, and total RAM capacity listed under Physical Memory.

How to manage memory in node js? ›

Best Practices for Node. js Memory Management
  1. Monitor and Detect Memory Leaks: Utilize tools like `node-heapdump` or `node-memwatch` to identify and analyze memory leaks. ...
  2. Limit Memory Usage: ...
  3. Optimize Garbage Collection: ...
  4. Use Object Pooling: ...
  5. Profile Your Application: ...
  6. Upgrade Node.
Nov 5, 2023

How to check memory leaks in NodeJS? ›

Tools for Debugging Memory Leaks
  1. heapdump: This is a built-in Node. js module that can be used to create a snapshot of the program's memory heap. ...
  2. memwatch: This is a popular third-party module that can be used to monitor the program's memory usage over time. ...
  3. chrome devtools: Node v6.
Jan 3, 2023

How to debug JavaScript heap out of memory? ›

node-inspect is a built-in debugger for Node. js. It allows for live debugging, setting breakpoints, and inspecting variables. Particularly for memory issues, it can be paired with Chrome DevTools to profile and take heap snapshots, just as you would with frontend JavaScript.

How to reduce memory usage in NodeJS? ›

To optimize the Garbage Collector, here are some practical tips.
  1. Avoid global variables: Do not use global variables. ...
  2. Use object pooling: Reuse objects instead of creating them new through object pooling.
  3. Remove unnecessary data: Removing cached data or processed data can reduce what has already been processed.

What is the maximum memory limit for Node js? ›

By default, Node. js (up to 11. x ) uses a maximum heap size of 700MB and 1400MB on 32-bit and 64-bit platforms, respectively. For current defaults, see the reference mentioned at the end of blog.

What is the default memory limit in Node js? ›

Save motss/f55b92ccab0d434fa6e6cfd07423014b to your computer and use it in GitHub Desktop. By default the memory limit in Node. js is 512MB. This will cause FATAL ERROR- JS Allocation failed – process out of memory when processing large data files.

How to improve node js performance? ›

2. Tips to Improve Node JS Performance
  1. 2.1 Monitor & Measure App Performance. ...
  2. 2.2 Reduce Latency Time Through Caching. ...
  3. 2.3 Optimize Your Data Handling Methods. ...
  4. 2.4 Load Balancing. ...
  5. 2.5 Use Timeouts. ...
  6. 2.6 Monitor in Real-Time. ...
  7. 7 Improve Throughput by Cluster. ...
  8. 2.8 Employ HTTP/2 and SSL/TLS to Make Web Browsing Faster.
Nov 3, 2023

How can I increase my RAM availability? ›

Here are a few steps you'll want to try before you take drastic measures to free up RAM.
  1. Restart your device. ...
  2. Try other browsers. ...
  3. Clear RAM cache. ...
  4. Update software to the latest versions. ...
  5. Delete unused extensions. ...
  6. Use optimization software.
Feb 23, 2024

How to set value in local storage in node js? ›

To store data in local storage, you use the setItem() method. This method takes in two arguments, a key and a value. If the key does not exist in local storage, the setItem() method will create a new key and assign the given value to it.

How much memory does Node.js use? ›

By default, Node. js (up to 11. x ) uses a maximum heap size of 700MB and 1400MB on 32-bit and 64-bit platforms, respectively.

How to check Node size? ›

SSH into your Node. Wait for ncdu to finish scanning your Node's disk. It will display a list of directories and their respective sizes. Use the arrow keys to navigate through the directories and subdirectories to find out which one is taking up the most disk space.

Top Articles
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 5852

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.