← Blog

Claude skill async race condition security — SA-SKL-ASYNCRACE2

Race conditions in async JavaScript MCP skills go beyond the classic TOCTOU check-then-act pattern. Four advanced variants appear repeatedly in community skill audits: shared mutable state read by concurrent Promise.all branches, missing atomic Redis operations for distributed mutual exclusion, async boundaries that escape a held lock, and ORM transactions that read without locking rows. SA-SKL-ASYNCRACE2-001 through ASYNCRACE2-004 document each with production-quality fixes.

By SkillAudit  |  6 Nov 2026

Why advanced async race conditions are distinct from basic TOCTOU

The classic TOCTOU pattern — check a condition, then act on it in a later statement — is well understood. Advanced async race conditions are subtler: the read and write may both be inside a transaction or behind a lock, yet the transaction lacks row-level locking, or the lock does not remain held across the await boundary. In Node.js every await suspends the current function and yields control to the event loop, so a second concurrent request can interleave between any two awaited statements even when the developer intended them to be atomic. MCP skills that handle credits, balance deductions, file writes, or distributed scheduling are especially exposed because the window between read and write is hidden inside innocent-looking async/await syntax.

SA-SKL-ASYNCRACE2 in scope: ASYNCRACE2-001 (Promise.all shared mutable balance), ASYNCRACE2-002 (non-atomic Redis GET+SET mutex), ASYNCRACE2-003 (file lock escaped across await boundary), ASYNCRACE2-004 (Prisma transaction without SELECT FOR UPDATE). All four are detected by SkillAudit's data-flow and concurrency pattern analysis.

ASYNCRACE2-001 — Promise.all with shared mutable state

When two concurrent API requests both call an async function that reads a balance, computes a new value, and writes it back, the operations interleave at every await. Both branches read the same balance before either has written a new one. Each then subtracts its own amount from the stale read value and stores the result — the second write silently overwrites the first, and one deduction is lost. This is a classic lost-update race, but it is easy to miss because each individual function looks correct in isolation and the calls are hidden inside a Promise.all.

// VULNERABLE: two concurrent callers both read then write the same balance
async function deductBalance(id, amount) {
  const bal = await getBalance(id);       // both callers read bal = 100
  const newBal = bal - amount;            // caller A: 100-30=70; caller B: 100-50=50
  await setBalance(id, newBal);           // caller B writes 50, overwriting A's 70
  return newBal;
}

// Called concurrently — interleaving guaranteed at each await
await Promise.all([
  deductBalance(userId, 30),   // should leave 70
  deductBalance(userId, 50),   // should leave 20 (or fail if balance insufficient)
]);
// Actual result: balance is 50 — the 30-unit deduction is silently lost
// FIXED: atomic database-level decrement with a guard condition
// Uses a single UPDATE statement — no separate read, no race window
async function deductBalance(id, amount) {
  const result = await db.query(
    `UPDATE balances
        SET balance = balance - $1
      WHERE id = $2
        AND balance >= $1
  RETURNING balance`,
    [amount, id]
  );
  if (result.rowCount === 0) {
    throw new Error('Insufficient balance or concurrent update conflict');
  }
  return result.rows[0].balance;
}

// Now safe to run concurrently — the database serialises the UPDATE
await Promise.all([
  deductBalance(userId, 30),
  deductBalance(userId, 50),
]);
// One succeeds, the other throws if balance is insufficient — no lost update
CRITICAL
SA-SKL-ASYNCRACE2-001 — MCP skill reads a mutable value with one async call and writes the modified value with a second async call; concurrent invocations (including those spawned by Promise.all) interleave between the read and write, causing lost updates. Fix: replace the read-modify-write sequence with a single atomic database UPDATE … WHERE balance >= amount RETURNING balance; check rowCount === 1 to detect contention; never read application-side before writing numeric counters.

ASYNCRACE2-002 — Missing Redis SETNX atomicity

A common pattern for distributed mutual exclusion in MCP skills is to check whether a Redis key exists before setting it, treating the key as a lock. The flaw is that redis.get(lockKey) and redis.set(lockKey, …) are two separate network round-trips with an await in between. Two requests that arrive at the same millisecond both send GET, both receive null, both decide the lock is free, and both execute SET. Both proceed into the critical section simultaneously, defeating the entire mutex.

