Optimize Node.js memory consumption
Asked Answered
W

5

17

I'm writing a simple cms in Node.js, Express and MongoDB. I'm planning to run a different Node.js process for every site. The problem is that after startup the process takes about 90m of RAM and for me it's too big (eight site take all server RAM). This memory is taken after the first connection to the site and other connections don't affect the memory.

Is there a guideline or a list of "best practices" to optimize this memory usage? I'm trying to track where the memory is allocated with process.memoryUsage() or a similar function but it's not simple to do this.

Is not a problem of memory leaks or something similar because the memory usage doesn't grow up after the first connection, so probably the optimization could be in loading less modules or do something differently...

Watkins answered 11/2, 2014 at 6:20 Comment(0)
D
16

The links below may help you to understand and detect memory leaks (if they do exist):

Debugging memory leaks in node.js

Detecting Memory Leaks in Node.js Applications

Tracking Down Memory Leaks in Node.js

These SO questions may also be useful:

How to monitor the memory usage of Node.js?

Node.js Memory Leak Hunting

Democratize answered 11/2, 2014 at 7:22 Comment(0)
M
0

Here is a quick fix, a node.js lib that will restart the any node process once it reaches a certain size. https://github.com/DoryZi/memory_limiter

Misti answered 4/3, 2015 at 17:49 Comment(0)
M
0

Set the --max_old_space_size CLI flag to control the maximum heap size. There's a post that describes Running a node.js app in a low-memory environment

tl;dr; Try setting this value, in megabytes, to about 80% of the maximum memory footprint you want node to try to remain under. e.g. to run app.js and keep it under 500MB RAM used

node --max_old_space_size=400 app.js

This setting is also described in the Node JS CLI documentation

Male answered 13/11, 2022 at 5:35 Comment(0)
A
0

Start your node.js app with --inspect option. After that, you can visualize and profile your application with the new Node.js Chrome Debugging.

enter image description here

Amentia answered 11/8, 2023 at 23:34 Comment(0)
J
0

You can minify your sourcecode via esbuild like:

npm i -g esbuild

esbuild
  --bundle ./start.ts \
  --outfile=./dist/start.js \
  --platform=node \
  --minify

and then start your server with the outfile instead. This can cut down on memory consumption significantly, as node.js holds on to all the source code it required as strings in memory. If your script requires a bunch of files, also in node_modules, this can consume quite some RAM.

Jaynajayne answered 26/7, 2024 at 8:8 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.