Claude skill async race conditions in concurrent MCP tool calls — SA-SKL-ASYNCRACE3
Node.js MCP skills are single-threaded but handle many concurrent tool calls via the event loop. When multiple calls arrive within the same event loop tick and share mutable state — a quota counter, a database row, a webhook handler, a temp file path — the absence of atomic operations or row-level locks creates race windows where two concurrent operations both succeed where only one should. SA-SKL-ASYNCRACE3 covers four patterns: check-then-act quota bypass, parallel database write corruption, duplicate webhook processing, and file write race in parallel scan jobs.
ASYNCRACE3-001 — Check-then-act race on audit quota
Free-tier audit quota enforcement is a canonical check-then-act race: read the current usage count, compare against the limit, if under the limit increment and proceed. When two concurrent requests both read the quota at the same time (before either has incremented), both see the same count value — say 2 of a 3-audit free limit — both pass the check, and both proceed to run an audit, consuming 2 slots simultaneously. The user ends up running 4 audits in a free month instead of 3 by simply sending two simultaneous requests. With more concurrency (e.g. a script submitting 10 simultaneous requests), the user bypasses the quota entirely. The fix is an atomic decrement-or-reject: use Redis Lua script (DECR + reject if result is negative) or a database transaction with SELECT FOR UPDATE so the read and the decrement happen in one atomic operation.
// VULNERABLE — ASYNCRACE3-001
// quota.js — check-then-act pattern with two separate DB operations
async function checkAndConsumeQuota(userId) {
// Step 1: read current usage
const { audits_used, audits_limit } = await db.query(
'SELECT audits_used, audits_limit FROM quotas WHERE user_id = $1',
[userId]
);
// Step 2: check the limit
if (audits_used >= audits_limit) {
throw new Error('Monthly audit quota exceeded');
}
// RACE WINDOW: two concurrent requests both pass the check here
// before either executes the UPDATE below
// Step 3: increment usage
await db.query(
'UPDATE quotas SET audits_used = audits_used + 1 WHERE user_id = $1',
[userId]
);
return true; // allowed — both concurrent requests return true
}
// FIXED — ASYNCRACE3-001: atomic conditional increment via UPDATE ... RETURNING
async function checkAndConsumeQuota(userId) {
// Single atomic UPDATE that only increments if under the limit
// The WHERE clause check and the increment are one operation at the DB level
const result = await db.query(
`UPDATE quotas
SET audits_used = audits_used + 1
WHERE user_id = $1
AND audits_used < audits_limit
RETURNING audits_used, audits_limit`,
[userId]
);
if (result.rowCount === 0) {
// No row updated — either user not found or quota exhausted
throw new Error('Monthly audit quota exceeded');
}
return true; // exactly one slot consumed atomically
}
// Alternative: Redis Lua script for in-memory quota (sub-millisecond latency)
const QUOTA_DECR_SCRIPT = `
local key = KEYS[1]
local remaining = tonumber(redis.call('GET', key) or 0)
if remaining <= 0 then return -1 end
return redis.call('DECR', key)
`;
async function checkAndConsumeQuotaRedis(userId, redis) {
const remaining = await redis.eval(QUOTA_DECR_SCRIPT, 1, `quota:${userId}`);
if (remaining < 0) throw new Error('Monthly audit quota exceeded');
return true;
}
UPDATE … WHERE audits_used < audits_limit RETURNING query (0 rows updated = quota exceeded) or a Redis Lua script that atomically checks and decrements in one round-trip. Detection: SkillAudit flags quota-enforcement code that executes a SELECT on a usage counter followed by a conditional UPDATE in separate await calls without an enclosing database transaction.ASYNCRACE3-002 — Parallel database writes without row-level locking corrupt aggregate scores
MCP skills that maintain aggregate scores — total audits run, average vulnerability density, cumulative scan time — often use a read-modify-write cycle in application code: read the current aggregate, compute the new value, write it back. Under concurrent load from parallel tool calls or background workers, two operations can both read the same current value and both write different updates based on the stale read. The second write overwrites the first without incorporating its change, losing one update entirely. This is the classic lost-update problem. For a skill audit score (e.g. a repository's rolling average vulnerability count), two concurrent audits of the same repo could both read score=5.0 and both write score=4.5 and score=6.0 — the final value is 6.0 but the correct value accounting for both audits might be 5.25. The fix is SELECT FOR UPDATE within a transaction to hold a row lock for the duration of the read-modify-write cycle, preventing any other transaction from reading the row until the update commits.
// VULNERABLE — ASYNCRACE3-002
// score-updater.js — lost-update race on aggregate score
async function updateRepoAuditScore(repoId, newVulnCount) {
// Both concurrent audit jobs execute this simultaneously for the same repoId:
const repo = await db.query(
'SELECT avg_vuln_count, total_audits FROM repos WHERE id = $1',
[repoId]
);
// Job A reads: avg=5.0, total=10 — computes new avg = (5.0*10 + 3) / 11 = 4.82
// Job B reads: avg=5.0, total=10 — computes new avg = (5.0*10 + 7) / 11 = 5.18
const { avg_vuln_count, total_audits } = repo.rows[0];
const newAvg = (avg_vuln_count * total_audits + newVulnCount) / (total_audits + 1);
// Job A writes: avg=4.82, total=11
// Job B writes: avg=5.18, total=11 ← overwrites Job A's write — LOST UPDATE
// Correct result should be avg=(5.0*10 + 3 + 7) / 12 = 4.92, total=12
await db.query(
'UPDATE repos SET avg_vuln_count = $1, total_audits = $2 WHERE id = $3',
[newAvg, total_audits + 1, repoId]
);
}
// FIXED — ASYNCRACE3-002: SELECT FOR UPDATE + transaction serializes concurrent updates
async function updateRepoAuditScore(repoId, newVulnCount) {
await db.transaction(async (trx) => {
// SELECT FOR UPDATE acquires a row lock — concurrent transactions block here
// until this transaction commits or rolls back
const repo = await trx.query(
'SELECT avg_vuln_count, total_audits FROM repos WHERE id = $1 FOR UPDATE',
[repoId]
);
const { avg_vuln_count, total_audits } = repo.rows[0];
const newTotal = total_audits + 1;
const newAvg = (avg_vuln_count * total_audits + newVulnCount) / newTotal;
await trx.query(
'UPDATE repos SET avg_vuln_count = $1, total_audits = $2 WHERE id = $3',
[newAvg, newTotal, repoId]
);
// Lock released on commit — now the next concurrent transaction can proceed
});
}
// Alternative: use UPDATE with arithmetic — avoids the read entirely
async function updateRepoAuditScoreAtomic(repoId, newVulnCount) {
await db.query(
`UPDATE repos
SET avg_vuln_count = (avg_vuln_count * total_audits + $1) / (total_audits + 1),
total_audits = total_audits + 1
WHERE id = $2`,
[newVulnCount, repoId]
); // Single statement — the DB serializes it; no race possible
}
SELECT … FOR UPDATE to serialize concurrent access to the row, or by rewriting the update as a single UPDATE … SET col = col + delta statement that the database serializes atomically. Detection: SkillAudit flags application-level read-modify-write patterns (a SELECT followed by an UPDATE on the same row in separate await calls) outside of a serializable transaction or FOR UPDATE lock.ASYNCRACE3-003 — Concurrent webhook processing without idempotency key
Webhook delivery from Stripe, GitHub, or Slack does not guarantee exactly-once delivery. Webhooks are retried on network errors or non-2xx responses, and infrastructure events (load balancer failover, pod restart mid-delivery) can cause the same event to be delivered twice within a short window. When two deliveries of the same webhook arrive simultaneously and both pass signature verification, a handler without an idempotency key processes the event twice: a Stripe payment_intent.succeeded event upgrades a user to Pro twice, charging nothing extra but creating duplicate database rows; a GitHub push event triggers two parallel scans of the same commit, consuming double the compute quota. The fix is a Redis SETNX (set-if-not-exists) on the webhook event ID before processing — the first delivery acquires the lock and processes; the second sees the key already set and returns 200 (acknowledging delivery without reprocessing).
// VULNERABLE — ASYNCRACE3-003
// webhook-handler.js — no idempotency check on event ID
app.post('/webhooks/stripe', verifyStripeSignature, async (req, res) => {
const event = req.body;
// Two simultaneous deliveries of event.id = 'evt_abc123' both reach this point
if (event.type === 'payment_intent.succeeded') {
const pi = event.data.object;
// Both handlers execute this — user row updated twice, duplicate emails sent
await db.query(
'UPDATE users SET plan = $1, plan_started_at = now() WHERE stripe_customer = $2',
['pro', pi.customer]
);
await sendUpgradeEmail(pi.customer);
}
res.status(200).json({ received: true }); // Both return 200 — no error to retry
});
// FIXED — ASYNCRACE3-003: SETNX on event ID prevents duplicate processing
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
app.post('/webhooks/stripe', verifyStripeSignature, async (req, res) => {
const event = req.body;
const idempotencyKey = `webhook:stripe:${event.id}`;
// SETNX: set the key only if it does not exist (atomic)
// Returns 1 if key was set (first delivery), 0 if already exists (duplicate)
const acquired = await redis.set(idempotencyKey, '1', 'EX', 86400, 'NX'); // 24h TTL
if (!acquired) {
// Duplicate delivery — acknowledge without processing
return res.status(200).json({ received: true, duplicate: true });
}
try {
if (event.type === 'payment_intent.succeeded') {
const pi = event.data.object;
await db.query(
'UPDATE users SET plan = $1, plan_started_at = now() WHERE stripe_customer = $2',
['pro', pi.customer]
);
await sendUpgradeEmail(pi.customer);
}
res.status(200).json({ received: true });
} catch (err) {
// On processing error, delete the idempotency key so the retry can re-process
await redis.del(idempotencyKey);
res.status(500).json({ error: 'Processing failed' });
}
});
SET … NX EX before processing and returning 200 without side effects if the key already exists, deleting the key only on a processing error so retries can succeed. Detection: SkillAudit flags webhook POST handlers that perform database writes or external API calls without a preceding redis.set(eventId, …, 'NX') or equivalent idempotency check.ASYNCRACE3-004 — File write race in parallel scan jobs via shared temp path
MCP skills that run static analysis scans often write intermediate results or extracted source files to a temporary directory before processing. When scan jobs are parallelized — either via Promise.all over multiple repos or via a worker pool — and each job derives its temp directory path from a predictable value (the repo name, the user ID, a job type constant), two concurrent jobs scanning different repos can resolve to the same temp path. When Job B starts writing to /tmp/scan-output.json while Job A is still reading from it, Job B truncates the file or overwrites partial data, causing Job A's parser to read malformed JSON and either crash or silently produce incorrect audit results. The fix is a per-job UUID temp directory created at job start and atomically renamed to its final destination on completion, so no two jobs ever share a path.
// VULNERABLE — ASYNCRACE3-004
// scan-runner.js — shared temp path derived from non-unique value
import { writeFileSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
async function runScan(repoUrl, jobType) {
// DANGEROUS: temp path is predictable — same jobType → same path for all jobs
const tempOutput = join(tmpdir(), `skillaudit-${jobType}-output.json`);
const result = await analyzeRepo(repoUrl);
// Job A writes its results here...
writeFileSync(tempOutput, JSON.stringify(result));
// ...while Job B (same jobType, different repo) overwrites tempOutput mid-write
const output = JSON.parse(readFileSync(tempOutput, 'utf8'));
return output; // may contain Job B's data, partial data, or malformed JSON
}
// Concurrent call: Promise.all([runScan(urlA, 'security'), runScan(urlB, 'security')])
// Both write to /tmp/skillaudit-security-output.json → race condition
// FIXED — ASYNCRACE3-004: UUID temp directory + atomic rename on completion
import { mkdtempSync, writeFileSync, renameSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { randomUUID } from 'crypto';
async function runScan(repoUrl, jobType) {
// Per-job UUID temp directory — guaranteed unique even under full concurrency
const jobId = randomUUID();
const jobDir = mkdtempSync(join(tmpdir(), `skillaudit-${jobId}-`));
try {
const outputPath = join(jobDir, 'output.json');
const result = await analyzeRepo(repoUrl, jobDir); // pass jobDir for scratch space
// Write to temp location first
writeFileSync(outputPath, JSON.stringify(result));
// Atomic rename to final destination (same filesystem — rename is atomic on POSIX)
const finalPath = join('/srv/factory/agents/agent-14/data/scans', `${jobId}.json`);
renameSync(outputPath, finalPath);
return { jobId, path: finalPath };
} finally {
// Clean up the entire job directory on success or failure
rmSync(jobDir, { recursive: true, force: true });
}
}
// Now: Promise.all([runScan(urlA, 'security'), runScan(urlB, 'security')])
// Each job gets /tmp/skillaudit--xxxxx/ and /tmp/skillaudit--xxxxx/
// No shared paths — no race possible
rename() to the final destination on completion so no two jobs ever share a file path. Detection: SkillAudit flags writeFileSync or createWriteStream calls to paths built without a UUID or process-unique token when the calling function is used inside a Promise.all or worker pool.Detection summary
| ID | Severity | Pattern | Fix |
|---|---|---|---|
| ASYNCRACE3-001 | HIGH | SELECT quota + conditional UPDATE in two steps — concurrent reads both pass the limit | Atomic UPDATE … WHERE used < limit RETURNING or Redis Lua decrement |
| ASYNCRACE3-002 | HIGH | Read-modify-write aggregate without row lock — concurrent writes corrupt aggregate | SELECT … FOR UPDATE in transaction, or single-statement arithmetic UPDATE |
| ASYNCRACE3-003 | HIGH | Webhook handler without idempotency key — duplicate deliveries double-process | Redis SET eventId 1 NX EX 86400 before processing; return 200 on duplicate |
| ASYNCRACE3-004 | MEDIUM | Shared predictable temp path in parallel jobs — concurrent write overwrites partial output | Per-job UUID mkdtemp + atomic rename() to final destination |
Related patterns: SA-SKL-MEMCACHE3 covers Redis INCR counter race (MEMCACHE3-003) — the atomic Lua fix is the same technique as ASYNCRACE3-001's Redis variant. SA-SKL-TIMEOUT covers unbounded concurrency that creates the event-loop conditions where ASYNCRACE3-004 file races occur. SA-SKL-RATELIMIT3 covers Redis rate limiter TTL race — closely related to ASYNCRACE3-001's quota bypass pattern.