How-To Guide

How to Avoid Async Deadlocks

Recognise and prevent deadlocks in async code: lock ordering, bounded waits, transaction scope and cancellation so a stall is impossible or fails fast.

On this page

  1. Introduction
  2. How Async Deadlocks Form
  3. Bounded Waits Turn Deadlock into Error
  4. Lock Ordering and Consistent Acquisition
  5. Transaction and Connection Scope
  6. Detection and Recovery
  7. Common Pitfalls and Conclusion

Introduction

Deadlock is the state where every participant is waiting for a resource another participant holds, and nothing can progress. In async code it is especially easy to create by accident, because awaiting inside a critical section, nesting locks in inconsistent order, or holding a database connection while awaiting a network call all silently convert a correct-looking flow into a permanent stall. Unlike a crash, a deadlock leaves the system alive but stuck, which makes it harder to detect and often worse to operate.

How Async Deadlocks Form

The classic cause is lock ordering. Task A takes lock 1 then waits for lock 2; task B takes lock 2 then waits for lock 1. Neither can proceed. In async code the same occurs with mutexes, database row locks, connection pool slots and semaphore permits. The fix is a global order: every task acquires resources in the same sequence, so a cycle cannot form.

The async-specific cause is awaiting while holding a resource. If a task holds a mutex and awaits a call that needs the same mutex, it deadlocks itself. If it holds a database connection and awaits a call that needs a connection from an exhausted pool, it deadlocks the pool. Any await inside a critical section is a candidate.

// DEADLOCK: holding the lock across an await that needs the same lock.
async function update(id: string) {
  return lock.withLock(id, async () => {
    const current = await load(id); // fine
    await lock.withLock(id, async () => save(current)); // re-enter: deadlock
  });
}
// FIX: compute the new value before re-acquiring, or use one lock scope.
async function updateFixed(id: string) {
  const current = await load(id);
  return lock.withLock(id, async () => save(current));
}

Bounded Waits Turn Deadlock into Error

A deadlock you cannot prevent, you can at least detect by bounding every wait. If a lock, a pool checkout or a channel receive can wait forever, a bug becomes a permanent stall; if it has a timeout, the same bug becomes a fast, loud failure you can alert on. Bounded waits convert unbounded damage into a diagnosable event.

Set the bound below the caller’s own deadline so the outer layer still has time to fail gracefully or retry. The timeout should be a clear, distinct error, not a generic one, so the alerting and the logs name “lock timeout” rather than “unknown failure”, which is what makes the incident tractable.

async function withDeadline<T>(p: Promise<T>, ms: number, label: string): Promise<T> {
  let timer: NodeJS.Timeout;
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new Error('deadlock_timeout: ' + label)), ms);
  });
  try {
    return await Promise.race([p, timeout]);
  } finally {
    clearTimeout(timer!);
  }
}

await withDeadline(lock.acquire(id), 2000, 'lock:' + id); // fails, not hangs

Lock Ordering and Consistent Acquisition

Establish a global order over all lockable resources and require every acquisition to follow it. If resources are keys, sort them before acquiring, so two tasks that need the same two keys always take them in the same order. For hierarchical resources, acquire parent before child, always. A single, enforced order removes the cycle structure that deadlock requires.

When you must acquire more than one resource, acquire all or none: try to take them all and release everything if any fails, rather than holding a partial set while waiting for the rest. This reduces the window in which two tasks hold complementary halves of a set, which is the prelude to the cycle.

async function lockAll(keys: string[], lock: KeyedLock) {
  const ordered = [...keys].sort();         // global order: sorted acquisition
  const held: Array<() => void> = [];
  try {
    for (const key of ordered) {
      held.push(await lock.acquire(key));   // always in the same sequence
    }
  } catch (err) {
    held.forEach((release) => release());   // all-or-none: release partials
    throw err;
  }
  return () => held.reverse().forEach((release) => release());
}

Transaction and Connection Scope

Database deadlocks come from transactions holding locks while waiting for other locks. Keep transactions short and never make a network call inside a transaction: fetching a remote resource while holding row locks invites both a database deadlock and a pool exhaustion deadlock. Do all external calls before you begin the transaction, or after it commits.

Also avoid holding a connection while awaiting unrelated work. A pool with every connection held by a task that is itself waiting for another connection cannot recover. Check out a connection, use it, return it promptly, and never await something that needs a connection while holding one.

// BAD: network call inside the transaction holds row locks and a connection.
async function bad() {
  await db.transaction(async (tx) => {
    await tx.update('inventory', { id }, { qty: -1 });
    await http.get('https://pricing.example.com/' + id); // holds tx open, long
  });
}
// GOOD: fetch outside the transaction; keep the tx short.
async function good() {
  const price = await http.get('https://pricing.example.com/' + id);
  await db.transaction(async (tx) => {
    await tx.update('inventory', { id }, { qty: -1 });
    await tx.update('prices', { id }, { price });
  });
}

Detection and Recovery

Even with the above, deadlocks can happen, so plan to detect and recover. Log every acquisition and release with an id and a timestamp so a stall can be reconstructed. When a bounded wait times out, capture the stack of the waiting task and the holder of the resource, so the cycle is visible instead of inferred.

For database deadlocks, most engines detect the cycle and abort one transaction; make your code retry on that specific error rather than treating it as fatal, with backoff and a retry limit. For in-process deadlocks, a watchdog that fires when no progress is made for a threshold can restart the affected worker, which is often the fastest path back to health.

Common Pitfalls and Conclusion

Do not await inside a critical section unless you have proven it cannot re-enter. Do not adopt inconsistent lock order across modules. Do not hold a connection or transaction across a network call. Do not leave waits unbounded. And do not assume your code has no deadlocks because it “works in staging”; deadlocks are timing-dependent and often only appear under production concurrency.

Async deadlocks come from waiting while holding, from inconsistent ordering, and from unbounded waits. Prevent them with a global order, all-or-none acquisition, short transactions and no awaits inside critical sections; detect them with bounded waits and acquisition logs; recover with retries and watchdogs. The goal is not that stalls never happen, but that when they would, the system fails fast and tells you where.

Sources: PostgreSQL: Deadlocks, Microsoft: Deadlock prevention, Node.js: AsyncResource and locks.

FAQ

What is the fastest way to stop an async deadlock from hanging forever?
Bound every wait: put a timeout on lock acquisition, pool checkout and channel receive, shorter than the caller deadline. A deadlock then surfaces as a fast, named error instead of an indefinite stall.
Why is a network call inside a database transaction dangerous?
It holds row locks and a pool connection for the duration of the call, so concurrent transactions and other pool users can block on it, creating both database deadlocks and connection-pool exhaustion. Do external calls before or after the transaction.

Related Examples