Saturday, January 12, 2013

NodeJS Event Loop Explained*

Event Loop A programming construct that waits for and dispatches events or messages in a program.

Traditional Muti-Threaded Model
  • N Worker thread/process
  • Each incoming connection handed to a worker, that worker/ thread is blocked until completion of operations. Examples: File I/O, DB I/O, Network I/O …
Blocking  = Waste of resources
NodeJS Event Loop
  • Asynchronous
  • Non-blocking I/O
Instead of performing I/O in our code, we dispatch I/O events to Node’s event loop and let it handle process optimization, threads and concurrency
Let’s review a typical example with 3 clients making calls to webserver and in turn to database.
As, shown in image, with traditional multi-threaded system, there is a significant amount of blocking happening.
On other-hand single threaded operation on NodeJS server runs asynchronously and efficiently.
* This post uses excerpts from Wikipedia and Dr. Constantine Aaron Cois’s articles