Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Node.js, is writing to a TCP connection blocking?

I have a node.js process which has several entry points, including a tcp server, websocket server, and named pipe server. I am wondering if any interactions with these connections will be blocking.

Example: for a given connection, if there isnt anything in the buffer because the client didnt send anything yet, will this block all other code from running in the Node.js process until the client sends data?

My understanding is that node will offload I/O operations like these to the system kernel, so it wouldnt hold up the call stack.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Most likely I am getting something wrong here so please let me know! Thank you.

>Solution :

This is a very interesting question!

I would recommend you to start by understanding what the event loop is (reading https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/) and then understanding the difference between blocking & non-blocking calls (reading https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/).

Now we’ll know a bit more about how node works behind the scenes, what blocking and non-blocking operations are and therefore we’re equipped to understand and spot what will or won’t block our loop.

Will a TCP connection block it? There may be a module out there that will, it really depends on each case, library, implementation.

Regarding TCP on the "native" implementation, if you’re using the node.js Net module you’ll find that it is a:

module [that] provides an asynchronous network API for creating stream-based TCP or IPC servers

Therefore, in principle, it will be non-blocking.

As an example, if we look at the socket.write documentation itself, we’ll find that this function:

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. ‘drain’ will be emitted when the buffer is again free.

Therefore it should not block.

PS: Another interesting article on this subject is https://medium.com/@hnasr/when-nodejs-i-o-blocks-327f8a36fbd4

Happy reading, and keep an eye out for blocking function calls!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading