← Blog

Claude skill async/await race conditions and concurrent API handler vulnerabilities — SA-SKL-ASYNCRACE2

Node.js is single-threaded but async/await does not make it safe from race conditions. Every await is a suspension point where another concurrent coroutine can run — and when two coroutines share mutable state (a database row, a Redis key, a filesystem path, a uniqueness invariant) without atomic operations, they can each observe a consistent-looking snapshot of the world just before the other modifies it. SA-SKL-ASYNCRACE2 covers four patterns unique to MCP skill concurrent API handlers: double-spend via non-transactional credit debit, Redis cache stampede from simultaneous cache misses, file TOCTOU between fs.access and fs.writeFile, and Promise.all duplicate record creation that bypasses application-level existence checks.

By SkillAudit  |  7 Nov 2026

ASYNCRACE2-001 — Double-spend via async credit debit without DB transaction

Credit and balance systems are the highest-stakes targets for async race conditions. The classic double-spend scenario unfolds when a POST /use-credit endpoint performs two independent database operations: a SELECT balance FROM accounts WHERE id = $1 to read the current balance, and an UPDATE accounts SET balance = balance - 5 to deduct the amount. These are two separate round-trips to the database, separated by an await boundary. When two requests arrive concurrently — close enough in time that both reach the SELECT before either reaches the UPDATE — both observe the same balance value. Both pass the sufficiency check. Both execute the deduction. And both succeed.

With a starting balance of 10 and two concurrent requests each deducting 5, the correct final balance is 0. The vulnerable result is 5: Request A reads balance=10, Request B reads balance=10 (before A's UPDATE has committed), Request A updates to balance=10-5=5, Request B updates to balance=10-5=5 (overwriting A's result). The user has spent 10 credits but their balance shows 5 — they have effectively doubled their purchasing power. Under sustained concurrent load with an automated script, a user with 10 credits could purchase hundreds of items.

The core problem is that the read and the write must be atomic. PostgreSQL provides two mechanisms. The first is an explicit transaction with SELECT ... FOR UPDATE: the row-level lock acquired by FOR UPDATE forces the second concurrent SELECT to block until the first transaction commits, ensuring it sees the post-deduction balance. The second — and often more efficient — approach is a conditional atomic UPDATE: UPDATE accounts SET balance = balance - 5 WHERE id = $1 AND balance >= 5 RETURNING balance. The database engine evaluates both the condition and the update in a single operation. If rowCount === 0, the balance was insufficient (or the race was lost); the application returns an error. No separate SELECT is needed.

The RETURNING balance clause also gives the caller the post-update balance for free, eliminating any temptation to do a follow-up read. For distributed systems where multiple service instances share a Redis balance cache alongside the database, the cache must be invalidated or updated atomically with the database row — otherwise a cache hit on stale data can cause a third concurrent request to bypass the database check entirely.

// VULNERABLE — ASYNCRACE2-001
// POST /use-credit — two separate DB operations create a race window
app.post('/use-credit', authenticate, async (req, res) => {
  const userId = req.user.id;
  const cost = 5;

  // Step 1: read current balance
  const { rows } = await db.query(
    'SELECT balance FROM accounts WHERE id = $1',
    [userId]
  );
  const balance = rows[0].balance; // Request A: 10, Request B: 10 (both see same value)

  // Check sufficiency — both requests pass this check
  if (balance < cost) {
    return res.status(402).json({ error: 'Insufficient credits' });
  }

  // RACE WINDOW: both requests passed the check above and now both execute the UPDATE
  // Request A: balance = 10 - 5 = 5  ✓
  // Request B: balance = 10 - 5 = 5  ✓  (should have been 0, or should have failed)
  await db.query(
    'UPDATE accounts SET balance = balance - $1 WHERE id = $2',
    [cost, userId]
  );

  // Both requests succeed — user spent 10 credits, balance shows 5 (double-spend)
  res.json({ success: true, newBalance: balance - cost });
});
// FIXED — ASYNCRACE2-001: atomic conditional UPDATE with RETURNING
app.post('/use-credit', authenticate, async (req, res) => {
  const userId = req.user.id;
  const cost = 5;

  // Single atomic UPDATE: WHERE clause check + deduction happen as one DB operation
  // If balance < cost, no row is updated (rowCount === 0)
  const { rows, rowCount } = await db.query(
    `UPDATE accounts
     SET balance = balance - $1
     WHERE id = $2
       AND balance >= $1
     RETURNING balance`,
    [cost, userId]
  );

  if (rowCount === 0) {
    // Either insufficient balance or the row doesn't exist
    return res.status(402).json({ error: 'Insufficient credits' });
  }

  // Exactly one atomic operation succeeded; rows[0].balance is post-deduction value
  res.json({ success: true, newBalance: rows[0].balance });
});

