惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
量子位
小众软件
小众软件
C
Cybersecurity and Infrastructure Security Agency CISA
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tenable Blog
V
Vulnerabilities – Threatpost
Know Your Adversary
Know Your Adversary
T
Threat Research - Cisco Blogs
Latest news
Latest news
Spread Privacy
Spread Privacy
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
T
Tor Project blog
Hacker News: Ask HN
Hacker News: Ask HN
V2EX - 技术
V2EX - 技术
T
The Exploit Database - CXSecurity.com
博客园 - 三生石上(FineUI控件)
K
Kaspersky official blog
Cyberwarzone
Cyberwarzone
博客园 - 叶小钗
博客园 - 聂微东
Last Week in AI
Last Week in AI
爱范儿
爱范儿
腾讯CDC
博客园 - Franky
美团技术团队
J
Java Code Geeks
O
OpenAI News
L
Lohrmann on Cybersecurity
Simon Willison's Weblog
Simon Willison's Weblog
有赞技术团队
有赞技术团队
T
Threatpost
G
GRAHAM CLULEY
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
I
Intezer
N
News and Events Feed by Topic
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
The Blog of Author Tim Ferriss
S
Security @ Cisco Blogs
Forbes - Security
Forbes - Security
N
News | PayPal Newsroom
Stack Overflow Blog
Stack Overflow Blog
Scott Helme
Scott Helme
H
Hacker News: Front Page
Cloudbric
Cloudbric

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Blocking vs Non-Blocking Code in Node.js
Akash Kumar · 2026-06-28 · via DEV Community

"Blocking code makes your server wait. Non-blocking code makes your server work while it waits."


Introduction

You've heard that Node.js is fast. But Node.js doesn't make your CPU faster or your database queries instant. What it does is eliminate something far more wasteful than slow code — idle waiting.

Most performance problems in web servers aren't caused by computation being too slow. They're caused by threads sitting frozen, doing absolutely nothing, while they wait for a file to load or a database to reply. Node.js is built from the ground up to never let that happen.

To understand how, you need to understand the difference between blocking and non-blocking code — and why that difference changes everything about how a server handles real-world load.


1. What Blocking Code Means

Blocking code is code that prevents anything else from executing until it finishes.

When a blocking operation runs, the thread freezes. It starts the operation, then stands there doing nothing — completely locked — until the result comes back. Only then can the next line of code run.

const fs = require("fs");

// BLOCKING
const data = fs.readFileSync("users.json", "utf8"); // thread frozen here
console.log("File loaded:", data);
console.log("This runs AFTER the file is fully loaded");

The readFileSync call tells Node: "Read this file. Don't do anything else until you're done." The thread sits completely still — not processing other requests, not running other callbacks — just waiting for the operating system to hand back the file contents.

The Queue Analogy

Blocking code is like a bank teller who only handles one customer at a time — and spends most of that time staring at the printer waiting for paperwork to come out. The teller is occupied but not productive. Everyone in line waits for the printer, not the teller.

What Blocking Looks Like on a Thread

Thread executing blocking code:

Time ───────────────────────────────────────────────────────►

  [Start readFileSync]
  │
  │  ← thread is FROZEN here
  │  ← cannot accept new requests
  │  ← cannot run any other code
  │  ← just... waiting
  │
  [OS returns file data]
  │
  [console.log runs — finally]

Everything halts. The thread cannot do anything else during that gap — no matter how long it takes.


2. What Non-Blocking Code Means

Non-blocking code starts an operation, registers a callback (or returns a Promise), and immediately moves on to the next piece of work. When the operation finishes, Node.js comes back and runs the callback.

const fs = require("fs");

// NON-BLOCKING
fs.readFile("users.json", "utf8", (err, data) => {
  // This runs LATER — when the file is ready
  if (err) throw err;
  console.log("File loaded:", data);
});

// This runs IMMEDIATELY — doesn't wait for the file
console.log("Continuing while file loads...");

// Output order:
// Continuing while file loads...    ← runs first
// File loaded: { ... }              ← runs when OS is ready

The thread hands off the file-read task to the operating system, registers the callback, and immediately moves forward. When the OS signals the file is ready, Node.js queues the callback and runs it on the next available tick.

The Same Thread, But Never Idle

Thread executing non-blocking code:

Time ───────────────────────────────────────────────────────►

  [Call readFile → hand off to OS]
  [Register callback]
  [Continue to next line — runs IMMEDIATELY]
  [Handle other requests]
  [Run other callbacks]
                         [OS signals: file ready]
                         [Callback fires — process data]

The thread is never frozen. It keeps moving. The slow work happens off to the side and the thread is notified when it's done.


3. Why Blocking Slows Servers

A single user triggering a blocking read is a minor nuisance. A hundred concurrent users doing it is a disaster.

Blocking Under Load

When your server uses blocking I/O, every request that triggers a blocking operation freezes the thread handling it:

