From my Azure Function (which runs in Node.js, triggered by EventHub message) I would like to make a post request to some external page. Something like:
module.exports = function (context, eventHubMessages) {
var http = require("http");
context.log('JavaScript Function triggered by eventHub messages ');
http.request(post_options, function(res){
...
})
context.done();
The code above will probably work but I have a doubt if that is not an antipattern.
Imagine situation when there are thousands of functions triggered in short period of time - for each execution we would need to create an HTTP client and create a connection...
From short research I have found some solution proposal for C# Azure Functions: https://docs.microsoft.com/en-us/azure/architecture/antipatterns/improper-instantiation/ which uses static HttpClient class.
I have a question, is there any similar approach in Node.js Azure Function? Or any other way to avoid this problem, to share an object between Node.js Azure Function executions?
If thousands of functions triggered in short period of time you should limit the sockets by modifying the http.globalAgent
or by passing an instance of a new Agent
An Agent is responsible for managing connection persistence and reuse for HTTP clients. It maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. Whether it is destroyed or pooled depends on the keepAlive option.
Source: https://nodejs.org/api/http.html#http_class_http_agent
http.globalAgent.maxSockets
defaults to infinity so unless you limit this value your function will run out of sockets and you'll see your requests start to fail.
Additionally if you are planning on connecting to the same host you should enable keep-alive on the globalAgent/Agent
to enable pooled connections.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With