Home > Software engineering >  Does nodejs http/s module use worker threads to listen for a request?
Does nodejs http/s module use worker threads to listen for a request?

Time:01-31

Had some conversation with a co-worker and it went down a rabbit hole of threads and i was questioning if something like expressjs, which uses the nodejs built in https module, uses workers to listen for connections for each network request or some other design.

Would anyone know how normally http type request wait for connections? threads? workers?

CodePudding user response:

Does nodejs http/s module use worker threads to listen for a request?

No, it does not. Nodejs is an event driven system. Wherever possible, it uses an underlying asynchronous capability in the OS and that is what it does for all TCP/UDP networking, including http.

So, it uses native asycnhronous features in the OS. When some networking event happens (such as an incoming connection or an incoming packet), then the OS will notify nodejs and it will insert an event into the event queue. When nodejs is not doing something else, it will go back to the event queue and pull the next event out of the event queue and run the code associated with that event.

This is all managed for nodejs by the libuv library which provides the OS compatibility layer upon which nodejs runs (on several different platforms). Networking is part of what libuv provides.

This does not involve having a separate thread for every TCP socket. libuv itself uses a few system threads in order to do its job, but it does not create a new thread for each TCP socket you have connected and it's important to note that it is using the native asynchronous networking interfaces in the operating system (not the blocking interfaces).

The libuv project is here (including the source) if you want to learn more about that specific library.

libuv does use a thread pool for some operations that don't have a consistent, reliable asynchronous interface in the OS (like file system access), but that thread pool is not used or needed for networking.

There are also a zillion articles on the web about how various aspects of the nodejs event loop work, including some in the nodejs documentation itself.

  • Related