๐ 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?
- โ Prevent data corruption from simultaneous writes
- โ Ensure ACID (Atomicity, Consistency, Isolation, Durability)
- โ Allow safe concurrent access
- โ Enable isolation levels (READ COMMITTED, SERIALIZABLE, etc.)
๐ง Core Lock Types
๐ Shared Lock (S Lock)
- Acquired when reading data
- Allows other shared locks (multiple readers)
- Blocks exclusive locks
// SQL Server
SELECT * FROM orders WITH (HOLDLOCK);
โ
Good for consistency
โ ๏ธ Blocks writers
๐ Exclusive Lock (X Lock)
- Acquired when writing data (INSERT, UPDATE, DELETE)
- Blocks all other locks, including shared
- Only one exclusive lock allowed on a resource
// 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)
- Used before acquiring exclusive locks to prevent deadlocks
- Only one update lock is allowed until it's escalated to exclusive
- Common in SQL Server
-- SQL Server hint:
SELECT * FROM accounts WITH (UPDLOCK);
โ
Prevents deadlocks in read-then-write patterns
โ ๏ธ Confusing to debug
๐งฑ Schema Locks
- Lock metadata structures like tables, indexes, constraints
- Acquired during
ALTER TABLE
,CREATE
, orDROP
- Prevents reads/writes while schema changes
โ
Maintains metadata consistency
โ ๏ธ Can block regular queries if schema change is long
๐ฆ Bulk Update Lock (BU Lock)
- Used for bulk insert/update operations
- Allows high throughput by restricting concurrency
- Mostly seen in SQL Server and during
BULK INSERT
โ
Fast bulk operations
โ ๏ธ Prevents other access
๐ Granularity Levels
1. Row-level Lock
- Locks a single row
- Supported by InnoDB, PostgreSQL, SQL Server
โ
High concurrency
โ ๏ธ Overhead managing many locks
2. Page-level Lock
- Locks a data page (typically 8KB)
- Used in some SQL Server/older engines
โ
Balance between row/table
โ ๏ธ Can cause contention if multiple rows per page accessed
3. Table-level Lock
- Locks entire table
- Used by MyISAM and optionally by InnoDB or during DDL
// MySQL
LOCK TABLES orders WRITE;
โ
Simple to manage
โ ๏ธ Low concurrency
๐ Other Locks and Concepts
๐ Intention Locks
- Metadata locks that signal intent to acquire a row/table lock
- Help coordinate between lock levels
- Common in InnoDB
Lock | Meaning |
---|---|
IS | Intention to acquire shared lock at lower level |
IX | Intention to acquire exclusive lock at lower level |
๐ Key Range Locks
- Lock a range of keys to prevent phantom reads
- Used in SERIALIZABLE isolation (e.g.
SELECT โฆ FOR UPDATE
with range)
โ
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:
- Too many row locks
- Resource pressure
- Lock threshold exceeded
โ
Prevents memory exhaustion
โ ๏ธ May cause unexpected contention
๐งฏ Deadlocks and Prevention
Two transactions holding locks on resources the other needs โ deadlock.
Coffman Conditions for Deadlock:
- Mutual exclusion
- Hold and wait
- No preemption
- Circular wait
๐ ๏ธ Strategies:
- Set lock timeout
- Retry with backoff
- Always acquire locks in same order
- Use optimistic locking where applicable
๐งช Monitoring Locks
- PostgreSQL:
pg_locks
- MySQL:
INFORMATION_SCHEMA.INNODB_LOCKS
- SQL Server:
sys.dm_tran_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
- PostgreSQL Concurrency Control
- SQL Server Locking Overview
- MySQL InnoDB Locking
- High Performance MySQL (O'Reilly)
<< back to Guides