6

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://learn.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?

2
  • 2
    I don't think that patterns from C# apply to Node functions. Node should manage connections for you. I would move require out of function, and context.done inside the callback. Commented Dec 20, 2017 at 13:36
  • Can you tweak the other end to accept websockets? Because that's your best plan, all else makes more or less a poor workaround if you're talking hundreds of TCP handshakes per second. Commented Dec 22, 2017 at 0:05

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.