// Alternative: explicit transaction with SELECT FOR UPDATE (useful when
// the deduction logic is more complex than a single expression)
app.post('/use-credit-tx', authenticate, async (req, res) => {
  const userId = req.user.id;
  const cost = 5;

  await db.transaction(async (trx) => {
    // FOR UPDATE acquires a row lock — concurrent transactions block here
    // until this transaction commits or rolls back
    const { rows } = await trx.query(
      'SELECT balance FROM accounts WHERE id = $1 FOR UPDATE',
      [userId]
    );
    if (!rows.length || rows[0].balance < cost) {
      throw Object.assign(new Error('Insufficient credits'), { status: 402 });
    }
    const { rows: updated } = await trx.query(
      'UPDATE accounts SET balance = balance - $1 WHERE id = $2 RETURNING balance',
      [cost, userId]
    );
    return updated[0].balance;
  }).then(newBalance => res.json({ success: true, newBalance }))
    .catch(err => res.status(err.status || 500).json({ error: err.message }));
});
HIGH
SA-SKL-ASYNCRACE2-001 — Credit debit endpoints that issue a separate SELECT then UPDATE in two distinct await calls allow concurrent requests to both read the same balance before either write, enabling unlimited double-spend where both deductions succeed against the same funds; fix by using a single UPDATE … WHERE balance >= cost RETURNING balance (rowCount=0 means failure) or a transaction with SELECT … FOR UPDATE to serialize the read-check-write cycle atomically. Detection: SkillAudit flags route handlers containing a SELECT balance (or similar) followed by a conditional UPDATE … SET balance = balance - … in separate await calls without an enclosing transaction or FOR UPDATE lock.

ASYNCRACE2-002 — Async cache stampede via non-atomic Redis set

Caching is introduced precisely to avoid expensive operations — heavy database queries, external API calls, complex computations. The standard pattern is cache-aside: check the cache, if hit return the cached value, if miss compute and store. The race condition appears when two or more requests arrive simultaneously and all miss the cache. Each coroutine suspends at the first await redis.get(key), both see null, both proceed to compute the expensive result, and both call await redis.set(key, result). Under light concurrency the worst consequence is wasted computation — both results are correct and one silently overwrites the other. Under heavy concurrency the problem becomes a cache stampede: when 1000 concurrent requests all miss a just-expired cache entry, all 1000 hit the database simultaneously, potentially collapsing the database under load that the cache was designed to absorb.

A second subtlety is result inconsistency. If the expensive computation is non-deterministic (calling an external LLM API, reading a file that changes between calls, or computing based on current time), the two concurrent computations may produce different results. One overwrites the other silently and there is no error — the cache contains whichever result wrote last, and that may or may not be the most recent or correct value. For billing summaries, audit counts, or permission snapshots, this silent inconsistency is a security concern, not merely a correctness concern.

The fix for simple two-request races is Redis SET key value EX 300 NX: the NX (not exists) flag makes the set conditional and atomic at the Redis level — only the first writer wins, all others' writes are silently ignored. For cache stampede under high concurrency, the solution is a distributed mutex: before computing the expensive value, attempt to acquire a short-lived lock (SET lockKey '' NX EX 5). Only the holder of the lock computes and populates the cache; all other concurrent requests either wait and re-check, or return a stale value if one is available. This reduces N concurrent database queries to exactly 1 during the cache-miss window.

