Don’t Let Race Conditions Wreck Your Database: When to Use SELECT ... FOR UPDATE
When I first started building backend systems, my approach to updating a user's balance or product inventory was straightforward: SELECT the current value, do the math in code, and UPDATE the row.
It works great—right up until more than one person uses your app at the same time.
The moment thousands of concurrent requests hit your server (think flash sales, ticket drops, or payment processing), a silent bug wakes up: the Race Condition. Here is how one of the most reliable tools in MySQL and PostgreSQL—SELECT ... FOR UPDATE—stops it dead in its tracks, and the traps you need to avoid when using it.
1. The "Free Money" Bug
Imagine you’re building a checkout flow. The naive implementation looks like this:
-
Check the user's balance:
SELECT balance FROM users WHERE id = 1;(Returns $100). -
Verify in code that they have enough to buy an $80 item.
-
Deduct the amount:
UPDATE users SET balance = balance - 80 WHERE id = 1;
Now, what happens if the user double-clicks "Pay" (or sends two parallel requests) at the exact same millisecond?
Both requests read $100 before either has written anything back. Both pass the validation check. Both execute the UPDATE. Suddenly, the user just spent $160 out of a $100 wallet. The business loses money, and the backend team gets paged first.
2. What SELECT ... FOR UPDATE Actually Does
Appending FOR UPDATE to a SELECT statement sends a clear message to the database:
"I am about to modify this row. Lock it down. If anyone else tries to update it or lock it for reading, make them wait in line until I’m done."
Under the hood, the database acquires an Exclusive Lock (row-level lock) on the selected rows. While your transaction holds that lock, other transactions attempting to SELECT ... FOR UPDATE or UPDATE the same row will block until you either COMMIT or ROLLBACK.
3. Implementing It in Go
In Go, SELECT ... FOR UPDATE must run inside a database transaction (db.BeginTx). The lock is only released when the transaction ends. Always defer tx.Rollback() immediately after starting the transaction so you never leak a lock if an error or panic occurs.
Go
func DeductBalance(ctx context.Context, db *sql.DB, userID int64, amount int64) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
// Safe to call even after Commit(); it becomes a no-op if already committed
defer tx.Rollback()
var balance int64
// 1. Lock the row for this user
err = tx.QueryRowContext(ctx,
"SELECT balance FROM users WHERE id = $1 FOR UPDATE",
userID,
).Scan(&balance)
if err != nil {
return err
}
// 2. Check business logic safely while holding the lock
if balance < amount {
return errors.New("insufficient balance")
}
// 3. Perform the update
_, err = tx.ExecContext(ctx,
"UPDATE users SET balance = balance - $1 WHERE id = $2",
amount, userID,
)
if err != nil {
return err
}
// 4. Commit and release the lock
return tx.Commit()
}
4. Three Pitfalls That Will Wreck Production
SELECT ... FOR UPDATE is powerful, but misusing it can take down your database faster than the race condition itself. Watch out for these three traps:
-
Deadlocks: Suppose Transaction A locks Row 1 and waits for Row 2, while Transaction B locks Row 2 and waits for Row 1. Both stall until the database kills one of them. The fix: Always acquire locks in a consistent, deterministic order (for example, always sort
user_ids ascending before locking multiple rows in a transfer). -
Long-Running Transactions: Because other requests have to wait in line, holding a lock for too long creates a traffic jam that exhausts your database connection pool. The fix: Keep transactions as short as humanly possible. Never make third-party HTTP/API calls, send emails, or run heavy computations inside a locked transaction.
-
Missing Indexes (The Table-Lock Nightmare): In MySQL (InnoDB), row-level locks are actually placed on index records. If your
WHEREclause doesn't use an index, the database has to scan—and lock—every single row in the table. Always verify your query plan withEXPLAINto make sure you’re hitting an index.
5. Wrapping Up
SELECT ... FOR UPDATE is the classic form of Pessimistic Locking—you assume a conflict will happen, so you lock the data upfront to be safe. It’s the gold standard for high-contention operations like payments, seat reservations, and flash-sale inventory.
If your system has low contention and you want to avoid the overhead of blocking queries, look into Optimistic Locking (using a version column in your UPDATE ... WHERE id = ? AND version = ? clause) for better throughput.
Have you ever been burned by a race condition in production? Drop your war stories and how you fixed them in the comments!
All rights reserved