Intermediate LevelWeb Security & Cyber Defense
How do Time-of-Check to Time-of-Use (TOCTOU) Race Conditions cause double-spending in financial APIs?
❓ Interview Prompt: Explain TOCTOU Race Conditions, concurrent API requests, double-spending vulnerabilities, atomic database transactions, and SELECT FOR UPDATE.
Time-of-Check to Time-of-Use (TOCTOU) race conditions occur when an application checks a condition (user balance $\ge \$100$) and performs an action (deduct $\text{balance}$) in non-atomic steps:
Double-Spend Exploit:
An attacker fires 10 concurrent requests simultaneously ('Promise.all([transfer(), transfer(), ...])').
•
All 10 requests pass the balance check BEFORE any single request completes the deduction!
•
Fix: Use atomic database transactions with 'SELECT ... FOR UPDATE' row locking or atomic update operations ('UPDATE account SET balance = balance - 100 WHERE balance >= 100').
Code Implementation Example
typescript
import { db } from './db';
export async function executeAtomicTransfer(userId: string, amount: number) {
return await db.$transaction(async (tx) => {
// ✅ Atomic UPDATE with balance condition prevents double-spending race conditions!
const result = await tx.$executeRaw'
UPDATE accounts
SET balance = balance - ${amount}
WHERE user_id = ${userId} AND balance >= ${amount}
';
if (result === 0) throw new Error('Insufficient funds or concurrent update conflict');
});
}💡Executing atomic SQL balance deduction to prevent double-spending race conditions.
🎯 Interview Key Takeaway
Use atomic database transactions with row locking or conditional UPDATE queries to prevent TOCTOU double-spending race conditions.
#TOCTOU#Race Conditions#Double-Spend#Intermediate
Back to all Web Security & Cyber Defense Questions→