Race conditions

suggest change

A race condition occurs when the outcome of a program depends on the uncontrollable timing, ordering, or interleaving of concurrent execution units (multiple HTTP requests, background workers, or threads). In PHP, race conditions commonly manifest as Check-Then-Act (Time-of-Check to Time-of-Use, or TOCTOU) defects in database updates, file operations, inventory management, and multi-threaded extensions.


1. The Check-Then-Act Flaw

The most frequent source of race conditions in web applications is inspecting a condition and performing an action in separate, non-atomic steps:

<?php
// DANGEROUS: Classic Check-Then-Act race condition

function withdrawMoney(PDO $pdo, int $userId, float $amount): bool
{
    // Step 1: Check balance
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = :id");
    $stmt->execute(['id' => $userId]);
    $balance = (float) $stmt->fetchColumn();

    if ($balance >= $amount) {
        // Step 2: Time gap! Another concurrent request can read the same balance here.
        // Step 3: Act
        $update = $pdo->prepare("UPDATE users SET balance = balance - :amount WHERE id = :id");
        return $update->execute(['amount' => $amount, 'id' => $userId]);
    }

    return false;
}

If an account has $100 and the user issues two simultaneous withdrawal requests of $100:

  1. Request 1 checks balance: finds $100 ≥ $100 (Passes check).
  2. Request 2 checks balance before Request 1 finishes updating: also finds $100 ≥ $100 (Passes check).
  3. Both requests deduct $100, leaving the account at -$100 (double spending).

2. Preventing Database Race Conditions

Strategy A: Single Atomic SQL Update (Preferred)

Whenever possible, fold the check and the mutation into a single atomic SQL statement executed by the database engine:

<?php

function withdrawMoneyAtomic(PDO $pdo, int $userId, float $amount): bool
{
    // The database ensures atomicity and row locking internally
    $stmt = $pdo->prepare("
        UPDATE users 
        SET balance = balance - :amount 
        WHERE id = :id AND balance >= :amount
    ");
    $stmt->execute(['amount' => $amount, 'id' => $userId]);

    // rowCount() returns 1 if deduction succeeded, 0 if balance was insufficient
    return $stmt->rowCount() === 1;
}

Because relational databases handle single-row updates atomically, concurrent requests cannot interleave during evaluation.

Strategy B: Pessimistic Locking (FOR UPDATE)

When business logic requires multi-step calculations across several tables before writing:

<?php

$pdo->beginTransaction();

try {
    // FOR UPDATE locks the selected row until commit or rollback
    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = :id FOR UPDATE");
    $stmt->execute(['id' => $userId]);
    $balance = (float) $stmt->fetchColumn();

    if ($balance < $amount) {
        $pdo->rollBack();
        return false;
    }

    // Execute complex calculations, logging, ledger updates...
    $update = $pdo->prepare("UPDATE users SET balance = balance - :amount WHERE id = :id");
    $update->execute(['amount' => $amount, 'id' => $userId]);

    $pdo->commit();
    return true;
} catch (Throwable $e) {
    $pdo->rollBack();
    throw $e;
}

3. File System Race Conditions (TOCTOU)

Checking if a file exists before creating or writing to it is vulnerable to filesystem race conditions:

// VULNERABLE: A concurrent process can create $file between check and write
if (!file_exists($filePath)) {
    file_put_contents($filePath, $initialData);
}

The Atomic Solution: Exclusive Creation Flag ('x')

Use the 'x' or 'x+' mode in fopen(), which maps to the operating system's O_CREAT | O_EXCL flags. This guarantees that file creation and opening succeed atomically only if the file does not already exist:

<?php

$filePath = '/tmp/exclusive_job.pid';

// Atomically create file; returns false if file already exists
$handle = @fopen($filePath, 'x');

if ($handle === false) {
    die("File already exists; another process claimed this task.\n");
}

try {
    fwrite($handle, (string) getmypid());
    // Execute critical job...
} finally {
    fclose($handle);
    unlink($filePath);
}

4. Multi-Threading Race Conditions (parallel)

In multi-threaded PHP environments (using the parallel extension), race conditions arise when multiple worker threads read and write shared variables without synchronization:

<?php

use parallel\Runtime;
use parallel\Sync;

// Buggy: Unsynchronized counter in threads
// Two threads incrementing 1,000 times will result in less than 2,000 increments

// Safe: Synchronized state with parallel\Sync
$syncCounter = new Sync(0);

$runtimes = [new Runtime(), new Runtime()];
$futures = [];

for ($i = 0; $i < 2; $i++) {
    $futures[] = $runtimes[$i]->run(function(Sync $sync) {
        for ($j = 0; $j < 1000; $j++) {
            // Invoking the Sync object runs the closure while holding its mutex
            $sync(function() use ($sync) {
                $sync->set($sync->get() + 1);
            });
        }
    }, [$syncCounter]);
}

foreach ($futures as $f) {
    $f->value();
}

echo "Final count: " . $syncCounter->get() . "\n"; // Guaranteed 2000

5. Coupon and Voucher Redemption Races

A common e-commerce attack is the coupon race condition: submitting 10 simultaneous HTTP requests with the same single-use discount coupon code. If the application checks used == false across all requests before marking it used = true, the discount applies multiple times.

Prevention with Unique Database Constraints

Add a database unique constraint on (coupon_id, user_id) or enforce atomic updates:

ALTER TABLE coupon_redemptions ADD CONSTRAINT unique_user_coupon UNIQUE (coupon_id, user_id);

If multiple concurrent requests attempt to insert the same combination, the database immediately rejects duplicates with a unique key violation.


Summary of Prevention Rules

  1. Avoid Check-Then-Act: Never separate authorization/validation checks from the mutating query.
  2. Rely on Atomic Database Operations: Use atomic SQL arithmetic (balance = balance - X WHERE balance >= X).
  3. Use Explicit Locks When Necessary: Use SELECT ... FOR UPDATE in transactions, advisory locks (flock), or Redis locks.
  4. Leverage Database Constraints: Enforce uniqueness at the database schema level rather than checking in application code.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents