Node.js

Is Node.js Single-Threaded or Multithreaded? Explained With Examples

One of the most common questions in Node.js interviews is: Is Node.js single-threaded or multithreaded?If you've worked with Node.js, you might already know…

D
DevByteTechnical Author
Published
13 min read1 views
Is Node.js Single-Threaded or Multithreaded? Explained With Examples

One of the most common questions in Node.js interviews is: Is Node.js single-threaded or multithreaded?

If you've worked with Node.js, you might already know that JavaScript runs on a single main thread by default. But Node.js can also handle multiple operations concurrently, use background threads, and execute JavaScript in separate worker threads.

So, is Node.js single-threaded or multithreaded?

The short answer is that Node.js executes JavaScript on a single main thread by default, but its runtime uses additional mechanisms—including the operating system, a thread pool, and optional worker threads—to handle concurrent work.

In this guide, we'll explore how Node.js handles asynchronous operations, how the event loop works, what libuv does, and when multithreading is useful.

Quick Overview: Node.js Threading

Concept

What It Does

Main JavaScript thread

Executes JavaScript callbacks and application code

Event loop

Coordinates the execution of callbacks and asynchronous operations

libuv

Provides the event loop and other cross-platform asynchronous runtime functionality

libuv thread pool

Handles certain operations in background threads

Operating system

Handles many network I/O operations and other asynchronous tasks

Worker threads

Allow JavaScript to run in separate threads

Child processes

Run separate processes that can execute JavaScript independently

Cluster

Allows multiple Node.js processes to share a server port

Let's understand each component in detail.

1. Is Node.js Single-Threaded?

Yes, Node.js runs JavaScript on a single main thread by default.

This means that a typical Node.js application executes its JavaScript code on one main thread. JavaScript callbacks generally run one at a time on that thread.

Consider this example:

console.log("First");

console.log("Second");

console.log("Third");

Output:

First
Second
Third

The statements execute sequentially.

Now consider a slightly different example:

console.log("Start");

setTimeout(() => {
  console.log("Timer completed");
}, 1000);

console.log("End");

Output:

Start
End
Timer completed

Why does this happen?

The timer doesn't block the main JavaScript thread while it waits. Node.js arranges for the callback to become eligible for execution after the timer's delay, and the event loop runs it when the appropriate conditions are met.

The delay is not a guarantee that the callback will execute at exactly that time.

This is one of the fundamental concepts behind asynchronous programming in Node.js.

Does single-threaded mean Node.js can handle only one request?

No.

A Node.js server can manage many concurrent connections without creating a separate JavaScript thread for every request.

For example, imagine a server receiving requests from 1,000 users.

Many requests might involve:

  • Reading data from a database.

  • Calling an external API.

  • Reading a file.

  • Waiting for a network response.

While one operation is waiting for I/O, Node.js can continue processing other work.

This is possible because the main JavaScript thread doesn't have to remain blocked while every asynchronous operation completes.

Remember: Single-threaded JavaScript execution does not mean single-request processing.

2. How Does Node.js Handle Asynchronous Operations?

To understand Node.js concurrency, you need to understand three important components:

  1. The call stack.

  2. The event loop.

  3. Asynchronous operations handled through runtime and operating-system facilities.

Let's look at a simplified example.

const fs = require("node:fs");

console.log("Start");

fs.readFile("example.txt", "utf8", (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  console.log(data);
});

console.log("End");

Possible output:

Start
End
Contents of the file

Assuming the file read completes after the synchronous statements, the output follows this order.

What's happening internally?

Step 1: Execute synchronous code

Node.js executes console.log("Start") on the main JavaScript thread.

Step 2: Start the asynchronous file operation

Node.js initiates the file read. The operation is handled by the runtime's asynchronous I/O mechanisms, which use the libuv thread pool for this type of file-system operation.

The JavaScript thread doesn't need to wait for the file contents before continuing.

Step 3: Continue executing JavaScript

Node.js executes console.log("End").

Step 4: Complete the file operation

When the file has been read, the runtime makes the callback eligible to run.

Step 5: Execute the callback

The event loop eventually runs the callback on the main JavaScript thread.

The file read can take place in the background, but the JavaScript callback still executes on the main thread.

This is a key distinction: an asynchronous operation can complete in the background without its JavaScript callback running on a separate thread.

3. What Is the Node.js Event Loop?