Note that using NX alone does not solve stampede — it only ensures the first writer wins. All N requests still compute in parallel; they just don't all write. The mutex is essential for stampede prevention because it serializes computation, not just the write. For MCP skills where the expensive operation is an LLM call or an upstream API with rate limits, allowing N concurrent identical calls to proceed can exhaust rate limits and trigger upstream throttling, cascading into broader skill failures.

// VULNERABLE — ASYNCRACE2-002
// cache-handler.js — two separate operations create a race window
async function getCachedAuditSummary(repoId, redis, db) {
  const cacheKey = `audit:summary:${repoId}`;

  // Step 1: check the cache — 1000 concurrent requests all see null
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  // RACE WINDOW: all 1000 requests reach here simultaneously (cache miss)
  // All 1000 hit the database with the same query at the same time — stampede
  const result = await db.query(
    'SELECT COUNT(*) vulns, MAX(scanned_at) last_scan FROM audits WHERE repo_id = $1',
    [repoId]
  );
  const summary = result.rows[0];

  // All 1000 requests call redis.set — last writer wins (non-deterministic under LLM)
  // With a plain SET: each write silently overwrites the previous
  await redis.set(cacheKey, JSON.stringify(summary), 'EX', 300);
  return summary;
}
// FIXED — ASYNCRACE2-002: Redis SET NX for atomic conditional write (simple case)
async function getCachedAuditSummaryNX(repoId, redis, db) {
  const cacheKey = `audit:summary:${repoId}`;

  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  const result = await db.query(
    'SELECT COUNT(*) vulns, MAX(scanned_at) last_scan FROM audits WHERE repo_id = $1',
    [repoId]
  );
  const summary = result.rows[0];

  // NX flag: set only if the key does not exist — first writer wins atomically
  // 'EX', 300: 5-minute TTL; NX: set-if-not-exists
  await redis.set(cacheKey, JSON.stringify(summary), 'EX', 300, 'NX');
  return summary;
}

// FIXED — ASYNCRACE2-002: distributed mutex for stampede prevention (high-concurrency case)
async function getCachedAuditSummaryMutex(repoId, redis, db) {
  const cacheKey = `audit:summary:${repoId}`;
  const lockKey = `audit:summary:${repoId}:lock`;

  // Check cache first (fast path — no lock needed)
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  // Try to acquire the mutex — NX EX 5: lock expires in 5s even if holder crashes
  const lockAcquired = await redis.set(lockKey, '1', 'NX', 'EX', 5);

  if (!lockAcquired) {
    // Another coroutine is computing — poll the cache until it's populated
    // (in production: use exponential backoff or return stale value if available)
    for (let i = 0; i < 10; i++) {
      await new Promise(r => setTimeout(r, 50 * (i + 1)));
      const retried = await redis.get(cacheKey);
      if (retried) return JSON.parse(retried);
    }
    // Fallback: compute anyway if lock holder timed out
  }

  try {
    // Only the mutex holder (or fallback) reaches here — single DB query
    const result = await db.query(
      'SELECT COUNT(*) vulns, MAX(scanned_at) last_scan FROM audits WHERE repo_id = $1',
      [repoId]
    );
    const summary = result.rows[0];
    // Write with NX so a racing fallback doesn't overwrite
    await redis.set(cacheKey, JSON.stringify(summary), 'EX', 300, 'NX');
    return summary;
  } finally {
    await redis.del(lockKey); // Release the mutex
  }
}
MEDIUM
SA-SKL-ASYNCRACE2-002 — Cache-aside patterns that issue a plain redis.set(key, value) after a cache miss allow all concurrent cache-missing requests to both compute the expensive result and overwrite each other's writes (silent last-writer-wins inconsistency), and under high concurrency cause a stampede where all requests simultaneously hit the backing database; fix with Redis SET key value EX ttl NX for atomic first-writer-wins semantics, and a distributed mutex (SET lockKey '' NX EX 5) to serialize computation under stampede conditions. Detection: SkillAudit flags redis.set calls not using the NX flag when they appear inside a cache-miss branch of a redis.get check in a concurrent handler.

ASYNCRACE2-003 — File TOCTOU between fs.access check and fs.writeFile

