Skip to content
jshacks.dev
Async

Concurrency vs Parallelism in JavaScript

Learn the difference between concurrency and parallelism in JavaScript, how the event loop provides one and workers provide the other, and when you need each.

6 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, TypeScript, npm and Vite logos.

People say JavaScript is single-threaded and then say it handles thousands of connections at once, and both statements are true because concurrency and parallelism are different things. Concurrency means several tasks are in progress during the same period, with the work interleaved. Parallelism means several tasks are executing at the very same instant, on different processor cores. JavaScript's main thread gives you the first and never the second: one piece of your code runs at a time, but while a request waits for the network, another can run. To get true parallelism you add threads, through Web Workers in the browser and worker_threads in Node.js. This post explains the distinction with runnable examples on Node.js 24, shows what each model can and cannot speed up, and gives a decision rule for choosing between them.

Definitions that hold up

A useful picture is a cook in a kitchen. One cook who puts a pot on to boil, chops vegetables while it heats and stirs a sauce when the timer rings is concurrent: several dishes progress, one action at a time. Two cooks working at two stoves are parallel. More cooks make parallel work faster. A single cook who never stands idle, because there is always something to do while waiting, is already efficient, and a second cook adds nothing to the waiting time of the boiling water.

JavaScript's event loop is the single cook. Waiting operations, such as network requests, file reads and timers, are the pots on the stove: the runtime handles them outside your code and tells you when they finish. Computation is the chopping: it needs the cook's hands, and while it happens nothing else can.

Concurrency: waiting together

When work consists of waiting, concurrency alone is enough to overlap it.

JavaScript
const wait = (ms, name) =>
  new Promise((resolve) => setTimeout(() => resolve(name), ms));

const start = Date.now();

const results = await Promise.all([wait(50, "a"), wait(50, "b"), wait(50, "c")]);

const elapsed = Date.now() - start;
console.log(results);
console.log("finished in under 120 ms:", elapsed < 120);
Text
[ 'a', 'b', 'c' ]
finished in under 120 ms: true

Three 50 ms waits finished in about 50 ms, not 150, even though a single thread ran everything. Each timer was started, the thread went back to the loop, and all three were ticking at once. This is the model behind servers that handle many connections on one thread: while one request waits for its database query, the thread serves another.

Concurrency does not speed up computation

If the work needs the processor, interleaving it does not finish it sooner. Two tasks that each take 100 ms of computation take about 200 ms together on one thread, however you arrange them.

JavaScript
function busy(ms) {
  const end = Date.now() + ms;
  while (Date.now() < end) {
    // computing
  }
}

const start = Date.now();

await Promise.all([
  Promise.resolve().then(() => busy(100)),
  Promise.resolve().then(() => busy(100)),
]);

const elapsed = Date.now() - start;
console.log("took at least 190 ms:", elapsed >= 190);
Text
took at least 190 ms: true

Using Promise.all made no difference, because both callbacks ran on the same thread, one after the other. The promise machinery coordinated them and did not run them in parallel. The correct reading of "async" code is that it overlaps waiting and nothing more.

Parallelism: more threads

Worker threads run JavaScript on separate threads, each with its own event loop and memory. Two workers can compute at the same time on a machine with two or more cores.

JavaScript
import { Worker, isMainThread, parentPort } from "node:worker_threads";

if (isMainThread) {
  const run = () =>
    new Promise((resolve, reject) => {
      const worker = new Worker(new URL(import.meta.url));
      worker.once("message", resolve);
      worker.once("error", reject);
    });

  const start = Date.now();
  await Promise.all([run(), run()]);
  const elapsed = Date.now() - start;

  console.log("two 100 ms jobs finished in under 190 ms:", elapsed < 190);
} else {
  const end = Date.now() + 100;
  while (Date.now() < end) {
    // computing
  }
  parentPort.postMessage("done");
}
Text
two 100 ms jobs finished in under 190 ms: true

The same file serves as main script and worker, which isMainThread tells apart. On a machine with at least two free cores, the two 100 ms jobs overlapped and finished in about 100 ms plus the cost of starting a worker, which is not free. On a single core, they would not overlap, so the threshold is a statement about typical hardware and not a guarantee.

What parallelism costs

Threads are not a free upgrade, and three costs shape how you use them.

Startup. Each worker boots a JavaScript environment, which takes time and memory. A worker for a ten millisecond task is slower than doing the task in place. Reuse workers with a pool, such as the piscina package, and keep them for jobs measured in tens of milliseconds or more.

Communication. Workers do not share objects. Data is copied through postMessage using structured cloning, which is cheap for small values and expensive for large ones. Transferring an ArrayBuffer hands over ownership without copying, and a SharedArrayBuffer shares the same memory between threads, with Atomics for safe access.

JavaScript
import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

if (isMainThread) {
  const shared = new SharedArrayBuffer(4);
  const view = new Int32Array(shared);

  await new Promise((resolve) => {
    const worker = new Worker(new URL(import.meta.url), { workerData: shared });
    worker.once("exit", resolve);
  });

  console.log("value written by the worker:", Atomics.load(view, 0));
} else {
  const view = new Int32Array(workerData);
  Atomics.add(view, 0, 42);
}
Text
value written by the worker: 42

Complexity. Parallel code has races, deadlocks and ordering bugs that single-threaded JavaScript avoids by design. The more you share, the more you need to coordinate, which is why the message-passing style is the default and shared memory is the exception.

Where each runs

Concurrency (event loop)Parallelism (workers)
BrowserPromises, timers, fetch, eventsWeb Workers, SharedArrayBuffer
Node.jsPromises, timers, I/O callbacksworker_threads, child_process, cluster
Best forWaiting on network, disk, timersImage processing, parsing, compression, crypto, simulations
MemoryShared, one heapSeparate heaps, copied messages
Speeds upThroughput of I/O-bound workComputation on multiple cores

Node.js also provides parallelism outside your JavaScript. The libuv thread pool runs file system calls, DNS lookups and some crypto and zlib operations on background threads, which is why a crypto.pbkdf2 call, which is asynchronous, can overlap with other work and use several cores without any worker code from you. The pool defaults to four threads and is set with UV_THREADPOOL_SIZE.

A decision rule

Ask what the task is waiting for. If it waits for something outside the process, a database, an API or a file, use asynchronous code and let the loop overlap the waits. You will see no gain from threads. If it spends its time computing, and the computation is long enough to notice, use a worker or a pool. If it is a mix, such as downloading many images and resizing them, split it: download concurrently on the main thread, and send the resizing to workers.

For a server, a related decision is scaling across cores. A single Node.js process uses one core for JavaScript, so a machine with eight cores runs eight processes, through the cluster module or a process manager, or runs several containers. That is parallelism at the process level, and it needs no change to your code as long as the processes do not share state in memory.

Common misconceptions

"async makes it multi-threaded." It does not. An async function runs on the calling thread, and only the waiting is handled elsewhere.

**"Promise.all runs tasks in parallel."** It waits for them together. If they are I/O they overlap, and if they are computation they run one after the other.

"More workers are always faster." Past the number of cores, extra workers compete for the same processors and add switching and memory cost.

"Single-threaded means slow." For I/O-heavy services, it is often the efficient choice, since there is no locking and no thread-per-connection overhead.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.