Sujith S Manjavana
Sujith S Manjavana

Reputation: 1586

node.js CPU usage spikes

I have an express.js app running in cluster mode (nodejs cluster module) on a linux production server. I'm using PM2 to manage this app. It usually uses less than 3% CPU. However, sometimes the CPU usage spikes up to 100% for a short period of time (less than a minute). I'm not able to reproduce this issue. This only happens once a day or two. Is there any way to find out which function or route is causing the sudden CPU spikes, using PM2? Thanks.

Upvotes: 1

Views: 3140

Answers (2)

BKs0Lk1
BKs0Lk1

Reputation: 306

i think have some slow synchronous execution on some request in your application.

  • add log every request income on middleware and store to elastic search and find what request have long response time or use newrelic (easy way but spend more money).
  • use blocked-at to find slow synchronous execution if detect try to use worker threads or use lib workerpool

Upvotes: 3

Ibrahim shamma
Ibrahim shamma

Reputation: 418

My answer is based purely on my experience with the topic

  1. Before going to production make local testing like:
  • stress testing.
  • longevity testing.

For both tests try to use tool like JMeter where you can put your one/multiple endpoints and run loads of them in period of time while monitoring CPU & MEMORY Usage.

  1. If everything is fine, try also to stop the test and run the api manually try to monitor its behavior, this will help you if there is memory leak from the APIs themselves
  2. Is your app going through .map() , .reduce() for huge arrays?
  3. Is your app is working significantly better after reboot? if yes, then you need to suspect that the express app experiencing memory leak and Garbage collector trying to clean the mess.
  4. If it's possible, try to rewrite the app using fastify, personally, this did not make the app much faster, but able to handle 1.5X more requests.

Upvotes: 1

Related Questions