BLOCKING SERVER — 4 requests arrive simultaneously

Time ───────────────────────────────────────────────────────►

Req A: [── read file ──][respond]
Req B:                  [── read file ──][respond]
Req C:                                  [── read file ──][respond]
Req D:                                                  [── read file ──][respond]

Total time = sum of all waits.
Under 100 concurrent requests: catastrophic queue buildup.

Each request waits for the one before it. As traffic grows, response times grow linearly. At enough concurrency, requests time out before they're even handled.

The Thread Pool Trap

Traditional multi-threaded servers (PHP, Java out of the box) sidestep this by giving each request its own thread. That way, each blocking request only freezes its own thread. But threads are expensive:

Traditional server under 1,000 concurrent requests:
→ 1,000 threads spawned
→ ~1–2 GB RAM just for thread stacks
→ constant OS context switching between them
→ diminishing returns as concurrency grows beyond the pool size

Node.js sidesteps this entirely — one thread, never blocking, handles thousands of connections.

Non-Blocking Under Load

NODE.JS NON-BLOCKING — same 4 requests

Time ───────────────────────────────────────────────────────►

Thread: [A:start][B:start][C:start][D:start][A:cb][B:cb][C:cb][D:cb]
              ↓       ↓       ↓       ↓
             OS      OS      OS      OS   ← all 4 reads run simultaneously

Total time ≈ time of the SLOWEST single read, not their sum.

All four I/O operations run concurrently in the background via libuv. The thread registers all four, keeps moving, and handles callbacks as each one completes.


4. Async Operations in Node.js

Node.js gives you three patterns for writing non-blocking code, each building on the previous.

Pattern 1: Callbacks

The original Node.js pattern. Pass a function as the last argument — it's called when the async operation completes.

const fs = require("fs");

fs.readFile("config.json", "utf8", (err, data) => {
  if (err) {
    console.error("Read failed:", err.message);
    return;
  }
  const config = JSON.parse(data);
  console.log("Config loaded:", config);
});

console.log("Server starting..."); // runs immediately, before the file loads

The Node.js callback convention: The first argument is always the error (null on success), the second is the result. You'll see this pattern throughout Node.js core modules.

Pattern 2: Promises

Promises represent a future value and are cleanly chainable. fs.promises gives you Promise-based versions of all file system operations.

const fs = require("fs").promises;

fs.readFile("config.json", "utf8")
  .then(data => {
    const config = JSON.parse(data);
    console.log("Config:", config);
  })
  .catch(err => {
    console.error("Read failed:", err.message);
  });

console.log("Server starting..."); // still runs immediately

Pattern 3: async/await (preferred)

async/await is syntactic sugar over Promises. It makes async code look synchronous — without actually blocking.

const fs = require("fs").promises;

async function loadConfig() {
  try {
    const data = await fs.readFile("config.json", "utf8");
    const config = JSON.parse(data);
    console.log("Config:", config);
    return config;
  } catch (err) {
    console.error("Read failed:", err.message);
  }
}

loadConfig();
console.log("Server starting..."); // still runs immediately

await looks like it's waiting — but it only suspends the async function itself, releasing the thread to do other work. When the Promise resolves, execution resumes exactly where it paused.

The Critical Difference at a Glance

// BLOCKING — thread frozen for the entire read duration
const data = fs.readFileSync("users.json", "utf8");
processData(data);
handleNextRequest();   // waits for everything above to finish

// NON-BLOCKING — thread free the entire time
fs.readFile("users.json", "utf8", (err, data) => {
  processData(data);   // runs when file is ready
});
handleNextRequest();   // runs IMMEDIATELY, in parallel with the read


5. Real-World Examples

File Read: Sync vs Async in an Express Route

const express = require("express");
const fs = require("fs");
const fsPromises = require("fs").promises;
const app = express();

// BLOCKING — freezes the entire server for every single request
app.get("/config-bad", (req, res) => {
  const data = fs.readFileSync("config.json", "utf8"); // server stalls here
  res.json(JSON.parse(data));
});

// NON-BLOCKING — correct approach
app.get("/config-good", async (req, res) => {
  try {
    const data = await fsPromises.readFile("config.json", "utf8");
    res.json(JSON.parse(data));
  } catch (err) {
    res.status(500).json({ error: "Failed to load config" });
  }
});

With the blocking version, 50 simultaneous requests to /config-bad form a strict queue — each one waiting for the previous file read to complete. With the non-blocking version, all 50 reads start immediately and resolve as the OS finishes each one.

Database Calls: The Most Common Real-World Case

Every database query is I/O. Blocking on a DB call in a request handler is one of the most common and costly beginner mistakes.

// BLOCKING DB CALL (conceptual — good DB libraries are always async)
app.get("/users-bad/:id", (req, res) => {
  // Server frozen for the entire 50–200ms DB round trip
  const user = db.querySync("SELECT * FROM users WHERE id = ?", [req.params.id]);
  res.json(user);
});

