Why a single "while" loop can freeze Node.js for every user in the world.
Node.js (and the browser) runs on a Single-Threaded Event Loop. Think of it like a single waiter in a restaurant. The waiter can take hundreds of orders quickly (asynchronous operations like DB queries) because he hands the ticket to the kitchen and immediately returns to the dining room. But if the waiter decides to cook a steak himself (a synchronous, CPU-heavy task like parsing a huge JSON file or calculating cryptography), he stands at the stove for 5 seconds. During those 5 seconds, the waiter is "Blocked". No other tables can order, and the entire restaurant freezes.
Anything that requires heavy CPU computation (Regex parsing, sorting huge arrays, image processing, JSON.parse on a 50MB string) blocks the event loop. To fix it, you must move that heavy computation entirely out of the Node.js process using a Worker Thread or a separate background microservice.
// THE BAD WAY: Blocks the Event Loop
app.post('/upload', (req, res) => {
// This takes 4 seconds of pure CPU time.
// During this time, NO ONE else can load the website!
const image = processImageSync(req.body);
res.send(image);
});
// THE GOOD WAY: Offload to a Worker or Background Queue
app.post('/upload', async (req, res) => {
// Send to a Redis Queue. The Event Loop is instantly free!
await queue.add('image-processing', req.body);
res.send({ status: 'Processing in background' });
});
Moving CPU-heavy tasks to Worker Threads or Background Queues adds architectural complexity. You now have to manage message brokers (like Redis or RabbitMQ) and handle scenarios where the background job fails asynchronously (meaning you have to build webhooks or websockets to notify the user when the job finishes).
*Sync. For example, using fs.readFileSync('/big.csv') in a web endpoint will freeze the server for everyone while the file is read. Always use fs.readFile() with callbacks or Promises.