4 Hours

11. Advanced ACID: Transactions & Locking

Concurrency

Handling High-Stakes Traffic

In a high-traffic app, two users might try to buy the last seat on a flight at the exact same millisecond. To solve this, you must master Transactions and Explicit Locking. This is the difference between a working app and a financial disaster.

Transaction Isolation Levels

Postgres follows the SQL standard for isolation, allowing you to choose how private your transaction should be from others.

  • Read Committed (Default): You only see data that was committed before your query started. Most common for standard web apps.
  • Repeatable Read: Ensures that if you read the same row twice, the data won't change even if another user commits an update.
  • Serializable: The highest level. The database acts as if transactions ran one-by-one. Guaranteed to prevent all anomalies, but comes with a performance cost.

Explicit Row Locking: FOR UPDATE

Sometimes MVCC isn't enough. If you are calculating a bank balance, you need to claim a row so no one else can touch it until you are done.

SQL
-- Claiming the row for our transaction
BEGIN;
SELECT balance FROM accounts 
WHERE id = 42 
FOR UPDATE; -- This locks the row for everyone else!

UPDATE accounts SET balance = balance - 100 WHERE id = 42;
COMMIT;

The Deadlock Trap

Deadlocks happen when Transaction A waits for B, and B waits for A. Postgres detects this automatically and kills one of the transactions to save the server. Senior engineers prevent deadlocks by always locking tables in the same order throughout the codebase.

Knowledge Check

Ready to test your understanding of 11. Advanced ACID: Transactions & Locking?

Back