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

推荐订阅源

L
LINUX DO - 最新话题
G
Google Developers Blog
J
Java Code Geeks
The GitHub Blog
The GitHub Blog
F
Full Disclosure
H
Help Net Security
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
Recent Announcements
Recent Announcements
Help Net Security
Help Net Security
The Hacker News
The Hacker News
IT之家
IT之家
Y
Y Combinator Blog
Martin Fowler
Martin Fowler
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
V
Visual Studio Blog
博客园 - 聂微东
Hacker News: Ask HN
Hacker News: Ask HN
H
Hacker News: Front Page
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Last Week in AI
Last Week in AI
Schneier on Security
Schneier on Security
N
News and Events Feed by Topic
博客园 - 【当耐特】
有赞技术团队
有赞技术团队
AWS News Blog
AWS News Blog
Blog — PlanetScale
Blog — PlanetScale
博客园_首页
Google DeepMind News
Google DeepMind News
Cloudbric
Cloudbric
N
News | PayPal Newsroom
A
About on SuperTechFans
S
Schneier on Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Hugging Face - Blog
Hugging Face - Blog
M
MIT News - Artificial intelligence
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
雷峰网
雷峰网
T
The Exploit Database - CXSecurity.com
罗磊的独立博客
K
Kaspersky official blog
The Cloudflare Blog
I
Intezer

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
How Node.js Handles Multiple Requests with a Single Thread
SATYA SOOTAR · 2026-05-09 · via DEV Community

Hello readers 👋, welcome to the 6th blog of our Node.js journey!

In the last post, we explored the crucial difference between blocking and non-blocking code. We saw that a single blocking call can freeze an entire server, while non-blocking code keeps it responsive. Today, we tackle the question that naturally follows: if Node.js runs JavaScript on just one thread, how on earth does it handle thousands of requests at the same time without falling apart?

It sounds impossible. A single checkout line in a supermarket can only process one customer at a time. Yet Node.js servers routinely manage tens of thousands of concurrent connections. The answer lies in a brilliant combination of the event loop, non-blocking I/O, and background workers. Let's break it down.

The single-threaded nature of Node.js

First, let's be clear: Node.js executes your JavaScript code in a single main thread. That means when you write:

console.log("Step 1");
console.log("Step 2");

Enter fullscreen mode Exit fullscreen mode

These two lines never run simultaneously. Step 1 finishes before Step 2 starts. This single-threaded design simplifies your code because you don't have to worry about two pieces of code modifying the same variable at the same time.

But a traditional server that uses one thread per request (like many Java or PHP setups) would quickly run out of threads under high load. Each thread consumes memory, and context switching between hundreds of threads wastes CPU. Node.js takes a totally different path. It keeps the single thread but never lets it sit idle.

The magic comes from how it delegates work outside that thread. The main thread is like a project manager who never does heavy lifting; they hand tasks off to specialists and only get involved when results are ready.

The event loop: the master coordinator

The event loop is the core mechanism that enables this pattern. It's a continuously running loop that watches two things: the call stack (where functions execute) and the task queue (where callbacks wait). When the stack is empty, the loop picks the next callback from the queue and pushes it onto the stack for execution.

Think of the event loop as a restaurant's head chef. She can only cook one dish at a time (single thread). But she doesn't peel potatoes or wait for water to boil. She delegates those tasks to assistants (background workers). While they work, she moves on to the next order. When an assistant finishes, they call out "Done!" and the chef briefly pauses, plates the component, and continues.

In Node.js, this "delegation" happens whenever you call an asynchronous function like fs.readFile, http.get, or a database query. The main thread dispatches the I/O operation, registers a callback, and moves on to process the next request immediately.

Delegating tasks to background workers

Where does the actual I/O happen? Node.js uses two main mechanisms:

  1. Operating system kernel: For network I/O, the OS provides non-blocking system calls (like epoll on Linux, kqueue on macOS). The main thread registers a socket with the kernel and asks to be notified when data arrives. The kernel handles the waiting, and the main thread carries on with other work. When data is ready, a callback is queued.

  2. The libuv thread pool: For operations that don't have non-blocking OS support (like file system calls or some DNS lookups), libuv, the library that powers the event loop, maintains a pool of background threads. When you call fs.readFile, libuv grabs a thread from the pool, reads the file content on that thread, and then, once done, pushes the callback into the event loop's queue to be executed on the main thread.

In both cases, the main thread never blocks. It just schedules work and handles results. The heavy I/O happens elsewhere.

Handling multiple client requests: a step-by-step view

Imagine a Node.js HTTP server that logs the request, then responds after a short delay (simulating a database lookup). Here's the code:

const http = require("http");

http.createServer((req, res) => {
  console.log("Request received:", req.url);
  setTimeout(() => {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Response for " + req.url);
    console.log("Response sent:", req.url);
  }, 100);
}).listen(3000, () => {
  console.log("Server running on port 3000");
});

