Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Functions [JavaScript / Node.js] - HTTP call, good practices

Tags:

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?

like image 312
tommy vercetti Avatar asked Dec 20 '17 12:12

tommy vercetti


1 Answers

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.

like image 125
nelak Avatar answered Sep 20 '22 13:09

nelak