Sunday, November 21, 2010

Taking Baby Steps with Node.js – Threads vs. Events

In a previous blog post, I provided a shallow introduction to Node.js. I also mentioned where you can find more information on how to get it installed on Windows as well as how to install a seemingly popular package manager in the JavaScript community called Npm.
In the mean time, I’ve started to get a more clearer view on the general concepts on which Node.js is based on, as well as the kind of applications that can be built using this server-side platform. The more I read and learn about Node.js, the more I come to the conclusion that it is very much targeted towards building real-time applications. Google Wave, Friendfeed and most recently Facebook are popular examples. You can also read this article to learn more about other examples of real-time web applications.
As I briefly mentioned in the previous blog post, Node.js makes heavy use of JavaScript’s event-based style of programming which lies at the heart of it’s capabilities for building real-time applications. This event-based model is a completely different way of thinking compared to the thread-based model that we’ve been so accustomed to over the past couple of years. ASP.NET Web Services or WCF services for that matter are excellent examples of the thread-based model. Every time a message comes in, these frameworks spawn a new thread or take one from the thread pool in order to handle this request. There’s nothing wrong with this approach. In fact, this thread-based model makes perfect sense for many of the scenarios out there. But generally not for real-time applications that usually require long-lived connections.
In the thread-based model, most of the threads spend a lot of their time being blocked; waiting for I/O operations like executing queries against a database, calling another service or writing to a file on disk. These are expensive operations that usually take longer to complete compared to in-memory operations. When having large amounts of traffic, you can’t afford to have threads blocking for long periods of time. Otherwise you’ll be hitting the maximum number of available threads rather sooner than later.

Read more: <elegantc*de>