Enter fullscreen mode Exit fullscreen mode

Now, open three tabs and quickly hit the server with different URLs. If Node.js were single-threaded in a blocking way, each request would need to finish before the next one even starts. But what actually happens is:

  1. Request A arrives. The main thread logs "Request received: /a" and calls setTimeout. This schedules a timer in libuv and immediately returns.
  2. The main thread is free. Request B arrives instantly. It logs "Request received: /b", sets another timer, and returns.
  3. Request C arrives, logs, sets a timer.
  4. After about 100ms, the timers start firing. Libuv queues the callbacks. The event loop picks them up one by one, and the main thread sends responses: "Response sent: /a", then "Response sent: /b", then "Response sent: /c".

All three requests were accepted and processed concurrently, using a single JavaScript thread that never waited for the 100ms delay. The 100ms was spent in the background, not on the main thread.

This is concurrency without parallelism.

Why Node.js scales so well

The secret to Node.js's scalability is that it doesn't dedicate a thread to each connection. In a traditional threaded server, if you have 10,000 concurrent connections, you might have 10,000 threads. Each thread consumes roughly 1 MB of stack space, so that's 10 GB of memory just for thread stacks. Plus, the OS scheduler wastes CPU switching among them.

In Node.js, the memory footprint per connection is minimal: a small amount of state to remember the request, and a callback function. The event loop efficiently manages all of them on a single thread. This allows a Node.js process to comfortably handle tens of thousands of open connections (like WebSocket sessions) on modest hardware.

Moreover, the event loop model naturally matches I/O heavy workloads. Most web servers spend the majority of their time waiting for the database, filesystem, or external APIs. Node.js turns that waiting into an opportunity to serve other requests.

Concurrency vs parallelism: a crucial distinction

It's vital to understand that Node.js provides concurrency, not parallelism, within a single process.

  • Concurrency: Multiple tasks are in progress at the same time, but not necessarily executing simultaneously. The single thread switches between them so fast that it looks like they run together.
  • Parallelism: Multiple tasks literally run at the same instant on different CPU cores.

Node.js is concurrent through the event loop. But you can achieve parallelism by running multiple Node.js processes (clustering) or using worker threads for CPU-intensive tasks. However, the default model, and the one we're discussing, is single-threaded concurrency.

The head chef analogy makes this clear. The chef is concurrent: she manages several dishes at once, keeping them all moving forward. But she only has two hands; she cannot physically chop and stir at the same instant. She is not parallel. If she needs to chop fifty onions (a CPU-heavy task), she would block the whole kitchen. So she hires an assistant (a worker thread) to do that in parallel. For most server tasks (I/O), the assistants are already built in (the OS and libuv).

Visualizing the single thread handling multiple requests

Here's a mental picture of the flow:

Time 0ms:   Request A arrives → main thread logs, starts async I/O, moves on
Time 1ms:   Request B arrives → main thread logs, starts async I/O, moves on
Time 2ms:   Request C arrives → main thread logs, starts async I/O, moves on
...
Time 100ms: I/O for Request A completes → callback queued
            I/O for Request B completes → callback queued
Time 101ms: Event loop picks A's callback → main thread sends response A
Time 102ms: Event loop picks B's callback → main thread sends response B
...

Enter fullscreen mode Exit fullscreen mode

The main thread was blocked for only a tiny fraction of the total time (the logging and response sending). The actual waiting happened in the background, concurrently, for all requests.

Conclusion

Node.js handles multiple requests with a single thread by never waiting. It delegates I/O tasks to the OS kernel or a background thread pool, uses an event loop to manage callbacks, and keeps its main thread free to accept new work. This is a radical departure from the thread-per-connection model and is the reason Node.js excels at building fast, scalable network applications.

To recap:

  • Node.js JavaScript runs on one thread, ensuring simplicity and avoiding synchronization bugs.
  • The event loop orchestrates concurrency by continuously dispatching callbacks when the stack is empty.
  • Time-consuming I/O is handed off to the OS (non-blocking) or to a libuv thread pool, never blocking the main thread.
  • Multiple client requests are handled by interleaving their short, non-blocking pieces, giving the illusion of simultaneous processing.
  • This model scales well because memory per connection is tiny, and CPU time isn't wasted on thread management.
  • Node.js provides concurrency, not parallelism, on a single process. For true parallel computation, you can use clustering or worker threads.

Now that you understand this foundational concept, you're ready to build applications that can handle massive concurrency with ease. In the next post, we'll explore some of the most commonly used built-in modules that Node.js provides to make all this power accessible.


Hope you found this helpful! If you spot any mistakes or have suggestions, let me know. You can find me on LinkedIn and X, where I post more about web development.