Time-of-check to time-of-use (TOCTOU) vulnerabilities in filesystems are a classic concurrency hazard. In Node.js async/await code, the pattern manifests as a two-step file existence guard: first await fs.promises.access(filePath) to check whether the file already exists (catching the error means it does not exist), then await fs.promises.writeFile(filePath, data) to write the new content. These are two separate system calls separated by an await boundary — and between them, another concurrent coroutine can execute.

When two MCP skill invocations both attempt to create the same output file — perhaps storing the results of a scan keyed by a repository name — both execute the fs.access check, both receive "file does not exist" (ENOENT), and both proceed to call fs.writeFile. The first write creates the file. The second write, which arrives fractions of a millisecond later, opens the file and truncates it before writing its own content. The first request's data is silently lost. If both requests were writing audit results for the same repository, one result is permanently discarded. If the write is part of a deduplication mechanism — storing a record to prevent double-processing — the second write overwrites the guard itself, defeating the deduplication entirely.

The correct fix is to combine the existence check and the creation into a single atomic system call. POSIX provides open(2) with the O_CREAT | O_EXCL flags: this call succeeds only if the file does not exist and creates it atomically in one operation. If the file already exists, the call fails with EEXIST — no TOCTOU window, no race. In Node.js this is fs.promises.open(filePath, 'wx'): the w flag opens for writing (creating if needed), and x sets O_EXCL. If the file already exists, the call throws an error with code === 'EEXIST', which the application catches and handles as a "file already exists, skip this write" branch.

An important subtlety: fs.promises.writeFile(filePath, data, { flag: 'wx' }) provides the same atomic create-exclusive semantics in a single call without needing to manually open and write. This is the most concise fix. For directories, fs.promises.mkdir(dirPath, { recursive: false }) throws EEXIST atomically if the directory already exists, making it the equivalent tool for directory creation guards.

// VULNERABLE — ASYNCRACE2-003
// output-writer.js — TOCTOU between access check and writeFile
import fs from 'fs/promises';
import path from 'path';

async function writeAuditOutput(repoName, auditData) {
  const outputPath = path.join('/srv/factory/agents/agent-14/data/audits', `${repoName}.json`);

  // Step 1: check if the file already exists
  let fileExists = false;
  try {
    await fs.access(outputPath); // throws ENOENT if file does not exist
    fileExists = true;
  } catch {
    fileExists = false; // ENOENT — file does not exist
  }

  if (fileExists) {
    throw new Error(`Audit output for ${repoName} already exists`);
  }

  // RACE WINDOW: both concurrent requests passed the existence check above
  // Both now call writeFile — second write truncates and overwrites first
  await fs.writeFile(outputPath, JSON.stringify(auditData, null, 2));
  // The first request's audit data is silently lost
  return outputPath;
}
// FIXED — ASYNCRACE2-003: atomic create with O_CREAT|O_EXCL via flag 'wx'
import fs from 'fs/promises';
import path from 'path';

async function writeAuditOutput(repoName, auditData) {
  const outputPath = path.join('/srv/factory/agents/agent-14/data/audits', `${repoName}.json`);

  try {
    // 'wx' flag = O_WRONLY | O_CREAT | O_EXCL — atomic: creates the file only
    // if it does not already exist. If it exists, throws EEXIST immediately.
    // No TOCTOU window — the check and the create are a single system call.
    await fs.writeFile(outputPath, JSON.stringify(auditData, null, 2), { flag: 'wx' });
    return outputPath;
  } catch (err) {
    if (err.code === 'EEXIST') {
      // File already exists — this is the expected "already written" case
      throw new Error(`Audit output for ${repoName} already exists`);
    }
    throw err; // Re-throw unexpected errors (EACCES, ENOSPC, etc.)
  }
}

