SQL & Relational Databases (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
Concurrency Control: Optimistic vs Pessimistic Locking.
senior Levelsql-databasesAdvanced Internals
In Simple Words:
- Pessimistic Locking (
SELECT ... FOR UPDATE): Acquires an exclusive row lock immediately, blocking other transactions until commit. Best for high-contention, low-latency financial balances where conflicts are frequent. - Optimistic Locking: No locks acquired during reading. The row has a
versionorupdated_atcolumn. When updating:UPDATE accounts SET balance = balance - 100, version = version + 1 WHERE id = 1 AND version = 5;Ifaffected_rows == 0, a concurrent update occurred, and the application retries. Best for low-contention web applications.