3 Intro to Node.js
At the end of this section you’ll have a basic understanding of Node.js®, Promises, and basic async concepts.
- What is Node.js
- Events, Threads, and Concurrency
- Why Node?
What is Node.js? An Introduction.
Events, threads, concurrency, what?
The traditional concurrency model is to spawn a new child process to serve each connection. The parent process will remain available for listening to new connections. Each new connection results in the creation of a child process dedicated to it.
This gets expensive.
The same code is running in each process (or each thread) but from the OS perspective they are different tasks. Multi-tasking is achieved through CPU-time multiplexing also known as time-sharing.
And it gets worst if the processes need to wait for something.
Wait & Blocking
There are many occasions on which a process or a thread will have to wait. It will wait for some external events to be completed before they can continue. Such occasions are IO. Blocking IO (or synchronous IO) will tie up the system resources as the waiting processes cannot be used for some other action.
However the system (your OS) is not stuck while IO is happening. The system is going to interrupt the process waiting for an IO operation, allowing the CPU to be used by another process.
The alternative is to use an event-driven model. This has proved useful in many products such as Nginx, Twisted, or EventMachine.
In an event model, everything runs in one process, one thread. Instead of spawning a new process/thread for each connection request, a event is emitted and the appropriate callback for that event is invoked.
In event-driven model, all the events are treated by a gigantic loop know as the event-loop.
- Requests, etc. arrive
- Added to the event loop
- Each event registers a callback, and executes it operation.
- Operation completes and triggers the callback.
- Next event is processed.
Imagine a king with servants.
Every morning all the servants line up, one at a time they come into his throne room. They report on what they’ve done, sometimes the king gives them more to do. Always one at a time, so the king can focus.
Why is PHP & Drupal bad at handling concurrency?
Drupal has a large memory foot print. You might need to allocate 100mb just to serve some JSON.
However, everything happens in order. Each IO operation blocks all subsequent ones. A 100ms request to the DB will block process execution.
- Rapid prototyping
- API Glue
- Queue'ish stuff
- Message passing