// Alternative: explicit open + write for more control (e.g., streaming large files)
async function writeAuditOutputStream(repoName, auditData) {
  const outputPath = path.join('/srv/factory/agents/agent-14/data/audits', `${repoName}.json`);

  let fileHandle;
  try {
    // fs.open with 'wx' flag — POSIX open(2) with O_CREAT | O_EXCL
    // Throws EEXIST if file already exists — atomic, no race window
    fileHandle = await fs.open(outputPath, 'wx');
    await fileHandle.writeFile(JSON.stringify(auditData, null, 2));
    return outputPath;
  } catch (err) {
    if (err.code === 'EEXIST') {
      throw new Error(`Audit output for ${repoName} already exists`);
    }
    throw err;
  } finally {
    await fileHandle?.close();
  }
}
HIGH
SA-SKL-ASYNCRACE2-003 — File existence guards implemented as a separate fs.promises.access check followed by fs.promises.writeFile have a TOCTOU race window between the two await calls where a concurrent request also passes the check and both write the same file, with the second writer silently overwriting the first's data or defeating deduplication logic; fix by using the 'wx' flag on fs.promises.writeFile (or fs.promises.open) which atomically implements O_CREAT | O_EXCL and throws EEXIST if the file already exists. Detection: SkillAudit flags fs.promises.access or existsSync calls on a path that is then passed to writeFile in a subsequent await without using the 'wx' flag.

ASYNCRACE2-004 — Promise.all concurrent requests create duplicate records

Application-level uniqueness checks — querying the database for an existing record before inserting a new one — are fundamentally unsafe under concurrency. The pattern is ubiquitous: before creating a user, an organization, or any entity with a unique identifier, the application runs SELECT id FROM users WHERE email = $1. If the query returns a row, the application returns "already exists". If not, it proceeds with INSERT INTO users (email, …) VALUES ($1, …). Under sequential execution this works. Under concurrent execution it fails.

The Promise.all([createUser(email), createUser(email)]) pattern fires both invocations simultaneously. Both reach the SELECT before either has committed an INSERT. Both receive an empty result set. Both proceed to insert. Both inserts succeed (unless a database constraint intervenes). The database now contains two user rows with the same email address. This is a duplicate record vulnerability that can manifest in multiple ways: a user who registers twice gets two separate accounts with potentially different data; a payment system that creates a customer record on first charge creates two customers in Stripe; a MCP skill that initializes a user's audit quota creates two quota rows, one of which is ignored, effectively giving the user double the quota.

The correct fix operates at the database layer, not the application layer. A UNIQUE constraint on the email column makes the database enforce uniqueness atomically — no two transactions can commit rows with the same email. The INSERT from the second concurrent request will fail with PostgreSQL error code 23505 (unique_violation). The application catches this error code specifically and returns HTTP 409 Conflict, distinguishing it from unexpected errors. This converts a silent data corruption into a clean, recoverable error response. Never rely solely on application-level existence checks for uniqueness because the check and the insert are not atomic, regardless of how close together they appear in the code.

An alternative for PostgreSQL is INSERT INTO users … ON CONFLICT (email) DO NOTHING RETURNING id (or DO UPDATE SET … RETURNING id for upsert semantics). The ON CONFLICT clause is processed by the database engine as a single atomic operation: if the INSERT would violate the unique constraint, it is silently suppressed (DO NOTHING) or merged (DO UPDATE), and the RETURNING clause yields the existing row's ID. This eliminates both the application-level SELECT and the error handling for 23505, replacing them with a single idempotent INSERT statement.

// VULNERABLE — ASYNCRACE2-004
// user-service.js — application-level uniqueness check bypassed by concurrent requests
async function createUser(email, name) {
  // Step 1: check if user already exists
  const existing = await db.query(
    'SELECT id FROM users WHERE email = $1',
    [email]
  );

  if (existing.rows.length > 0) {
    throw new Error('User with this email already exists');
  }

  // RACE WINDOW: two concurrent createUser(sameEmail) both pass the check above
  // before either executes the INSERT below

  // Both inserts succeed — two user rows with the same email in the database
  const { rows } = await db.query(
    'INSERT INTO users (email, name, created_at) VALUES ($1, $2, now()) RETURNING id',
    [email, name]
  );
  return rows[0].id;
}

