Class 54 of 58 • Enterprise Database Architecture

SQL Concurrency & Locking: Shared vs Exclusive Locks, Row Contention & Deadlocks

In high-traffic production environments—such as banking platforms, airline reservation systems, and flash-sale e-commerce websites—thousands of user sessions execute transactions against the same database tables at the exact same fraction of a second. Without rigorous concurrency controls, concurrent writes inevitably cause race conditions, lost updates, and financial corruption (e.g., two users purchasing the exact same remaining plane seat). To guarantee serializability and maintain ACID integrity, database engines implement sophisticated Locking Mechanisms and Concurrency Control Protocols.

Database Concurrency Locking Modes and Circular Deadlock Cycle Diagram

Figure 8.5: Lock compatibility matrix and the classic circular Wait-For graph resulting in an automatic engine deadlock resolution.


1. Lock Modes & The Compatibility Matrix

At the heart of the Two-Phase Locking (2PL) protocol are two fundamental lock modes:

• Shared Lock (S-Lock / Read Lock): Acquired automatically during read operations or explicitly via SELECT ... FOR SHARE. Multiple transactions can hold S-locks on the same row concurrently, permitting parallel reads.

• Exclusive Lock (X-Lock / Write Lock): Acquired automatically by UPDATE, DELETE, and INSERT statements, or explicitly via SELECT ... FOR UPDATE. Only one transaction can hold an X-lock on a row at any time. All other incoming lock requests are queued and blocked.

Existing Lock on Row Incoming Shared Request (S) Incoming Exclusive Request (X) Concurrency Impact
No Existing Lock ✓ GRANTED ✓ GRANTED Immediate execution
Shared Lock (S) Held ✓ GRANTED (Shared) ✗ BLOCKED (Waits) Readers never block readers; writers must wait
Exclusive Lock (X) Held ✗ BLOCKED (Waits) ✗ BLOCKED (Waits) Writer blocks all other incoming readers and writers

2. Explicit Locking: SELECT ... FOR UPDATE in Practice

Consider an e-commerce inventory checkout system. If you read the inventory with a standard SELECT, another session might deplete the stock before your UPDATE executes. To guarantee that no other session can modify or purchase the inventory while you calculate order totals, acquire an exclusive lock using SELECT ... FOR UPDATE:

-- ===================================================================
-- Safe Inventory Deduction Pattern (Pessimistic Locking)
-- ===================================================================
START TRANSACTION;

-- 1. Read inventory and acquire an Exclusive (X) lock on Product #405
SELECT stock_quantity 
FROM inventory 
WHERE product_id = 405 
FOR UPDATE;

-- Any other concurrent transaction attempting to read Product #405 
-- with FOR UPDATE or modify it will be BLOCKED here until this transaction commits!

-- 2. Verify sufficient stock in application code (e.g. stock >= requested_quantity)
-- Then execute deduction
UPDATE inventory 
SET stock_quantity = stock_quantity - 1 
WHERE product_id = 405;

-- 3. Record order item
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (9902, 405, 1, 149.99);

-- 4. COMMIT releases the Exclusive lock on Product #405
COMMIT;

3. The Deadlock Anatomy: How Circular Dependencies Occur

A Deadlock occurs when two concurrent transactions mutually block each other in a closed dependency cycle:

-- SESSION 1 (Transfer from Account A to Account B)
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1; -- Holds Lock on Row 1

-- SESSION 2 (Simultaneous Transfer from Account B to Account A)
START TRANSACTION;
UPDATE accounts SET balance = balance - 50 WHERE account_id = 2;  -- Holds Lock on Row 2

-- SESSION 1 now attempts to credit Account B:
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2; -- BLOCKED by Session 2!

-- SESSION 2 now attempts to credit Account A:
UPDATE accounts SET balance = balance + 50 WHERE account_id = 1;  -- BLOCKED by Session 1!

Deadlock Engine Intervention (Automatic Victim Rollback)

Neither Session 1 nor Session 2 can ever proceed. Modern RDBMS engines (InnoDB, PostgreSQL, SQL Server) run background Wait-For Graph cycle detection threads every few milliseconds. Upon detecting the loop, the engine picks the transaction that has generated the least undo log history (the cheapest to roll back), aborts it, and returns:

ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction

4. Senior Developer Strategies to Prevent Deadlocks in Production

• 1. Enforce Consistent Global Access Ordering: Ensure all application endpoints update tables and records in identical alphabetical or ascending Primary Key order. If both Session 1 and Session 2 update account_id = 1 before account_id = 2, a circular deadlock is mathematically impossible!

• 2. Keep Transactions Small & Fast: Never perform external network calls, file downloads, email dispatches, or heavy password hashing while holding open database transaction locks.

• 3. Use Lock Wait Timeouts: Configure innodb_lock_wait_timeout = 5 (seconds) so that if a lock cannot be acquired swiftly, the application fails gracefully rather than blocking the connection pool.

• 4. Implement Idempotent Application Retries: Always wrap transactional code in retry handlers configured with exponential backoff and jitter to catch and re-execute aborted deadlock victims automatically.


Hands-on Student Practice Session (Lab Challenge)

Concurrency & Race Condition Lab

Scenario: You are testing concurrent seat bookings for a concert hall with two interactive database terminal sessions.

Task 1: Open two terminal windows. In Terminal 1, begin a transaction and run SELECT * FROM seats WHERE seat_number = 'A1' FOR UPDATE;

Task 2: In Terminal 2, attempt to execute an UPDATE seats SET status = 'BOOKED' WHERE seat_number = 'A1';. Observe Terminal 2 enter a blocked waiting state.

Task 3: In Terminal 1, execute COMMIT;. Observe Terminal 2 immediately unblock and succeed, proving lock release serialization.


Frequently Asked Questions (FAQ)

A Database Lock is a synchronization mechanism used by the database engine to serialize concurrent access to shared data resources. Locks prevent race conditions, lost updates, dirty reads, and data corruption when multiple concurrent transactions attempt to read or modify the exact same records simultaneously.

A Shared Lock (`S`), also called a Read Lock, allows multiple concurrent transactions to read the same data simultaneously. An Exclusive Lock (`X`), also called a Write Lock, is acquired during INSERT, UPDATE, or DELETE operations; it prevents any other transaction from acquiring either an (S) or an (X) lock until the locking transaction issues COMMIT or ROLLBACK.

A Deadlock occurs when two or more transactions form a circular dependency: Transaction 1 holds a lock on Resource A and waits for Resource B, while Transaction 2 holds a lock on Resource B and waits for Resource A. The database engine's Deadlock Detector periodically traces the session Wait-For Graph, detects the closed loop, and terminates one transaction (the 'victim') with a rollback error.

`SELECT ... FOR UPDATE` acquires an Exclusive (X) lock on the selected rows immediately during a read operation. It prevents other concurrent transactions from modifying or locking those specific rows until your current transaction finishes, making it the industry standard for safe inventory checks and bank balance transfers.

Next Step in Your SQL Database Learning Path:

Proceed to the next class in sequence to build production mastery of relational database architecture.

Continue to Class 55: Full-Text Search → Previous: ← JSON Functions in SQL | Full Syllabus


Related SQL Masterclass Lessons & Recommended Next Topics

ACID & Transaction Isolation →

Understanding Read Committed, Repeatable Read, and Serializable.

Row Locking in UPDATE →

Exclusive (X) lock acquisition and row contention during writes.

Index-Driven Locking →

Why missing indexes cause InnoDB to lock the entire table.

Database Security Architecture →

Managing concurrent user session limits and connection pools.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!