Skip to content
jshacks.dev
Patterns

Concurrency Patterns as Design Patterns

Treat concurrency as design patterns: limits, mutexes, queues, fan-out and cancellation. Build each in JavaScript on Node.js and see the races they prevent.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, Node.js, npm and TypeScript logos.

JavaScript runs your code on one thread, yet concurrency problems are real: many promises are in flight at once, and each await is a point where another task can run and change shared state. The tools for managing that are design patterns with names: a limiter caps how much runs at once, a mutex serializes access to shared state, a queue decouples producers from consumers, fan-out and fan-in split work and gather the results, and cancellation stops work that is no longer wanted. This post builds each on Node.js 24 in plain JavaScript, with the output shown, and explains the race condition each one prevents.

Concurrency without threads

A single thread does not mean no races. Consider two withdrawals from the same account, each of which reads the balance, waits for some I/O and then writes the new value.

race.mjsJavaScript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

let balance = 100;

async function withdraw(amount) {
  const current = balance;
  await sleep(1);
  balance = current - amount;
}

await Promise.all([withdraw(30), withdraw(30)]);
console.log(balance);
Text
70

Both calls read 100 before either wrote, so each computed 70 and the second write overwrote the first. The correct answer is 40. This is a lost update: a read-modify-write sequence that was interrupted at an await. The code has no threads and no shared memory in the usual sense, and it still has a race, because the await yields control. Every pattern below exists to manage interleavings like this one.

Pattern 1: the mutex

A mutex lets only one task into a critical section at a time. In JavaScript, it is a promise chain: each caller waits for the previous holder to finish.

mutex.mjsJavaScript
function createMutex() {
  let tail = Promise.resolve();
  return function run(task) {
    const result = tail.then(task);
    tail = result.catch(() => {});
    return result;
  };
}

const lock = createMutex();
let balance = 100;

async function withdraw(amount) {
  return lock(async () => {
    const current = balance;
    await sleep(1);
    balance = current - amount;
  });
}

await Promise.all([withdraw(30), withdraw(30)]);
console.log(balance);
Text
40

The second withdrawal did not start until the first finished, so it read 70 and wrote 40. Each task is chained onto tail. The .catch(() => {}) on the stored tail keeps one failed task from breaking the chain for everyone after it, while the caller still receives the original rejection through result. The cost is that the critical section runs serially, so keep it small and do slow work, like network calls, outside it when you can.

Pattern 2: the limiter, or semaphore

A mutex allows one at a time. A limiter allows a fixed number. It is the right tool when you have many tasks and a downstream that cannot take them all at once, such as an API with a rate limit or a database with a connection cap.

limiter.mjsJavaScript
function createLimiter(max) {
  let active = 0;
  const queue = [];

  function next() {
    if (active >= max || queue.length === 0) return;
    active += 1;
    const { task, resolve, reject } = queue.shift();
    task()
      .then(resolve, reject)
      .finally(() => {
        active -= 1;
        next();
      });
  }

  return function limit(task) {
    return new Promise((resolve, reject) => {
      queue.push({ task, resolve, reject });
      next();
    });
  };
}

const limit = createLimiter(2);
let running = 0;
let peak = 0;

const work = (id) =>
  limit(async () => {
    running += 1;
    peak = Math.max(peak, running);
    await sleep(10);
    running -= 1;
    return id;
  });

const results = await Promise.all([1, 2, 3, 4, 5].map(work));
console.log(results, `peak concurrency: ${peak}`);
Text
[ 1, 2, 3, 4, 5 ] peak concurrency: 2

Five tasks were submitted at once, and never more than two ran together. Promise.all preserves the order of its inputs, so the results line up with the ids even though tasks finished at different times. A mutex is a limiter with max equal to one. Without a limit, Promise.all(urls.map(fetch)) over ten thousand URLs opens ten thousand connections at once, which exhausts sockets or triggers rate limits.

Pattern 3: the queue between producer and consumer

A queue decouples the rate at which work arrives from the rate at which it is processed. Producers add items and move on, and consumers take items when they are ready.

queue.mjsJavaScript
function createQueue() {
  const items = [];
  const waiting = [];
  return {
    push(item) {
      const waiter = waiting.shift();
      if (waiter) waiter(item);
      else items.push(item);
    },
    pull() {
      if (items.length > 0) return Promise.resolve(items.shift());
      return new Promise((resolve) => waiting.push(resolve));
    },
  };
}

const jobs = createQueue();
const done = [];

async function consumer(name) {
  for (let i = 0; i < 2; i++) {
    const job = await jobs.pull();
    await sleep(5);
    done.push(`${name}:${job}`);
  }
}

const consumers = Promise.all([consumer("a"), consumer("b")]);
["j1", "j2", "j3", "j4"].forEach((job) => jobs.push(job));
await consumers;
console.log(done);
Text
[ 'a:j1', 'b:j2', 'a:j3', 'b:j4' ]

Two consumers pulled from one queue, and the four jobs were split between them. Consumer a took j1 and b took j2, then each finished and pulled the next one. The exact interleaving depends on timing, and with equal delays this order is what the schedule produces. This simple queue is unbounded: if producers are faster than consumers, it grows without limit. A bounded queue makes push wait when full, which applies backpressure to the producers. Streams and async iterators give you bounded queues with backpressure built in.

Pattern 4: fan-out and fan-in

Fan-out splits a job into independent pieces that run at the same time, and fan-in gathers their results. Promise.all and Promise.allSettled are the standard tools.

fan.mjsJavaScript
async function fetchPrice(shop) {
  await sleep(shop.delay);
  if (shop.fails) throw new Error(`${shop.name} is down`);
  return { shop: shop.name, price: shop.price };
}

const shops = [
  { name: "alpha", price: 12, delay: 5 },
  { name: "beta", price: 9, delay: 2, fails: true },
  { name: "gamma", price: 11, delay: 3 },
];

const settled = await Promise.allSettled(shops.map(fetchPrice));
const prices = settled.filter((r) => r.status === "fulfilled").map((r) => r.value);
const best = prices.reduce((a, b) => (a.price <= b.price ? a : b));

console.log(prices);
console.log(best);
Text
[ { shop: 'alpha', price: 12 }, { shop: 'gamma', price: 11 } ]
{ shop: 'gamma', price: 11 }

All three requests started together, and the total time is that of the slowest, not the sum. allSettled kept the two successes when beta failed, and the best price was chosen among the survivors. Use Promise.all when any failure should abort the whole job, and allSettled when partial results are useful. Combine fan-out with a limiter when the number of pieces is large.

Pattern 5: first result wins

Sometimes you want the fastest of several equivalent sources: two mirrors of an API, or a cache against a database. Promise.race returns the first to settle, and Promise.any returns the first to succeed, ignoring failures.

any.mjsJavaScript
const mirror = (name, delay, fails = false) =>
  sleep(delay).then(() => {
    if (fails) throw new Error(`${name} failed`);
    return name;
  });

console.log(await Promise.any([mirror("eu", 20, true), mirror("us", 10), mirror("asia", 5, true)]));

try {
  await Promise.any([mirror("a", 1, true), mirror("b", 2, true)]);
} catch (err) {
  console.log(err.constructor.name, err.errors.length);
}
Text
us
AggregateError 2

asia was fastest but failed, so any ignored it and returned us. When every source fails, any rejects with an AggregateError that holds all the reasons. With race, the first rejection would have won, which suits a timeout, where the first to settle is the answer either way.

Pattern 6: cancellation

Work that nobody waits for is waste, and in the worst case holds resources. AbortController is the standard signal for cancelling: the caller aborts, and the task listens for the signal and stops.

cancel.mjsJavaScript
function cancellableSleep(ms, signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(resolve, ms, "finished");
    signal.addEventListener(
      "abort",
      () => {
        clearTimeout(timer);
        reject(signal.reason);
      },
      { once: true },
    );
  });
}

const controller = new AbortController();
const task = cancellableSleep(1000, controller.signal);
setTimeout(() => controller.abort(new Error("user navigated away")), 10);

try {
  await task;
} catch (err) {
  console.log(err.message);
}

console.log(await cancellableSleep(5, new AbortController().signal));
Text
user navigated away
finished

The aborted task rejected with the reason it was given, and the timer was cleared so nothing keeps the process alive. A task that is not aborted runs to completion. Most Node.js APIs that wait on I/O accept a signal option, including fetch, fs.promises calls and timers from node:timers/promises, and AbortSignal.timeout(ms) makes a signal that aborts itself after a delay. Passing the signal through every layer is how a request that is cancelled at the edge stops all the work done on its behalf.

Choosing a pattern

ProblemPattern
Read-modify-write on shared state across awaitMutex, or restructure to avoid the gap
Too many tasks at once for a downstreamLimiter
Work arrives faster than it is handledQueue, ideally bounded
Independent pieces of one jobFan-out and fan-in
Several equivalent sourcesPromise.any or race
Work no longer neededCancellation with a signal

Before reaching for a mutex, consider whether the race can be removed by design. If the read and the write happen with no await between them, the code cannot be interrupted, and no lock is needed. Computing the new value from the current one in one synchronous step is often enough.

no-lock.mjsJavaScript
let balance = 100;

async function withdrawSafe(amount) {
  await sleep(1);
  balance -= amount;
}

await Promise.all([withdrawSafe(30), withdrawSafe(30)]);
console.log(balance);
Text
40

The slow work happens first, and the read-modify-write is a single synchronous statement, so no other task can run in the middle. The pattern is to keep the critical section free of await.

Beyond one thread

For CPU-bound work, the event loop is the bottleneck, and these patterns do not help. Use worker threads, with a pool of workers and a limiter in front of them, or separate processes. For shared state across processes, the database or a store such as Redis is the place to lock, with its own mechanisms, and an in-memory mutex only protects one process.

Testing concurrent code

Tests should force the interleaving that causes the bug. A short sleep inside the critical section, as in the examples above, exposes races reliably, and asserting on the peak concurrency, as the limiter example does, checks the cap directly.

concurrency.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

test("the mutex prevents lost updates", async () => {
  let total = 0;
  const lock = createMutex();
  const add = (n) =>
    lock(async () => {
      const current = total;
      await sleep(1);
      total = current + n;
    });
  await Promise.all([add(1), add(2), add(3)]);
  assert.equal(total, 6);
});
Text
✔ the mutex prevents lost updates (5.2ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

Without the lock, the same test would end with 3 or another partial sum, depending on the order of writes.

Also inAsync
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.