Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to prevent memory leaks in a streaming http/s server in node.js?

How to prevent memory leaks in a streaming http/s server in node.js?

Problem

I built a Streaming Https Server that polls a back-end service and writes the data to the http client if it is available. The code for a specific https request looks like this somehow:

// check for new stuff periodically
var timer = setInterval( function() {
                   var resp = getResponseObject();
                   response.write(resp + "\n\r");
               }, 500);

// stop looping when the client disconnects
request.on('close', function() {
             clearInterval(timer);
             return;
             });

When the client disconnects, the time-out gets cleared and the loop stops. But will this on-close event always be triggered? Also on a not-so-clean client disconnect? I worry about leaving loops behind for connections that are no longer in place. Any idea if this is safe? Other approaches?

Thanks!

Problem courtesy of: pors

Solution

I don't believe you need to worry about "unclean" disconnects -- when the client machines are abruptly removed from the network, your server will eventually get either TCP FIN packets or ICMP Destination Unreachable messages, which will trigger the close event in your server and allow you to clean up.

What is probably more resource intensive would be hundreds or thousands of clients sending and receiving data so slowly that you wind up running out of file descriptors for all the network sockets. A client that connects with ridiculously low MTU could force your application to dribble megabytes down a connection in 100-byte chunks for days or weeks.

Solution courtesy of: sarnold

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to prevent memory leaks in a streaming http/s server in node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×