// VULNERABLE: GET and SET are two round-trips — race window between them
async function acquireLock(lockKey) {
  const existing = await redis.get(lockKey);  // request A: null
                                               // request B: null  (before A sets)
  if (existing) {
    return false; // lock taken
  }
  await redis.set(lockKey, '1', 'EX', 30);    // A sets; B also sets
  return true;    // both return true — both enter critical section
}

if (await acquireLock('job:send-email')) {
  await sendEmail(user);   // runs twice concurrently
  await redis.del('job:send-email');
}
// FIXED: SET … NX EX is a single atomic command — no race window
// ioredis: redis.set(key, value, 'NX', 'EX', seconds)
// Returns 'OK' if the key was set (lock acquired), null if already set

async function acquireLock(lockKey, ttlSeconds = 30) {
  const result = await redis.set(lockKey, '1', 'NX', 'EX', ttlSeconds);
  return result === 'OK';   // only one concurrent caller gets 'OK'
}

async function releaseLock(lockKey) {
  await redis.del(lockKey);
}

if (await acquireLock('job:send-email')) {
  try {
    await sendEmail(user);  // only one concurrent caller reaches here
  } finally {
    await releaseLock('job:send-email');
  }
}
HIGH
SA-SKL-ASYNCRACE2-002 — MCP skill implements a distributed Redis lock using a GET check followed by a separate SET; the two-command sequence is not atomic and allows concurrent requests to both observe a missing key and both acquire the lock simultaneously. Fix: use the single-command SET key value NX EX ttl pattern (redis.set(key, '1', 'NX', 'EX', 30) in ioredis); check that the return value is 'OK' before entering the critical section; always release the lock in a finally block.

ASYNCRACE2-003 — File lock not held across async boundary

File-based locking libraries such as proper-lockfile create a lock file synchronously to signal exclusive access. The lock works correctly for synchronous code, but most MCP skill handlers are async. Every await inside the locked section yields to the Node.js event loop, and if the lock has a TTL (many libraries default to 5–30 seconds to prevent stale locks) it can expire and be garbage-collected before the async work completes. A second request then acquires the lock while the first is still inside the critical section. Additionally, the lock is not automatically re-acquired after each await resumes — the first holder is unaware it has lost the lock.

// VULNERABLE: file lock expires or is released before async work finishes
const lockfile = require('proper-lockfile');

async function processFile(filePath) {
  const release = await lockfile.lock(filePath, { stale: 5000 }); // 5 s TTL
  try {
    const data = JSON.parse(await fs.readFile(filePath, 'utf8'));
    // await yields to event loop; if readFile takes > 5 s the lock expires
    await slowNetworkCall(data);   // another request acquires the lock here
    await fs.writeFile(filePath, JSON.stringify(updated)); // concurrent write!
  } finally {
    await release();
  }
}
// Root cause: proper-lockfile TTL is wall-clock, not tied to the async call stack;
// Node.js event-loop interleaving means the lock can expire mid-operation
// FIXED (single-process): use async-mutex — lock survives await boundaries
const { Mutex } = require('async-mutex');
const fileMutex = new Mutex();

async function processFile(filePath) {
  const release = await fileMutex.acquire();
  try {
    const data = JSON.parse(await fs.readFile(filePath, 'utf8'));
    await slowNetworkCall(data);   // mutex stays held — no other caller proceeds
    await fs.writeFile(filePath, JSON.stringify(updated));
  } finally {
    release();  // synchronous release; no await needed
  }
}

// FIXED (multi-process): Redis SET NX with explicit TTL extension via watchdog
// Set lock TTL well above maximum expected operation duration, then extend:
// const watchdog = setInterval(
//   () => redis.pexpire(lockKey, ttlMs), Math.floor(ttlMs / 2)
// );
// clearInterval(watchdog) in finally before releasing the key
HIGH
SA-SKL-ASYNCRACE2-003 — MCP skill acquires a file-based lock then performs async work inside the locked section; the file lock TTL can expire during awaited I/O or network calls, releasing the lock while the first holder is still operating, allowing a second request to acquire and enter the critical section concurrently. Fix: for single-process skills replace file locks with async-mutex whose Mutex correctly survives await boundaries; for multi-process skills use Redis SET NX with a TTL significantly longer than the worst-case operation duration and a watchdog timer to extend the lease before expiry.

