How-To Guide

How to Implement a Fair Async Mutex

Serialize access to a shared resource with a FIFO lock so no task starves and lock waits are observable.

On this page

  1. Introduction
  2. When You Need a Mutex in Async Code
  3. A Naive Lock and Why It Starves
  4. A FIFO Queue of Waiters
  5. Using the Mutex Around a Critical Section
  6. Timeouts, Cancellation and Reentrancy
  7. Read-Write Locks
  8. Observing Contention
  9. Conclusion

Introduction

Some resources cannot be shared concurrently inside a single process: a file that must be read-modify-written, a non-thread-safe client, or a section of code that must not interleave with itself. A mutex serializes access. In async code a naive mutex uses a boolean flag, and a boolean flag is unfair: a task that arrives while the lock is held may be queued behind a task that arrives repeatedly, and under load some tasks wait forever. A fair mutex keeps a first-in-first-out queue so every waiter eventually gets the lock in order. This article builds such a mutex, adds timeouts and observability, and contrasts it with a read-write lock for read-heavy work.

When You Need a Mutex in Async Code

JavaScript runs one task at a time, so it never interleaves within a single synchronous block. But an async function with an await yields control, and another task can run during the gap. That is exactly where a read-modify-write breaks: read the counter, await a network call, write the counter back, and a concurrent task that also read the old value overwrites your write. A mutex wraps the critical section so the read, the await and the write happen without another task entering.

Use it for genuine mutual exclusion, not as a general queue. If the resource can actually handle concurrency, a semaphore with more than one permit is the right tool; a mutex is a semaphore of one. Reach for a mutex when interleaving is incorrect, not merely inconvenient.

A Naive Lock and Why It Starves

The naive lock is a boolean plus a poll or a single shared promise. It works until several tasks contend: with a single shared promise, every waiter races to acquire the lock when it resolves, and the winner is arbitrary. A task that keeps losing the race may wait indefinitely while newer tasks repeatedly win. That is starvation, and it appears only under contention, which is when you least want a surprise.

Fairness means the order waiters acquire is the order they arrived. That requires a queue, not a flag. The queue is the whole point of a fair mutex and it is barely more code than the unfair version.

A FIFO Queue of Waiters

The mutex holds a boolean locked and an array of resolvers. Acquire: if not locked, set locked and return; otherwise push a resolver and await it. Release: if there is a waiter, shift it and resolve it, transferring the lock directly to that waiter without setting locked to false (so another arriving task cannot jump the queue); if there are no waiters, set locked to false.

class FairMutex {
  constructor() {
    this.locked = false;
    this.waiters = [];   // FIFO queue of resolve functions
  }
  async acquire() {
    if (!this.locked) {
      this.locked = true;
      return;
    }
    await new Promise((resolve) => this.waiters.push(resolve));
  }
  release() {
    const next = this.waiters.shift();
    if (next) {
      next();            // hand the lock to the next waiter in order
    } else {
      this.locked = false;
    }
  }
  async runExclusive(task) {
    await this.acquire();
    try { return await task(); }
    finally { this.release(); }
  }
}

Using the Mutex Around a Critical Section

Wrap the critical section in runExclusive so release happens even if the task throws. The mutex guarantees that only one task is inside the section at a time and that tasks enter in arrival order. Keep the section as short as possible: holding the lock across a slow remote call serializes every waiting task behind it, which is correct but can be slow, so do setup and teardown outside the lock when they do not need exclusivity.

const mutex = new FairMutex();
let counter = 0;

async function increment() {
  return mutex.runExclusive(async () => {
    const current = counter;
    await new Promise((r) => setTimeout(r, 10)); // simulate async work
    counter = current + 1;
    return counter;
  });
}

// Runs one at a time in arrival order; final counter is exact.
await Promise.all(Array.from({ length: 100 }, () => increment()));

Timeouts, Cancellation and Reentrancy

A waiter that can never acquire because the holder crashed is a leak. Add a timeout to acquire that removes the waiter from the queue on expiry, otherwise a timed-out waiter may later be resolved and hold a lock nobody will release. Support cancellation the same way, removing the waiter when its signal aborts.

Do not make the mutex reentrant by accident. If a task that holds the lock calls a function that tries to acquire the same lock, a naive mutex deadlocks. Reentrancy requires tracking the owning task, which is hard in a language without task identity; the simpler discipline is to never acquire the same lock twice on one path. If you truly need reentrancy, pass the critical section down explicitly rather than re-acquiring.

Read-Write Locks

When readers can run concurrently but writers need exclusivity, a read-write lock beats a plain mutex. It admits any number of readers, but a writer waits until readers drain and blocks new readers until it finishes. The risk is writer starvation if readers keep arriving; a fair version queues writers so a new reader cannot jump ahead of a waiting writer. Use it for a cache that many requests read and few invalidate.

Prefer the simplest lock that is correct. If reads are not actually concurrent-heavy, a mutex is easier to reason about. Read-write locks add states and therefore add bugs; adopt one only when the read concurrency clearly pays for the complexity.

Observing Contention

Expose the current queue length and the time tasks spend waiting. A mutex with a persistently non-empty queue is a bottleneck: either the critical section is too long or the work should not be serialized at all. Average wait time that grows with load is the signature of queuing, and it tells you to shorten the section or remove the lock.

Also watch for the opposite: a lock that is never contended is pure overhead and can often be deleted. Measure before keeping a lock, and keep it only if it prevents a real interleaving bug. A mutex is a correctness tool, not a habit.

Conclusion

A fair async mutex serializes a critical section and guarantees that waiters acquire in arrival order, which a boolean flag cannot do. Build it from a locked state plus a FIFO queue of resolvers, hand the lock directly to the next waiter on release, and always release in a finally so no permit leaks. Add acquire timeouts and cancellation that remove waiters from the queue, avoid accidental reentrancy, and use a read-write lock only when read concurrency is genuinely high. Expose the queue length so contention is visible, and delete the lock when it turns out nothing needed it.

Sources: async-mutex (npm), Mutual exclusion, Read-write lock.

FAQ

Why is a boolean lock unfair?
With a single shared promise or a poll, every waiter races to acquire when the lock frees, so the winner is arbitrary and a task can lose repeatedly while newer tasks win. A FIFO queue hands the lock to the next waiter in arrival order, preventing starvation.
When should I use a read-write lock instead of a mutex?
When many readers can safely run concurrently and only writers need exclusivity, such as a cache read by requests and invalidated rarely. If reads are not genuinely concurrent-heavy, a plain mutex is simpler and less bug-prone.

Related Examples