Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a simple way of counting requests that the sever is serving?

Tags:

node.js

In a simple nodejs server I want to track how many requests per second it is serving across all clients.

Should I be using a database? Or will that cause locking of some sort?

like image 548
dsuma Avatar asked Mar 13 '23 09:03

dsuma


1 Answers

If you just want to know instantaneously, how many requests have been served in a last time period, you can just create your own in-memory data structure that keeps track of the data necessary to calculate that. I see no reason to use a database for this:

If you are using Express, you can just make the first middleware that you register be one that collects the request data:

// collect request info
var requests = [];
var requestTrimThreshold = 5000;
var requestTrimSize = 4000;
app.use(function(req, res, next) {
    requests.push(Date.now());

    // now keep requests array from growing forever
    if (requests.length > requestTrimThreshold) {
        requests = requests.slice(0, requests.length - requestTrimSize);
    }
    next();
});

Now, you have an array of data that logs the time of your last N requests and you can calculate recent requests/second over any recent time period.

Just make sure this middleware is installed first so it is processed before any other middleware that might actually end the request (so it is always called).

Of course, if you want to collect more info than just the time of the request, instead of just pushing a time stamp into the array, you could create an object and push the object into the array. The object could have a timestamp property and any other properties you wish (URL of request, type of request GET, POST, etc..., IP of request, etc...).


Then, if you want to know how many requests in the last minute, you could calculate that like this:

app.get("/requests/minute", function(req, res) {
    var now = Date.now();
    var aMinuteAgo = now - (1000 * 60);
    var cnt = 0;
    // since recent requests are at the end of the array, search the array
    // from back to front
    for (var i = requests.length - 1; i >= 0; i--) {
        if (requests[i] >= aMinuteAgo) {
            ++cnt;
        } else {
            break;
        }
    }
    res.json({requestsLastMinute: cnt});
});
like image 118
jfriend00 Avatar answered May 02 '23 10:05

jfriend00