Search code examples
node.js

When should I use (or not use) the keepAlive option of the Node.js http Agent?


I recently had a problem with a Node.js http client in my application that was making so many requests to a remote API that it was exhausting the operating system's available ephemeral ports, triggering connect EADDRNOTAVAIL errors from some requests. I eventually discovered that I could eliminate this problem by making the requests using an http.Agent with options keepAlive: true and maxSockets set to some reasonable value. E.g.:

new http.Agent({keepAlive: true, maxSockets: 25})

This change seems to have eliminated my EADDRNOTAVAIL errors without any negative effects, but I'm wary of it because the keepAlive option defaults to false (and maxSockets defaults to Infinity). The fact that the default is false suggests that there is some cost or downside to setting keepAlive: true. I'd like to understand what the downside is so that I can understand in what situations I should turn keepAlive on, and when I should leave it off.


Solution

  • Moving the conversation in comments to an answer to close out the question.

    The keepAlive reuses sockets instead of instantiating new ones for every request, the "downside" here would be that the sockets will be around even after you have finished the requests and continue communicating over the network.

    This "downside" is actually the functionality you are looking for. Since closing them then reopening them have a negative impact, you want to keep these communication channels open.

    To further put someones (who has the same question) mind at ease, as @mactyr noted in the comments above (and based on this how-to blog post), keepAlive is non-invasive and can be turned on without the risk of doing something wrong.