The event loop is a core part of the Node.js runtime. It coordinates when asynchronous callbacks can execute.

It allows Node.js to keep processing JavaScript while asynchronous operations are pending.

Here's a simplified illustration of the process:

       Incoming Request
               |
               v
       Execute JavaScript
               |
               v
      Start Async Operation
               |
               v
   Wait for I/O / Background Work
               |
               v
      Operation Completes
               |
               v
      Callback Becomes Ready
               |
               v
      Event Loop Runs Callback
               |
               v
        Send Response

This is a conceptual diagram, not a complete representation of every event-loop phase.

The event loop does not automatically make CPU-intensive JavaScript execute in parallel. If a JavaScript function performs a large amount of synchronous computation, it occupies the main thread until that computation finishes.

Example: Blocking the event loop

console.log("Start");

const start = Date.now();

while (Date.now() - start < 5000) {
  // Simulate CPU-intensive synchronous work.
}

console.log("Finished");

This loop occupies the main JavaScript thread for approximately five seconds.

During that time, the thread cannot process other JavaScript callbacks.

If this code runs inside an HTTP server, other requests that need JavaScript execution may be delayed.

How to avoid blocking the event loop

Depending on the task, you can:

  • Use asynchronous APIs instead of synchronous operations.

  • Break manageable computations into smaller chunks.

  • Move CPU-intensive work to worker threads.

  • Use separate processes or dedicated background workers.

  • Optimize inefficient algorithms.

The correct solution depends on the workload. Replacing synchronous code with asynchronous code helps when the operation supports non-blocking I/O, but it does not make CPU-heavy calculations run in parallel automatically.

4. What Is libuv in Node.js?

libuv is a cross-platform library used by Node.js to implement the event loop and provide asynchronous I/O functionality.

It plays an important role in Node.js concurrency.

Some of its responsibilities include:

  • Managing the event loop.

  • Supporting asynchronous file-system operations.

  • Providing a thread pool for certain operations.

  • Supporting networking and other platform-specific asynchronous functionality.

  • Coordinating asynchronous operation completion with the event loop.

Does libuv use multiple threads?

Yes.

libuv maintains a thread pool that can execute certain tasks in background threads. By default, the pool has four threads, and its size can be configured through the UV_THREADPOOL_SIZE environment variable, subject to libuv's supported limits.

Operations that use this pool include many file-system operations, certain DNS lookups, and some cryptographic operations.

Not every asynchronous operation uses the thread pool.

For example, many network operations use operating-system facilities rather than consuming one thread-pool thread for each connection.

Example: File-system operations

const fs = require("node:fs");

fs.readFile("file1.txt", "utf8", (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  console.log("File 1 completed");
});

fs.readFile("file2.txt", "utf8", (err, data) => {
  if (err) {
    console.error(err);
    return;
  }

  console.log("File 2 completed");
});

console.log("Both reads started");

The two file reads can be in progress concurrently. Their callbacks may complete in either order.

However, this does not guarantee that every operation will run simultaneously on a separate thread. The exact behavior depends on the operation, available resources, and runtime implementation.

5. How Can Node.js Be Multithreaded?

Although Node.js executes JavaScript on one main thread by default, it provides APIs for running JavaScript in separate threads.

The most important option for CPU-intensive JavaScript is the worker_threads module.

A worker thread has its own JavaScript execution context and can perform computations independently of the main thread.

What are worker threads used for?

Worker threads are useful for tasks such as:

  • Processing large datasets.

  • Performing expensive mathematical calculations.

  • Parsing or transforming large amounts of data.

  • Generating computationally intensive reports.

  • Running CPU-heavy algorithms without blocking the main event loop.

Worker threads are usually not necessary for ordinary asynchronous database queries or HTTP requests.

Example: Creating a worker thread

Let's create a simple example with two files.

File 1: main.js

const { Worker } = require("node:worker_threads");

const worker = new Worker("./worker.js");

worker.on("message", (result) => {
  console.log("Result from worker:", result);
});

worker.on("error", (error) => {
  console.error("Worker error:", error);
});

worker.on("exit", (code) => {
  if (code !== 0) {
    console.error(`Worker stopped with exit code ${code}`);
  }
});

console.log("Main thread continues working");

File 2: worker.js

const { parentPort } = require("node:worker_threads");

let result = 0;

