QA
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→

More Web Security & Cyber Defense Interview Questions

Beginner LevelSecurity & Web Security

Explain OWASP Top 10 vulnerabilities (XSS, CSRF, SQL Injection) and their defenses.

Beginner LevelSecurity & Web Security

What are the 3 types of XSS (Stored, Reflected, DOM-based) and how do they differ?

Beginner LevelSecurity & Web Security

How do Parameterized Queries (Prepared Statements) prevent SQL Injection attacks?