Harith Zahid

I/O Operations vs CPU Computations

I/O Operations (Async Works Here ✅)

These involve waiting for something external to Node.js:

File System:

await fs.readFile('file.txt');      // ✅ Truly async
await fs.writeFile('file.txt', data); // ✅ Truly async

Network:

await fetch('https://api.com');      // ✅ Truly async
await db.query('SELECT * FROM users'); // ✅ Truly async
const response = await axios.get(url); // ✅ Truly async

Timers:

await new Promise(resolve => setTimeout(resolve, 1000)); // ✅ Truly async

Other:

await crypto.randomBytes(256);       // ✅ Truly async (uses OS)

Key Trait: The operation happens outside the JavaScript engine. Node.js delegates the work and gets notified when it's done.

CPU Computations (Async Doesn't Help ❌)

These involve actively calculating on the main thread:

Math Operations:

await fibonacci(40);                 // ❌ Still blocks!
await complexCalculation(data);      // ❌ Still blocks!

Data Processing:

await JSON.parse(hugeString);        // ❌ Still blocks!
await data.sort();                   // ❌ Still blocks!
await heavyRegex.test(longString);   // ❌ Still blocks!

Crypto (synchronous versions):

crypto.pbkdf2Sync(password, salt, 100000, 64, 'sha512'); // ❌ Blocks!

Key Trait: The CPU is actively working, not waiting.

Quick Test: "Is Node.js doing the work, or waiting?"

  • Waiting = I/O = async helps ✅
  • Doing = CPU = async doesn't help ❌

Example: The Fibonacci Problem

const express = require('express');
const app = express();

// CPU-intensive function
function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

// This BLOCKS the entire server for ~5 seconds
app.get('/heavy', async (req, res) => {
  const result = await fibonacci(40); // async/await doesn't help!
  res.json({ result });
});

app.get('/light', (req, res) => {
  res.json({ message: 'Fast response' });
});

app.listen(3000);

Problem: When /heavy is called, the entire server freezes. The /light endpoint won't respond until fibonacci is done.

Why async/await doesn't help: fibonacci is pure CPU computation. There's nothing to "wait" for - the CPU is busy calculating.