<< back to Guides

๐Ÿ” Deep Dive into Database Locks

Database locking is a concurrency control mechanism that ensures data consistency and integrity when multiple transactions access the same data simultaneously.

Locks prevent conflicts such as dirty reads, lost updates, and uncommitted data access.


๐Ÿ“Œ Why Are Locks Important?


๐Ÿง  Core Lock Types

๐Ÿ”„ Shared Lock (S Lock)

// SQL Server
SELECT * FROM orders WITH (HOLDLOCK);

โœ… Good for consistency
โš ๏ธ Blocks writers


๐Ÿ”’ Exclusive Lock (X Lock)

// MySQL (InnoDB)
START TRANSACTION;
UPDATE products SET price = price * 1.1 WHERE category = 'Electronics';

โœ… Ensures safe writes
โš ๏ธ Can lead to contention


๐Ÿ” Update Lock (U Lock)

-- SQL Server hint:
SELECT * FROM accounts WITH (UPDLOCK);

โœ… Prevents deadlocks in read-then-write patterns
โš ๏ธ Confusing to debug


๐Ÿงฑ Schema Locks

โœ… Maintains metadata consistency
โš ๏ธ Can block regular queries if schema change is long


๐Ÿ“ฆ Bulk Update Lock (BU Lock)

โœ… Fast bulk operations
โš ๏ธ Prevents other access


๐Ÿ” Granularity Levels

1. Row-level Lock

โœ… High concurrency
โš ๏ธ Overhead managing many locks


2. Page-level Lock

โœ… Balance between row/table
โš ๏ธ Can cause contention if multiple rows per page accessed


3. Table-level Lock

// MySQL
LOCK TABLES orders WRITE;

โœ… Simple to manage
โš ๏ธ Low concurrency


๐Ÿ”Ž Other Locks and Concepts

๐Ÿ” Intention Locks

Lock Meaning
IS Intention to acquire shared lock at lower level
IX Intention to acquire exclusive lock at lower level

๐Ÿ”‘ Key Range Locks

โœ… Needed for correct SERIALIZABLE behavior
โš ๏ธ May block inserts even outside exact keys


๐Ÿงช Locking Modes Summary Table

Lock Type Read Allowed Write Allowed Use Case
Shared (S) โœ… โŒ Safe reads
Exclusive (X) โŒ โœ… Safe writes
Update (U) โŒ Later โ†’ โœ… Deadlock prevention
Schema โŒ โŒ DDL operations
Bulk Update (BU) โŒ โœ… Mass ingestion
Row-level โœ… โœ… (isolated) High concurrency systems
Page-level โœ… โœ… Medium granularity
Table-level โŒ โŒ Full-table updates

๐Ÿ” Lock Escalation

Some engines (e.g. SQL Server) escalate from row/page โ†’ table-level locks automatically when:

โœ… Prevents memory exhaustion
โš ๏ธ May cause unexpected contention


๐Ÿงฏ Deadlocks and Prevention

Two transactions holding locks on resources the other needs โ†’ deadlock.

Coffman Conditions for Deadlock:

  1. Mutual exclusion
  2. Hold and wait
  3. No preemption
  4. Circular wait

๐Ÿ› ๏ธ Strategies:


๐Ÿงช Monitoring Locks


โœ… Summary

Category Examples When to Use
Granular Locks Row, Page, Table Based on concurrency/performance
Semantic Locks Shared, Exclusive, Update Based on read/write behavior
Metadata Locks Schema, Intention Structural or hierarchical locking
Optimizations Key Range, Bulk Update Specific high-throughput needs

๐Ÿ“š Further Reading


<< back to Guides