Cybersecurity Glossary

What is a Race Condition?

A race condition occurs when two or more operations access shared state at almost the same time and the application assumes an order that is not guaranteed. The code may look correct in a single request, yet fail under parallel execution. Security-relevant examples include redeeming one voucher twice, exceeding a transfer limit or changing a file between a check and its use.

The familiar check-then-act pattern is especially risky: the application verifies a condition and performs the action later, leaving a small window in which another request can change that condition.

How are race conditions prevented?

  • - Make critical operations atomic and enforce invariants in the database where possible.
  • - Use transactions, appropriate locking or compare-and-swap mechanisms.
  • - Design state-changing APIs to be idempotent and use unique operation identifiers.
  • - Test important business workflows with synchronized parallel requests.

Code example: redeem a voucher atomically

Vulnerable check-then-act pattern:

$voucher = Voucher::findOrFail($id);
if (!$voucher->redeemed) {
    creditAccount($user, $voucher->amount);
    $voucher->update(['redeemed' => true]);
}

Atomic with transaction and lock:

DB::transaction(function () use ($id, $user) {
    $voucher = Voucher::query()
        ->lockForUpdate()
        ->findOrFail($id);

    abort_if($voucher->redeemed, 409);
    creditAccount($user, $voucher->amount);
    $voucher->update(['redeemed' => true]);
});

The lock, credit and state change must share the same database transaction. Unique constraints and idempotency keys provide additional and often stronger invariants.

Why are these flaws difficult to find?

They may only appear in a narrow timing window and disappear during debugging. Reliable testing coordinates requests precisely and verifies the final state, not only individual HTTP responses.

Penetration Tests

Uncover Security Vulnerabilities

Professional penetration testing for your business

Web Apps
Networks
Mobile Apps
10% New Customer Discount
Plan Now

Thank you for your feedback! We will review it and optimize this content.

Do you have feedback on Race Condition? Tell us!