Question:
I have a Node.js app running on Ubuntu 14 on Amazon EC2.
I want to send an email in case that the memory usage reaches a specific size.
I know that PM2 exposes an API that allows, among other things, restarting the app whenever a certain amount of memory usage is reached. Now I don’t want to restart the app at this point, but just to get a notification about it, and doing with it whatever I want (in my case, sending an email).
How can I do it either with PM2 or any other free tool?
Answer:
To have a concrete implementation as matthewmatician mentioned.
You can easily do this all within node by periodically checking your memory usage: https://nodejs.org/api/process.html#process_process_memoryusage. If this is a long-running server, check it every hour or so. Then just fire off an email with a package like nodemailer if the memory reaches a certain threshold.
I like PM2, yet I was wondering if it could be done without.
As noted here, RSS (Resident Set Size) is the full memory usage of the process, this includes all memory usage of the shared memory. RSS can therefore be considered inacurate to be taken as the memory usage of a single process, since the shared memory is also used by other processes. Therefore PSS exists, which divides the shared memory over all other processes used.
I suppose we want to know the PSS value if we want to display the most accurate usage of memory by the node process. However, some person did mention PSS is more important for huge amount of fork processes, such as an Apache server (and thus a lot of shared memory).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var hour = 3600*1000; var checkMemory = function() { // Retrieves the memory usage var memory = process.memoryUsage(); var rss_memory_in_bytes = m.rss; var rss_memory_in_megabytes = m.rss / (1024**2); if (rss_memory_in_megabytes > 50) { // More than 50 megabytes RSS usage, do something doSomething(); } } var doSomething = function() { // For instance sending an email } // Check the memory usage every hour setInterval(checkMemory, hour); |
— UPDATED —
If there is more heap storage required, the Node process will attempt to allocate this memory. This allocation is done automatically. When successfull the heap storage increases and the rss as well. The heapUsage and heapTotal can therefore be neglected in our case.
There are ways of setting a memory limit, but we are interested at checking for a limit. I think it is reasonable to check for the amount of free system memory left. Yet, this has nothing to do with the actual memory usage of the Node process itself and would require a different threat on how to check for free system memory with a Node script.