Victor Pudeyev
Victor Pudeyev

Reputation: 4539

How do I prevent node.js from making future connections?

I'm looking to do the following: under load, when a certain threshold is reached, to disallow future connections, wait for the server to process all existing connections, reset the server, and allow future connections. I thought that setting http.maxSockets=0 or http.maxConnections=0 would let me not accept connections, but that doesn't seem to be the case.

Is there a way in node.js (or express.js) to disallow future connections?

Upvotes: 1

Views: 74

Answers (1)

c1moore
c1moore

Reputation: 1867

Looking at the code for Node's _http_agent.js, it looks like if the value for maxSockets is set to 0, the default value is used instead.

I will assume since you said "or express.js" you are using the Express.js middleware already. The Node-only alternatives are very straight forward for these solutions.

Solution 1

You could just set maxConnections to your threshold for connections:

var app = require('express');
var server = app.listen(80);    //Set up server using whichever port you want
server.maxConnections = thresholdConnections;

The server will now automatically reject connections when the threshold is reached. The advantage is it happens automatically, the disadvantage is it seems you want to completely finish processing all requests before listening for new ones at all.

Solution 2

The other solution would be to close your server. You can do so as follows:

var app = require('express');
var server = app.listen(3000);    //Set up server using whichever port you want

Later, once you have detected that your threshold for connections has been reached, you simply call server.close().

Once you finish processing all requests and sent your responses, you can start listening for more requests again the same way you originally started the server (i.e. app.listen(3000)).

Upvotes: 1

Related Questions