I have a node.js backend that connects to external service via HTTP request.
I am using the node.js HTTP to manage my requests. My question is about how to properly use Node.js http Agent with the keep-alive option.
The official documentation explains that we should create a new Agent and pass it to the request. This is the same for all the examples I found. They all do something like this:
const http = require("http");
const agent = new http.Agent({
keepAlive: true
});
const options = {
host: 'myserver.com',
port: 80,
path: '/',
method: 'GET',
agent: agent,
};
const req = http.request(options, (res) => {
console.log("StatusCode: ", res.statusCode);
});
Since my agent has keepAlive turned on I should create only one instance of the agent, save it somewhere (static?) and reuse it everytime I do a request to that service. In other words, I should only call new http.Agent one time when my backend is created and keep using the same instance, otherwise I would be created a new agent for every request. Is this correct? is there a better way of keeping the agent instance other than making it global or static?
I don't know if I'll be able to get an answer here or better as AWS directly, but let's say my backend is a AWS lambda fucntion, how can they share Agents between invocations, as lambdas are short lived, does it even make sense to have keepAlive for that use case?
Thank you for any clarification.