6/29/2023 0 Comments Node js thread sleep![]() Looking for stuff like “node async block event loop” one of the first results is this official Node.js. When something similar happened to me, I turned to Google for answers. How can we unblock our computation without such a penalty? ![]() ![]() Why did the setTimeout() add such a massive performance cost? Why was the async code blocked without the setTimeout() call? Only by reducing the number of iterations from 10⁷ to 10⁵, it completed after 2:23 minutes! (If you wonder, passing 1, instead of 0, as the delay parameter to setTimeout makes no difference - more on this later) ![]() Unfortunately, the cost of this solution is too high: we can see that the CPU is at about ~10%, so it seems it doesn’t work hard enough on the computation, which practically takes forever to complete (didn’t have enough patience to see it happen). So let’s start with a simple Express server:įinally, the server remains responsive during the heavy computation. You can play with the code bellow by cloning First, let’s block the Node.js Event-Loop!Įxamples below use Node 10.9.0 on an Ubuntu 18.04 VM with 4 cores, running on a MacBook Pro 2017 I’ll do my best to share the various questions I had, and share the answers I’ve found in various great articles, some fun experimentation and digging. Plenty of valuable information already exists about the Node.js Event-Loop, but it took me time find the answers for the specific questions I wanted to ask. I believe it’s important that as many Node developers will have this knowledge too - which led me to writing this article. When I tried to fix the situation, I realized how little I actually knew about the event-loop behavior and gained some realizations that at first surprised me and some fellow developers I shared this with. I recently stumbled upon a real event-loop blocking scenario here at Snyk. This is a known and challenging limitation of Node and is also nicely explained in the docs. There is a single main thread (a.k.a the Event-Loop) that executes all these callbacks, and thus the callbacks should be quick to complete as all other pending callbacks are waiting for their turn. A typical Node.js app is basically a collection of callbacks that are executed in reaction to various events: an incoming connection, I/O completion, timeout expiry, Promise resolution, etc.
0 Comments
Leave a Reply. |