Lock contention

On this page 8

Lock contention is the condition in which concurrent transactions repeatedly request locks that other transactions already hold, so they must wait instead of doing useful work. In database performance, it is one of the most common reasons why a system with idle CPUs and fast disks still delivers low throughput and unpredictable latency.

Every relational engine uses locks or comparable mechanisms to protect isolation and consistency in databases. Contention is not a defect in itself; it becomes a problem when the time spent waiting grows faster than the workload, which is a typical symptom of hot rows, long transactions or poorly chosen isolation levels.

How lock contention arises in a database engine

Lock contention arises when two or more sessions need incompatible locks on the same resource at the same time. The lock manager grants the first request and places the others in a wait queue, where they remain until the holder commits, rolls back or releases the lock early.

Compatibility is defined by a lock mode matrix. Shared locks for reading can coexist, while an exclusive lock for writing conflicts with almost every other mode. Engines also use intention locks on tables and pages so that a request for a coarse lock can detect finer locks below it without scanning every row.

The following table summarizes the lock modes that most engines implement and how they interact.

Lock modeTypical purposeCompatible with
Shared (S)Reading a row or page under locking readsShared, intention shared
Exclusive (X)Inserting, updating or deleting dataNo other mode
Update (U)Reading a row that will probably be modifiedShared only
Intention shared (IS)Signaling row-level shared locks below a tableAll modes except exclusive
Intention exclusive (IX)Signaling row-level exclusive locks below a tableIntention modes only
Common lock modes and their compatibility

Engines based on multiversion concurrency control (MVCC), such as PostgreSQL, Oracle Database and InnoDB in MySQL, let plain readers see a consistent snapshot without taking row locks. This removes most reader-writer conflicts, but writer-writer conflicts on the same row still serialize, so MVCC reduces contention without eliminating it.

Granularity, duration and the cost of waiting

The severity of lock contention depends on how much data a lock covers and how long it is held. Fine-grained row locks allow more parallelism but cost more memory and bookkeeping, while coarse table locks are cheap to manage but block unrelated work.

GranularityConcurrencyOverheadTypical trigger
Row or keyHighestHighest memory per lockPoint updates through an index
Page or blockModerateModerateRange scans in some engines
TableLowLowestDDL, bulk loads, lock escalation
Database or schemaVery lowMinimalMaintenance and restore operations
Lock granularity trade-offs

Some engines apply lock escalation, converting thousands of row locks into a single table lock to save memory. Escalation protects the lock manager but can suddenly block every other session touching that table, which makes it a frequent cause of sporadic contention spikes.

Duration matters even more than granularity. Under two-phase locking, write locks are held until the transaction ends, so a transaction that performs an update and then waits for an external API call keeps the row locked for the entire network round trip. Transaction length is the strongest lever that application teams control.

Lock contention is often confused with neighboring phenomena that produce similar symptoms but need different fixes. Distinguishing them early prevents tuning the wrong layer.

PhenomenonWhat happensTypical resolution
Lock contentionSessions wait in a queue for a held lockShorter transactions, better indexing, less hot data
DeadlockTwo sessions wait for each other in a cycleEngine kills a victim; fix lock ordering
Latch contentionThreads compete for internal memory structuresEngine configuration, partitioning hot pages
Blocking chainOne long holder blocks a cascade of waitersFind and end or shorten the head blocker
Connection saturationRequests wait for a free connectionConnection pooling and pool sizing
How lock contention differs from similar issues

A deadlock is a special case that the engine resolves automatically by aborting one participant, whereas ordinary contention simply makes everyone slower. Latches are short-lived internal locks on buffer pool pages and other memory structures; contention on them looks similar in monitoring but responds to engine-level changes, not to SQL rewrites.

Detecting and measuring contention

Lock contention is detected by measuring lock wait time relative to total query time. A query that runs in 5 ms when executed alone but takes 800 ms under load, with most of that time recorded as lock waits, is a clear contention case rather than a slow execution plan.

  • PostgreSQL exposes waiting sessions in pg_stat_activity and lock details in pg_locks; the log_lock_waits setting records waits longer than deadlock_timeout.
  • MySQL with InnoDB reports current waits in performance_schema.data_lock_waits and summarizes row lock time in SHOW ENGINE INNODB STATUS.
  • SQL Server shows blocking through sys.dm_tran_locks and wait statistics such as LCK_M_X in sys.dm_os_wait_stats.
  • The slow query log captures statements whose duration is dominated by waiting, which helps link contention to specific code paths.

Useful indicators include the ratio of lock wait time to execution time, the length of blocking chains, the identity of the head blocker, and whether waits concentrate on a few rows. Contention that rises sharply with concurrency while CPU stays flat is a classic queuing signature.

Reducing lock contention in practice

Reducing lock contention means shrinking the overlap between transactions that need the same data. The most effective measures change the workload pattern rather than the server configuration.

PatternRoot causeRecommended remedy
Hot counter rowEvery request updates one rowSharded counters or batched increments
Long transactionWork or I/O inside an open transactionCommit early; move external calls outside
Missing index on update filterScan locks many rows or gapsAdd an index matching the predicate
Queue table pollingWorkers lock the same next jobSELECT ... FOR UPDATE SKIP LOCKED
Large batch updateMillions of locks and escalationProcess in small chunks with commits
Contention patterns and remedies

Further options include choosing a lower isolation level where the business rules allow it, using optimistic concurrency with version columns, setting lock timeouts such as lock_timeout or innodb_lock_wait_timeout so that waits fail fast, and accessing tables in a consistent order to avoid deadlocks. Partitioning can help when contention concentrates on a narrow key range, such as the last page of an ever-increasing primary key.

Common mistakes when addressing lock contention

Teams frequently treat contention as a hardware problem. Adding CPU or memory rarely helps, because waiting sessions consume almost no resources; they simply sit in a queue.

  • Raising connection limits, which adds more waiters to the same queue and often worsens latency.
  • Using NOLOCK or read-uncommitted hints, which hides reader waits but risks dirty and inconsistent reads.
  • Ignoring idle-in-transaction sessions, which hold locks while doing nothing.
  • Blaming the database for contention created by ORM patterns that open transactions too early.

A plain-language summary

A database lets many people change information at the same time, but two people should never change the same record at the same moment. To prevent that, the database puts a temporary lock on the record while someone works on it.

Lock contention is what happens when many people want the same locked record. They form a line, like customers at a single checkout lane, and everyone waits even though the store has plenty of space. The fix is usually to make each visit to the lane shorter or to open more lanes by spreading the work across different records.

An example from practice

An online ticketing service stored the remaining seat count for each event in a single row. During a popular concert sale, about 2,000 requests per second tried to decrement that one row. Each transaction also called a payment gateway before committing, so locks were held for 300 to 600 ms, and response times climbed above ten seconds while the database server reported only 20 percent CPU usage.

The engineering team moved the payment call outside the transaction, reserved seats with short individual inserts into a reservations table, and recalculated the remaining count asynchronously. Lock wait time fell by more than 95 percent, and the next sale completed with median checkout latency below 200 ms on the same hardware.