DEV Community

Faheem 😒
Faheem 😒

Posted on

Saw a badly written NodeJS code causing performance issues

Note: I did not solve the issue. Sharing because I think it may be interesting.

Story

Some weeks ago someone contacted me to fix a performance issue. They were getting a response time of around a second on their production server, and sometimes, it worked fine.

The code worked perfectly on the local machine.

I took a look at the code and turns out it is badly written and has a callback hell. 20 levels of nested database calls in one place.

Possible Cause:

When you make calls to any services, such as the DB, it takes time. On localhost, since the database is on the same machine, the latency is almost 0.

However, on a production server, each database call will have a higher latency, which depends on the configuration.

Even if a single call has a latency of 50 ms (just an example), it will take 1000 ms (a second) for 20 DB calls.

And since all these calls are nested (one after another), they are not benefiting from the async nature of NodeJS.

Possible Solution:

While I did not solve the issue, I would have been solved the issue by:

  1. Getting rid of the callback hell.
  2. Avoiding unnecessary DB calls.
  3. Diving the code in smaller functions, so they can work independently.

Batch updates and caching the data may help improve the performance too.

Personally, the code reminded me of old-time when I was an intern and was making and solving the same mistakes. 😅

Top comments (0)