// NON-BLOCKING — how every good Node.js DB library works
app.get("/users/:id", async (req, res) => {
  try {
    // Thread is FREE during the 50–200ms DB round trip
    // Other requests are handled while this query runs in the background
    const user = await db.query(
      "SELECT * FROM users WHERE id = ?",
      [req.params.id]
    );

    if (!user) return res.status(404).json({ error: "Not found" });
    res.json(user);
  } catch (err) {
    res.status(500).json({ error: "Database error" });
  }
});

A typical DB query takes 20–200ms. With a blocking model, that's 20–200ms where your server can't respond to anyone else. With non-blocking, the thread handles dozens of other requests during that same window.

Running Multiple I/O Operations in Parallel

The biggest win from non-blocking I/O is Promise.all() — firing multiple operations simultaneously and waiting for all of them to finish.

const fsPromises = require("fs").promises;

// SEQUENTIAL — each await waits for the previous one to finish
async function loadSequential() {
  const users    = await fsPromises.readFile("users.json",    "utf8"); // 50ms
  const products = await fsPromises.readFile("products.json", "utf8"); // 50ms
  const orders   = await fsPromises.readFile("orders.json",   "utf8"); // 50ms
  return { users, products, orders };
  // Total: ~150ms
}

// PARALLEL — all three start and run at the same time
async function loadParallel() {
  const [users, products, orders] = await Promise.all([
    fsPromises.readFile("users.json",    "utf8"),
    fsPromises.readFile("products.json", "utf8"),
    fsPromises.readFile("orders.json",   "utf8")
  ]);
  return { users, products, orders };
  // Total: ~50ms (time of the slowest read, not the sum)
}

Three sequential awaits: ~150ms. Three parallel via Promise.all: ~50ms. The savings multiply with every additional operation.

The One Case Where Blocking Is Acceptable

Blocking I/O has exactly one legitimate home: startup scripts — code that runs once before the server begins accepting requests.

const fs = require("fs");

// ACCEPTABLE: runs once at startup, before any requests arrive
const config = fs.readFileSync("config.json", "utf8");
const settings = JSON.parse(config);

const app = express();
app.listen(3000, () => console.log("Server ready"));

// NEVER ACCEPTABLE: inside a request handler
app.get("/data", (req, res) => {
  const data = fs.readFileSync("data.json"); // blocks ALL concurrent requests
  res.json(data);
});

At startup, nothing is waiting — no requests are being handled, no users are impacted. Once the server is listening, treat every blocking call as a bug.


Blocking vs Non-Blocking: The Full Picture

                     BLOCKING                 NON-BLOCKING
──────────────────────────────────────────────────────────────────
Thread during I/O    Frozen — does nothing    Free — handles other work
Concurrent requests  Queue behind each other  All start immediately
Response time trend  Grows linearly with load Stays low under load
Code pattern         Direct return value       Callback / Promise / await
Node.js file API     readFileSync             readFile / fs.promises
Risk                 Server stall under load  CPU blocking (separate issue)
Route handlers       Never use blocking       Always use non-blocking
Startup scripts      Blocking is acceptable   Also fine either way
──────────────────────────────────────────────────────────────────


Quick Reference

Blocking Non-Blocking
Thread during I/O Frozen Free
Other requests Queued Handled in parallel
Node.js file API fs.readFileSync fs.readFile / fs.promises
Pattern Return value Callback / Promise / async-await
Multiple ops Sequential only Promise.all() for parallel
Route handlers Never Always
Startup scripts Acceptable Also fine

Key Takeaways

  • Blocking code freezes the thread until an operation completes — nothing else can run during that time
  • Non-blocking code hands off the operation, keeps moving, and handles the result via callback or Promise when it's ready
  • Under concurrent load, blocking I/O causes requests to queue — response times grow linearly with traffic
  • Node.js's single-thread model only works because of non-blocking I/O — mixing in blocking calls destroys the advantage
  • Use fs.readFile, async DB drivers, and async/await in all request handlers — never the Sync variants
  • Promise.all() runs multiple I/O operations in parallel — total time equals the slowest, not the sum
  • Blocking calls at startup (before the server listens) are the one acceptable exception

What's Next?

With a solid grip on blocking vs non-blocking, these topics follow naturally:

  • The event loop in depth — understanding exactly how Node.js decides which callback runs next and what "ticks" really means
  • Streams — processing large files and data without loading everything into memory at once
  • Worker Threads — the escape hatch for genuinely CPU-intensive work that would otherwise stall the event loop
  • async/await error handling patterns — centralising error handling so every async route is covered cleanly

The mental shift from "wait for it" to "come back when it's ready" is the core of everything Node.js does well. Once this clicks, writing high-performance server code becomes intuitive.


Next in the series: the Node.js event loop in depth — understanding exactly how callbacks are scheduled, what the call stack is, and why setTimeout(fn, 0) doesn't mean "immediately". 🚀