OwlTheEngineer
How It Actually WorksEpisode 57 · Backend

Optimistic vs Pessimistic Locking: How Databases Prevent Lost Updates

Why two users buying the last concert seat at the same millisecond causes a Lost Update, and how SELECT FOR UPDATE vs atomic version checks solve it.

Owl · 3 min read · 0 views
– comments
Ep 57 · Backend
60s VISUAL BREAKDOWN
Episode 57
Watch the fast visual breakdown or discuss on social:

Imagine one VIP concert seat (#A1) is left, and two users (User A and User B) click Buy at the exact same millisecond (12:00:00.001).

Without database-level concurrency control, both backend servers read stock = 1, both pass your application’s if (stock > 0) check, both charge Stripe, and both execute UPDATE seats SET stock = 0. You just sold the exact same seat twice—a classic Lost Update race condition.

To prevent lost updates in production, backend engineers rely on two fundamental strategies: Pessimistic Locking and Optimistic Locking.


1. Pessimistic Locking (SELECT ... FOR UPDATE)

Pessimistic Locking assumes collisions will happen, so it locks the row before reading or modifying it.

BEGIN;

-- Step 1: Acquire an exclusive row-level lock immediately on read
SELECT stock FROM seats
WHERE id = 'A1'
FOR UPDATE;

-- Step 2: Safely deduct inventory inside the lock
UPDATE seats SET stock = 0
WHERE id = 'A1';

COMMIT; -- Releases the row lock

Ordered Workflow (SELECT ... FOR UPDATE)

  1. Step ① — Lock on Read: User A runs SELECT ... FOR UPDATE. PostgreSQL immediately places an exclusive lock on Row #A1.
  2. Step ② — Queue Concurrent Callers: User B arrives 2ms later and runs SELECT ... FOR UPDATE. PostgreSQL blocks User B in a lock wait queue until User A’s transaction finishes.
  3. Step ③ — Update & Commit: User A updates stock = 0 and commits.
  4. Step ④ — Unlock & Advance Queue: The lock releases; User B wakes up, reads the newly committed stock = 0, and exits cleanly with “Sold Out”.

Production Trap: Never call slow external APIs (like Stripe or SendGrid) inside a SELECT ... FOR UPDATE transaction. Holding row locks during an 800ms HTTP call starves your database connection pool and risks deadlocks.


2. Optimistic Locking (WHERE version = 1)

Optimistic Locking assumes collisions are rare. Instead of blocking readers in a queue, every row stores an integer version column (or timestamp) that is verified atomically at write time.

-- Step 1: Both users read without any locks
SELECT stock, version FROM seats WHERE id = 'A1';
-- Returns: stock = 1, version = 1

-- Step 2: Atomic compare-and-swap on write
UPDATE seats
SET stock = 0, version = version + 1
WHERE id = 'A1' AND version = 1;

Ordered Workflow (WHERE version = 1)

  1. Step ① — Parallel Read (Zero Locks): Both User A and User B read stock = 1, version = 1 with zero lock wait.
  2. Step ② — First Writer Bumps Version: User A executes UPDATE ... WHERE id = 'A1' AND version = 1. Since version is still 1, PostgreSQL updates 1 row and increments version to 2.
  3. Step ③ — Stale Writer Rejected: User B executes the exact same UPDATE ... WHERE id = 'A1' AND version = 1. Because version is now 2, the WHERE clause matches nothing and returns 0 rows updated.
  4. Step ④ — Instant Conflict Detection: Your application sees updatedRows === 0 and immediately returns 409 Conflict (or retries with fresh data)—zero double-booking and zero lock queues.

Production Trap: Avoid Optimistic Locking on ultra-high-contention flash sales. If 10,000 users read version = 1 simultaneously, 9,999 fail with 0 rows updated and trigger a thundering-herd retry storm.


3. System Design Cheat Sheet

DimensionPessimistic Locking (FOR UPDATE)Optimistic Locking (version column)
Core MechanismExclusive Row Lock on ReadAtomic Version Check on Write
When It ChecksAt Read Time (Blocks concurrent readers)At Write Time (Zero locks on read)
Contention FitHigh Contention (Many users hit 1 row)Low Contention (Collisions are rare)
Best Use CasesConcert Tickets, Flash Sales, LedgersShared Docs, Profile Edits, B2B Settings
Failure ModeConnection Pool Exhaustion & DeadlocksRetry Storms under heavy contention
SYSTEM DESIGN CHECK

Test Your Understanding

Quick architectural scenario challenge based on this breakdown.

SCENARIO

A 3rd-party payment gateway starts timing out with 504 errors during peak traffic.

Q1.How should a downstream dependency failure be handled to protect upstream service availability?

Comments –