0

I know very little about nodejs. All I know is, that it works upon a single thread model, which switches to multiple threads for I/O tasks. So for example,

Request A ----> nodejs (Single Thread)

// Finds out that it the requires requires I/O operation

nodejs ----> underlying OS (Starts An Independent Thread)

// nodejs is free to serve more requests

Does this mean for 1000 concurrent requests, there will be a request that will be handled after all 999 requests are handled? If yes, it seems to be an inefficient system! I would term apache running php to be better suited (in the above case). Apache with PHP keeps the ability to launch 1000 concurrent threads and thus no processing queue and zero wait time.

I might be missing an important concept here, but is it really the way nodejs works?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

1

Node.js is based on the event loop programming model. The event loop runs in single thread and repeatedly waits for events and then runs any event handlers subscribed to those events. Events can be for example

timer wait is complete next chunk of data is ready to be written to this file theres a fresh new HTTP request coming our way All of this runs in single thread and no JavaScript code is ever executed in parallel. As long as these event handlers are small and wait for yet more events themselves everything works out nicely. This allows multiple request to be handled concurrently by a single Node.js process.

(There's a little bit magic under the hood as where the events originate. Some of it involve low level worker threads running in parallel.)

In this SQL case, there's a lot of things (events) happening between making the database query and getting its results in the callback. During that time the event loop keeps pumping life into the application and advancing other requests one tiny event at a time. Therefore multiple requests are being served concurrently.

Please look into this article Article