// Also vulnerable when called via Promise.all in a skill handler:
// await Promise.all([
//   createUser('alice@example.com', 'Alice'),  // first call
//   createUser('alice@example.com', 'Alice'),  // second call — race!
// ]);
// FIXED — ASYNCRACE2-004: DB UNIQUE constraint + catch error code 23505
// Migration (run once): ALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE (email);

async function createUser(email, name) {
  try {
    // No application-level SELECT — rely entirely on the database UNIQUE constraint
    // The constraint makes uniqueness enforcement atomic at the storage engine level
    const { rows } = await db.query(
      'INSERT INTO users (email, name, created_at) VALUES ($1, $2, now()) RETURNING id',
      [email, name]
    );
    return { id: rows[0].id, created: true };
  } catch (err) {
    if (err.code === '23505') {
      // PostgreSQL unique_violation — a row with this email already exists
      // Convert to a 409 Conflict HTTP response in the calling route handler
      throw Object.assign(new Error('User with this email already exists'), { status: 409 });
    }
    throw err; // Re-throw unexpected errors
  }
}

// Alternative: INSERT … ON CONFLICT for idempotent upsert semantics
async function createUserIdempotent(email, name) {
  // ON CONFLICT DO NOTHING: if email already exists, skip the insert atomically
  // RETURNING id: returns the new row's id (null if the insert was skipped)
  const { rows } = await db.query(
    `INSERT INTO users (email, name, created_at)
     VALUES ($1, $2, now())
     ON CONFLICT (email) DO NOTHING
     RETURNING id`,
    [email, name]
  );

  if (rows.length === 0) {
    // The insert was skipped — fetch the existing row's id
    const existing = await db.query('SELECT id FROM users WHERE email = $1', [email]);
    return { id: existing.rows[0].id, created: false };
  }

  return { id: rows[0].id, created: true };
}

// Now safe with concurrent calls:
// await Promise.all([
//   createUser('alice@example.com', 'Alice'),  // succeeds, returns id
//   createUser('alice@example.com', 'Alice'),  // throws 409 (createUser)
//                                               // or returns existing id (createUserIdempotent)
// ]);
HIGH
SA-SKL-ASYNCRACE2-004 — Application-level uniqueness checks (SELECT before INSERT) are bypassed by concurrent requests that both execute the SELECT before either commits the INSERT, allowing Promise.all or simultaneous API calls to produce duplicate records; fix by adding a database UNIQUE constraint on the column and catching PostgreSQL error code 23505 to return HTTP 409, or use INSERT … ON CONFLICT (col) DO NOTHING RETURNING id for idempotent atomic semantics — never rely solely on application-level existence checks for uniqueness. Detection: SkillAudit flags route handlers or service functions containing a SELECT … WHERE unique_col = $1 existence check immediately followed by an INSERT on the same table without an ON CONFLICT clause, especially when the function is called inside a Promise.all array.

Detection summary

ID Severity Pattern Fix
ASYNCRACE2-001 HIGH SELECT balance + UPDATE in separate awaits — concurrent reads both pass, double-spend Atomic UPDATE … WHERE balance >= cost RETURNING (rowCount=0 = fail) or SELECT FOR UPDATE in transaction
ASYNCRACE2-002 MEDIUM Cache miss without NX flag — concurrent misses stampede DB; last redis.set wins silently Redis SET key value EX ttl NX; distributed mutex (SET lock NX EX 5) for stampede prevention
ASYNCRACE2-003 HIGH fs.access then fs.writeFile TOCTOU — both pass check, second write overwrites first fs.promises.writeFile(path, data, { flag: 'wx' }) — atomic O_CREAT|O_EXCL; catch EEXIST
ASYNCRACE2-004 HIGH SELECT-before-INSERT uniqueness check bypassed by concurrent requests — duplicate records DB UNIQUE constraint + catch error code 23505 for 409; or INSERT … ON CONFLICT DO NOTHING

Related patterns: TOCTOU race condition security in MCP skills covers the broader class of time-of-check-to-time-of-use vulnerabilities beyond filesystem operations. SA-SKL-TIMING2 covers timing side-channel vulnerabilities in token comparison — a related class of concurrency-sensitive security issues where observable timing differences between code paths leak information about secret values.