for (let i = 0; i < 1_000_000_000; i++) {
  result += i;
}

parentPort.postMessage(result);

In this example:

  1. main.js creates a worker.

  2. The worker executes the calculation on its own JavaScript thread.

  3. The main thread continues executing while the worker calculates.

  4. The worker sends the result back through parentPort.

  5. The main thread receives the result through the message event.

The calculation is intentionally expensive and may take a substantial amount of time. Use a smaller loop when experimenting on a low-powered machine.

For production applications, also consider worker lifecycle management, task cancellation, error handling, and whether reusing a worker pool would be more efficient than creating a new worker for every task.

Important point

Worker threads can execute JavaScript in parallel, but creating too many workers can introduce overhead.

For many applications, a worker pool is preferable to creating a new worker for every job.

6. Worker Threads vs. Cluster vs. Child Processes

Node.js provides multiple ways to distribute work. These mechanisms serve different purposes.

Feature

Worker Threads

Cluster

Child Processes

Execution model

Separate JavaScript threads

Multiple Node.js processes

Separate processes

Memory

Separate JavaScript execution contexts; can share memory through SharedArrayBuffer

Separate process memory

Separate process memory

Best use case

CPU-intensive JavaScript tasks

Running multiple server processes

Isolated tasks and external commands

Communication

Messages and transferable data; optional shared memory

Inter-process communication

IPC when configured

Isolation

Less isolation than separate processes

Stronger process isolation

Stronger process isolation

Typical use

Expensive calculations

Scaling a server across CPU cores

Background jobs and external programs

Worker threads

Use worker threads when you need to move CPU-intensive JavaScript work off the main event loop.

Cluster

The node:cluster module allows you to run multiple Node.js processes that can share a server port.

Each worker is a separate process with its own JavaScript main thread and memory space.

Cluster can help a server use multiple CPU cores, but it introduces process-management considerations.

Child processes

Child processes allow Node.js to launch other programs or additional Node.js processes.

They're useful for running external commands, isolating workloads, or delegating tasks to separate processes.

Interview tip: Worker threads are generally the most direct answer when asked how to execute CPU-intensive JavaScript in parallel within a Node.js application.

7. Single-Threaded vs. Multithreaded: What's the Difference?

Let's compare the concepts.

Aspect

Single Main JavaScript Thread

Multiple JavaScript Threads

JavaScript execution

One main execution thread

Multiple independent execution threads

CPU-intensive work

Can block the main thread

Can run on worker threads in parallel

Asynchronous I/O

Supported

Also supported

Parallel JavaScript execution

Not across multiple threads by default

Possible with worker threads

Complexity

Usually simpler

Requires communication and lifecycle management

Best suited for

Typical request handling and I/O-heavy workloads

CPU-intensive workloads that benefit from parallel execution

One important distinction is that concurrency and parallelism are not the same thing.

  • Concurrency means multiple tasks can make progress during overlapping periods.

  • Parallelism means multiple tasks can execute at the same time, such as on different CPU cores.

Node.js can handle concurrent asynchronous operations using its event loop and runtime facilities without executing all their JavaScript code in parallel.

Worker threads can enable parallel JavaScript execution when the hardware and workload permit it.

8. Why Is Node.js So Good at Handling Many Requests?

Node.js is particularly useful for applications that spend much of their time waiting for I/O.

Examples include:

  • REST APIs.

  • Chat applications.

  • Real-time notification systems.

  • Streaming applications.

  • Backend services that communicate with databases and external APIs.

Consider an Express.js API endpoint:

app.get("/users", async (req, res, next) => {
  try {
    const users = await User.find().limit(100);

    res.json(users);
  } catch (error) {
    next(error);
  }
});

When the database query is awaiting a result, the main JavaScript thread can continue processing other work.

When the query completes, the handler resumes and sends the response.

This assumes the database driver and surrounding operations use asynchronous I/O correctly. Synchronous CPU-intensive work elsewhere in the application can still block the event loop.

What if 10,000 users send requests?

Node.js does not need to create 10,000 JavaScript threads simply to accept 10,000 concurrent connections.

However, actual capacity depends on many factors, including:

  • CPU and memory resources.

  • Database connection limits.

  • External API latency.

  • Application logic.

  • Request and response sizes.

  • Network bandwidth.

  • Rate limits and backpressure.

  • How much CPU work each request requires.

