Check-Then-Act (TOCTOU)

Time-Of-Check to Time-Of-Use: Why looking before you leap fails in concurrency.

The idea

A classic coding pattern is "Check-Then-Act": If the username is available, create the user. In a single-threaded world, this is perfect. In a concurrent world, between the microsecond you "Check" and the microsecond you "Act", another thread can jump in and invalidate your check. This causes two users to claim the same username!

Step 1: Alice and Bob both click 'Submit' at the exact same time for the username 'coder123'.

How it works (Database Constraints)

You cannot fix TOCTOU in application code without holding a heavy, globally blocking lock. The standard solution is to rely on the Database to enforce the rule atomically at the Time-Of-Use, using Unique Constraints.

# THE BAD WAY (Check-Then-Act TOCTOU Vulnerability)
user = db.query("SELECT id FROM users WHERE username = 'coder123'")
if not user:
    # ⚠ Another thread can insert 'coder123' RIGHT HERE!
    db.execute("INSERT INTO users (username) VALUES ('coder123')")
    
# THE GOOD WAY (Let the Database Enforce it Atomically)
# 1. Create a Unique Index on the database table:
#    CREATE UNIQUE INDEX idx_username ON users(username);

try:
    # We don't check. We just act. The DB will safely reject duplicates.
    db.execute("INSERT INTO users (username) VALUES ('coder123')")
except UniqueConstraintViolation:
    print("Username is taken!")

Cost

Relying on database constraints or `INSERT IGNORE` requires catching exceptions for expected control flow, which feels messy to some developers. However, it is fundamentally O(1) and the only race-condition-free way to handle uniqueness across multiple application servers.

Watch out for