Ankit Vaghela Ankit Vaghela - 4 months ago 12x
Node.js Question

CPU goes 100% due to so many http call in node js code. How I will optimize that code?

I am putting some sample code here from my application.
I am calling update data function. In one minute I have 150 calls of http.
So due to this code my cpu goes 100% and I want to optimize this code.
Wanted to fix performance issue of this node js code.

function doSynchronousLoop(data) {

if (data.length > 0) {

var loop = function(data, i) {

if (++i < data.length) {

var req = httpcall.request('http://myserverip/path', function(res) {
res.on('data', function (chunk) {

loop(data, i);
}, 50);



req.on('error', function(err) {
console.error('error: ' ,err.stack.split("\n"));


allData= [];


loop(data, 0);
allData= [];

function updateData(allData){


Your callback calls a new HTTP request on every "data" event. Unless the get request is really short, it'll fire multiple times, so several more http.get calls will be fired BEFORE the first one fires its end request. So, if you change your callback to fire on the end event instead of the data event, it will behave synchronously.