Node.js can handle many concurrent connections, but it is not infinitely scalable. Production systems still require performance measurement, sensible resource limits, and appropriate architecture.

9. When Should You Use Worker Threads in Node.js?

Use worker threads when the application performs CPU-intensive calculations that would otherwise occupy the main JavaScript thread for too long.

For example:

Good candidates:

  • Image processing that is CPU-intensive.

  • Large data transformations.

  • Computationally expensive algorithms.

  • Complex statistical calculations.

  • CPU-heavy document processing.

Usually not necessary:

  • Ordinary database queries.

  • Typical HTTP requests.

  • Waiting for an external API.

  • Reading files through asynchronous file-system APIs.

For I/O-heavy operations, asynchronous APIs are generally the better starting point.

For CPU-heavy tasks, consider worker threads, a background-job system, or a separate service depending on how much computation is involved and whether the work needs to scale independently.

A practical example

Imagine you're building an application that generates reports from millions of records.

If the report-generation logic performs heavy synchronous calculations on the main thread, other requests may be delayed.

You could move the computation to a worker thread or a separate worker service. The API can then return a job ID and let the client check the result later.

This architecture keeps the main request-handling path responsive while the report is generated.

10. Common Myths About Node.js Threading

Myth 1: Node.js is completely single-threaded

Reality: JavaScript runs on a single main thread by default, but the runtime can use background threads, and applications can create worker threads or additional processes.

Myth 2: Every asynchronous operation runs on a separate thread

Reality: Many network operations use operating-system asynchronous I/O facilities. Some operations use the libuv thread pool, while others follow different implementation paths.

Myth 3: async/await makes CPU-heavy code run in parallel

Reality: async/await provides a convenient way to work with promises. It doesn't automatically move CPU-intensive JavaScript onto another thread.

For example:

async function calculate() {
  let total = 0;

  for (let i = 0; i < 1_000_000_000; i++) {
    total += i;
  }

  return total;
}

calculate();

Despite the async keyword, the loop runs synchronously on the main JavaScript thread before the function returns its resolved promise.

Myth 4: Node.js cannot use multiple CPU cores

Reality: Node.js applications can use multiple CPU cores through worker threads, cluster workers, child processes, or separate application instances.

Myth 5: More threads always mean better performance

Reality: Threads have overhead. Too many workers can increase memory usage, context switching, and coordination costs. Choose a concurrency strategy based on measurements and workload requirements.

Frequently Asked Questions

1. Is Node.js single-threaded or multithreaded?

Node.js executes JavaScript on a single main thread by default. However, its runtime uses background mechanisms for asynchronous operations, and developers can create worker threads to execute JavaScript in parallel.

2. Does Node.js use multiple threads internally?

Yes. Node.js and its underlying runtime can use multiple threads for certain operations, including work handled by the libuv thread pool. The exact execution path depends on the operation.

3. What is the default size of the libuv thread pool?

The libuv thread pool has four threads by default. Its size can be configured using UV_THREADPOOL_SIZE, subject to supported limits.

4. Does async/await make Node.js multithreaded?

No. async/await makes promise-based asynchronous code easier to write and read. It does not automatically execute JavaScript on another thread.

5. How does Node.js handle multiple requests with one main thread?

Node.js uses asynchronous I/O and the event loop to manage many concurrent connections. When an operation is waiting for I/O, the main thread can execute other ready JavaScript work.

6. When should I use worker threads?

Use worker threads when CPU-intensive JavaScript would otherwise block the main event loop and the computation can benefit from being performed in parallel.

7. Can Node.js use all CPU cores?

Yes, but a single main JavaScript thread does not automatically use all cores for JavaScript execution. You can use worker threads or multiple Node.js processes to distribute work across CPU cores.

Conclusion

So, is Node.js single-threaded or multithreaded?

The most accurate answer is that Node.js executes JavaScript on a single main thread by default, while its runtime can use background threads and operating-system facilities to handle asynchronous work. Worker threads and multiple processes can provide parallel JavaScript execution when needed.

Understanding this distinction helps you design more responsive and scalable backend applications.

If you're building REST APIs, chat applications, or I/O-heavy services, Node.js's asynchronous architecture can be a great fit. If your application performs expensive calculations, consider worker threads or a separate processing service to prevent the main event loop from becoming blocked.

The key is to understand the workload, measure performance, and choose the right concurrency strategy for your application.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