ASYNCRACE2-004 — Prisma transaction read-modify-write without SELECT FOR UPDATE

Wrapping a read-modify-write in a Prisma $transaction does not automatically serialize concurrent transactions. The default PostgreSQL isolation level is READ COMMITTED, which means two concurrent transactions can both read the same row value before either commits. Both compute the same modified value, both write it, and both commit successfully — but only one charge is recorded. This is a lost-update race inside a transaction, and it is particularly dangerous for billing, credit deduction, and inventory reservation logic where the developer believes the transaction provides full isolation.

// VULNERABLE: Prisma transaction without row-level locking
// Two concurrent transactions both read credits = 10, both write 5
await prisma.$transaction(async (tx) => {
  const user = await tx.user.findUnique({ where: { id } });
  // READ COMMITTED: second transaction also reads credits = 10 here
  if (user.credits < cost) throw new Error('Insufficient credits');
  const newCredits = user.credits - cost;   // both compute 10 - 5 = 5
  await tx.user.update({
    where: { id },
    data: { credits: newCredits },          // both write 5 — one charge lost
  });
});
// Both transactions commit successfully; user charged once instead of twice
// FIXED option A: SELECT FOR UPDATE acquires a row-level lock
await prisma.$transaction(async (tx) => {
  // Raw query acquires an exclusive row lock before reading
  const [user] = await tx.$queryRaw`
    SELECT * FROM users WHERE id = ${id} FOR UPDATE
  `;
  if (user.credits < cost) throw new Error('Insufficient credits');
  const newCredits = user.credits - cost;
  await tx.user.update({ where: { id }, data: { credits: newCredits } });
  // Second concurrent transaction blocks on FOR UPDATE until this commits
});

// FIXED option B: atomic conditional UPDATE without a separate read
// Single statement — no race window, no transaction wrapper needed
const result = await prisma.user.updateMany({
  where: { id, credits: { gte: cost } },      // guard: only update if sufficient
  data:  { credits: { decrement: cost } },    // atomic decrement
});
if (result.count === 0) {
  throw new Error('Insufficient credits or concurrent update conflict');
}
CRITICAL
SA-SKL-ASYNCRACE2-004 — MCP skill wraps a read-modify-write in a Prisma $transaction without acquiring a row-level lock; at the default READ COMMITTED isolation level two concurrent transactions both read the same value before either commits, both compute an identical decrement, and both commit — one charge or reservation is silently lost. Fix: use SELECT … FOR UPDATE via tx.$queryRaw to acquire a row-level lock inside the transaction, or replace the read-modify-write with a single atomic prisma.user.updateMany using a gte guard and decrement data field; check result.count === 1.

SkillAudit detection summary — SA-SKL-ASYNCRACE2

FindingSeverityRoot CauseFix
ASYNCRACE2-001CRITICALConcurrent Promise.all branches read shared mutable balance, each computes a decrement from the same stale value, last write winsReplace read-modify-write with atomic UPDATE … WHERE balance >= amount RETURNING balance; check rowCount === 1
ASYNCRACE2-002HIGHRedis mutex uses GET then SET as two separate commands; concurrent requests both see null from GET and both acquire the lockUse single atomic SET key value NX EX ttl; only proceed when return value is 'OK'
ASYNCRACE2-003HIGHFile lock TTL expires during async work inside the locked section; Node.js event-loop yields on every await, lock not re-acquired on resumeUse async-mutex for single-process; Redis SET NX with watchdog TTL extension for multi-process
ASYNCRACE2-004CRITICALPrisma $transaction at READ COMMITTED isolation reads without row lock; concurrent transactions both commit the same decrement, one charge lostSELECT … FOR UPDATE inside transaction, or atomic updateMany with gte guard and decrement; check result.count === 1

Related patterns: For the classic TOCTOU check-then-act race condition in MCP skills, see SA-SKL-BRUTEFORCE. For transaction log integrity gaps that can mask race condition exploitation, see SA-SKL-TXLOG. For rate-limiting gaps that allow an attacker to amplify race condition windows, see SA-SKL-RATELIMIT2.