Skip to content

Locks & Concurrency Control ​

"Only an ACCESS EXCLUSIVE lock blocks a SELECT (without FOR UPDATE/SHARE) statement." — PostgreSQL documentation, Explicit Locking, "Table-Level Locks"

Summary: every database lets many transactions run at once, and locks are the main tool it uses to stop them corrupting each other's work. This page covers the lock modes, how waiting works, and how to see and bound it. Focus: PostgreSQL table and row locks, the lock queue, timeouts, SKIP LOCKED, advisory locks and pg_locks; InnoDB record, gap and next-key locks; how SQL Server, Oracle, MongoDB and Redis differ. Learning goal: given a stuck query, you can say which lock it waits for, who holds it, why, and which change (timeout, weaker mode, shorter transaction, redesign) removes the wait.

This page is the complete reference for lock-based concurrency control. It covers why concurrency control exists, locks vs latches, shared/exclusive/intention locks, two-phase locking, lock granularity, all eight PostgreSQL table-level lock modes with the full conflict matrix, the four row-level modes, the lock queue, lock_timeout, statement_timeout, NOWAIT, SKIP LOCKED, advisory locks, every view and function you need to diagnose a wait, the InnoDB lock family (record, gap, next-key, insert intention, AUTO-INC, IS/IX), and what SQL Server, Oracle, SQLite, MongoDB, CockroachDB and Redis do instead. It deliberately leaves three neighbours to their own pages: which anomalies each level allows is in Isolation Levels; how row versions let readers skip locks is in MVCC, VACUUM & Bloat; and cycles of waits are in Deadlocks. Whether to lock first or detect conflicts later is the subject of Optimistic vs Pessimistic Locking.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why locks exist and the trade-offWhy concurrency control exists
2PL, strict 2PL, granularity, intention locks: where the words come fromWhere it comes from
One concept per block with a timeline and a fixThe concept catalogue
The eight PostgreSQL table modes and which statement takes whichPostgreSQL table-level lock modes
FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHAREPostgreSQL row-level locks
Why a whole table freezes behind one ALTER TABLEThe lock queue
Record, gap, next-key, insert intention, AUTO-INCInnoDB locks
SQL Server escalation and hints, Oracle, SQLite, MongoDB, RedisPer-engine behaviour
Knobs, error codes, pg_locks, wait events, SHOW ENGINE INNODB STATUSMechanics
A stuck system, step by stepDiagnosing lock waits
Migrations, job queues, singleton jobs, hot counters in SQL + Go + LaravelSolving the classic problems
Which lock for which situationChoosing
Locks across services, replicas and shardsIn architecture
Reproduce it in two terminalsLab
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The lock families. Each row is unpacked below.

KindIn plain wordsExampleWho waits
Latch (LWLock, spinlock, buffer pin)Microsecond guard on an in-memory structureTwo backends touching the same buffer pageNobody you can see in SQL, except as LWLock/Buffer wait events
Table-level lock"What else may run on this table right now"ALTER TABLE needs ACCESS EXCLUSIVEConflicting statements on the whole table
Row-level lock"Nobody else may change this row"SELECT ... FOR UPDATEWriters and lockers of the same row, never plain readers
Gap / next-key lock (InnoDB)"Nobody may insert into this range"WHERE c1 BETWEEN 10 AND 20 FOR UPDATEInserts into the range
Intention lock (IS/IX)A table-level note "I lock rows in here"Any InnoDB row lockOnly whole-table lock requests
Advisory lockA named mutex the database stores for youpg_try_advisory_lock(42)Other callers of the same key
Metadata lock (MySQL)Guards the table definitionALTER TABLE vs open transactionsDDL, and everything queued behind it

PostgreSQL table modes in one line each (weakest to strongest).

ModeTaken byBlocks
ACCESS SHARESELECTonly ACCESS EXCLUSIVE
ROW SHARESELECT ... FOR UPDATE/SHAREEXCLUSIVE, ACCESS EXCLUSIVE
ROW EXCLUSIVEINSERT, UPDATE, DELETE, MERGESHARE and stronger
SHARE UPDATE EXCLUSIVEVACUUM, ANALYZE, CREATE INDEX CONCURRENTLYitself and stronger
SHARECREATE INDEXall writes
SHARE ROW EXCLUSIVECREATE TRIGGER, some ALTER TABLEwrites and itself
EXCLUSIVEREFRESH MATERIALIZED VIEW CONCURRENTLYeverything except plain reads
ACCESS EXCLUSIVEDROP, TRUNCATE, VACUUM FULL, most ALTER TABLEeverything, including SELECT

The five rules to act on.

SituationDo this
Any DDL on a busy tableSET LOCAL lock_timeout = '2s' and retry with backoff
Workers taking jobs from a tableFOR UPDATE SKIP LOCKED, short claim transaction
"Only one instance may run this"pg_try_advisory_xact_lock(key) (or a session lock on a pinned connection)
A counter everybody incrementsShard it, or append events and aggregate; do not queue on one row
Something is stuckpg_stat_activity + pg_blocking_pids(); on MySQL performance_schema.data_lock_waits

Why concurrency control exists ​

A database runs transactions concurrently because one at a time wastes the machine. Concurrency brings two classic problems: two writers overwrite each other (lost update, dirty write), and a reader sees a half-finished change. Concurrency control is the set of mechanisms that make concurrent execution look safe. There are two broad families. Pessimistic control assumes conflicts will happen and prevents them by making transactions wait (locks). Optimistic control lets everyone proceed and checks at write or commit time, aborting the loser (version columns, compare-and-set, PostgreSQL's SSI, MongoDB's write conflicts). Real engines mix both: PostgreSQL and InnoDB use MVCC so readers do not lock, and locks so writers do not collide. Which strategy to choose for your application is the subject of Optimistic vs Pessimistic Locking; this page is about the locks themselves.

Fewer or weaker locksMore or stronger locks
More concurrency, higher throughputTransactions wait in queues
Anomalies possible unless you add checksAnomalies prevented by construction
Errors at commit (retry) in optimistic schemesWaits, timeouts and deadlocks instead of retries
Cheap for read-heavy workloadsCheap for short, conflicting writes on few rows
Hard to reason about every interleavingHard to reason about wait chains and lock order

The analogy we reuse: a restaurant kitchen. Everyone may look at the menu on the wall (ACCESS SHARE). Cooks may use the stove at once because each has a pan (ROW EXCLUSIVE plus a row lock per pan). Repainting the kitchen (ACCESS EXCLUSIVE) needs it empty. The painter waits at the door for the last cook, and while the painter waits, the host seats no one new, not even for a glance at the menu: that is the lock queue. A sticky note on a pan saying "mine, don't touch" is a row lock; a sign on the pantry door saying "stocktaking in progress" that only polite staff respect is an advisory lock.

Three common misunderstandings, up front ​

  1. "A plain SELECT never waits." It takes ACCESS SHARE, which conflicts with ACCESS EXCLUSIVE, so ALTER TABLE, TRUNCATE, DROP and VACUUM FULL block it, and a waiting ACCESS EXCLUSIVE request blocks it too.
  2. "ROW EXCLUSIVE locks rows." It is a table-level mode. PostgreSQL's manual: "all of these lock modes are table-level locks, even if the name contains the word 'row'; the names of the lock modes are historical." Row locks are a separate mechanism stored in the row itself.
  3. "A lock wait will time out on its own." PostgreSQL's lock_timeout defaults to 0 (wait forever). InnoDB's innodb_lock_wait_timeout is 50 seconds, and MySQL's metadata-lock lock_wait_timeout defaults to a year. Unbounded waiting is the default almost everywhere.

Where it comes from ​

The vocabulary on this page comes from the IBM System R era (mid-1970s), where Eswaran, Gray, Lorie and Traiger described two-phase locking and Gray, Lorie, Putzolu and Traiger described lock granularity and intention modes. I did not re-read those papers for this page; the definitions below follow the engines' own manuals, which still use the same words. MongoDB's FAQ, for example, states the multiple-granularity scheme directly:

"In addition to a shared (S) locking mode for reads and an exclusive (X) locking mode for write operations, intent shared (IS) and intent exclusive (IX) modes indicate an intent to read or write a resource using a finer granularity lock." — MongoDB Manual, FAQ: Concurrency

PostgreSQL ships locks next to MVCC, not instead of it. Its manual says the lock modes "can be used for application-controlled locking in situations where MVCC does not give the desired behavior. Also, most PostgreSQL commands automatically acquire locks of appropriate modes to ensure that referenced tables are not dropped or modified in incompatible ways while the command executes." So there are implicit locks, taken by every statement for its own safety, and explicit locks you request: SELECT ... FOR UPDATE, LOCK TABLE, pg_advisory_lock. The InnoDB side is documented in the MySQL 8.4 manual, "InnoDB Locking", which defines shared and exclusive locks, intention locks, record, gap, next-key, insert intention and AUTO-INC locks. (The first request to dev.mysql.com returned HTTP 403 with a browser User-Agent; curl/8 as the agent returned 200 and the page.)

The concept catalogue ​

Each block: plain words, the usual wrong belief, definition, a two-session timeline, real scenarios, what each engine does, and the fix in SQL, Go and Laravel where code helps.

Locks vs latches: lightweight locks, spinlocks, buffer pins Important ​

In plain words: a lock protects your data for the length of a transaction and shows up in pg_locks. A latch protects the engine's own memory for a few microseconds and you never ask for it.

Common misunderstanding: "If pg_locks shows nothing waiting, there is no lock contention." Latch contention (LWLock waits on WALWrite, BufferContent, LockManager, ProcArray) never appears in pg_locks; you see it only in pg_stat_activity.wait_event_type.

Definition: PostgreSQL's lock manager README lists four kinds of interprocess locks:

"Spinlocks. These are intended for very short-term locks. If a lock is to be held more than a few dozen instructions, or across any sort of kernel call (or even a call to a nontrivial subroutine), don't use a spinlock." — PostgreSQL source, src/backend/storage/lmgr/README

The same file describes lightweight locks (LWLocks) as locks "typically used to interlock access to datastructures in shared memory", with shared and exclusive modes, no deadlock detection and "no timeout"; regular (heavyweight) locks, which have "full deadlock detection and automatic release at transaction end" and "should be used for all user-driven lock requests"; and SIReadLock predicate locks for Serializable. A buffer pin is a reference count on a shared buffer that stops it being evicted or cleaned while a backend reads it; VACUUM needs a "cleanup lock" (an exclusive pin) and waits with the BufferCleanup wait event when a cursor still holds a pin. The Explicit Locking chapter calls the per-page share/exclusive locks page-level locks and says they "are released immediately after a row is fetched or updated". InnoDB uses the same split: its row locks live in the lock system, while mutexes and rw-locks (latches) guard pages and internal lists, tuned by innodb_spin_wait_delay and innodb_sync_spin_loops.

text
     backend A                                   backend B
1    pin buffer 4711, take content lock (share)  pin buffer 4711, take content lock (share)  -- both fine
2    read tuple, release content lock            want content lock (exclusive) to write
3                                                -- waits microseconds: wait_event_type = LWLock
4    unpin buffer                                writes tuple, releases; nothing in pg_locks at any step

Real scenarios: a hot insert-only table whose last page every backend wants (BufferContent, relation extend locks); thousands of connections taking snapshots (ProcArray); many partitions touched per query exhausting fast-path slots (LockManager); VACUUM stuck behind an open cursor (BufferCleanup).

Lock (heavyweight)Latch (LWLock, spinlock, pin)
ProtectsTables, rows, objects, advisory keysShared-memory structures, buffer pages
Held forUntil transaction end (usually)Microseconds
Deadlock detectionYesNo
Visible inpg_locks, performance_schema.data_lockswait_event_type = LWLock, Buffer; InnoDB SEMAPHORES section
You control itYes (SQL)Only indirectly (fewer connections, fewer partitions per query)

Fix: latch contention is fixed by design, not by SQL: fewer active connections (a pooler, see Connection Pooling), fewer partitions touched per statement, fill factor and HOT updates for hot pages, and short cursors.

Shared, exclusive and intention locks (S, X, IS, IX) Must-know ​

In plain words: many readers may share a thing (S); one writer must have it alone (X). Intention locks are a cheap sign on the table that says "someone holds row locks inside", so a whole-table lock request can see it without checking every row.

Common misunderstanding: "Intention locks block other row lockers." They do not; IX and IX are compatible. The MySQL manual: "Intention locks do not block anything except full table requests (for example, LOCK TABLES ... WRITE)."

Definition: InnoDB's rules: before a shared row lock, take IS (or stronger) on the table; before an exclusive row lock, take IX. SELECT ... FOR SHARE sets IS, SELECT ... FOR UPDATE sets IX. The compatibility matrix from the manual:

Requested \ HeldXIXSIS
XConflictConflictConflictConflict
IXConflictCompatibleConflictCompatible
SConflictConflictCompatibleCompatible
ISConflictCompatibleCompatibleCompatible

PostgreSQL's ROW SHARE and ROW EXCLUSIVE play the role of IS and IX: they are the table-level modes taken by row lockers and writers. MongoDB uses the same hierarchy (global, database, collection) with S, X, IS, IX; SQL Server uses S, U, X, IS, IU, IX, SIX on rows, pages and tables.

text
     T1                                             T2
1    START TRANSACTION;                             START TRANSACTION;
2    SELECT * FROM t WHERE id=1 FOR UPDATE;
       -- IX on table t, X on record id=1
3                                                   SELECT * FROM t WHERE id=2 FOR UPDATE;
                                                      -- IX on t (compatible), X on id=2: no wait
4                                                   LOCK TABLES t WRITE;  -- needs X on t: waits for T1's IX
5    COMMIT;                                        -- granted

Real scenarios: LOCK TABLES ... WRITE in an old MySQL backup script that hangs behind any open transaction; mysqldump --lock-tables vs --single-transaction; MongoDB collMod or index builds needing X on a collection while writes hold IX.

Fix: let the engine pick intention locks; avoid table-level S/X (LOCK TABLES, TABLOCKX) in OLTP paths.

Two-phase locking (2PL) and strict 2PL Important ​

In plain words: a transaction first only takes locks (growing phase), then only releases them (shrinking phase). Strict 2PL keeps its write locks until commit, so nobody ever sees or overwrites uncommitted data.

Common misunderstanding: "PostgreSQL and InnoDB are 2PL databases." They hold every lock until transaction end (strict, in fact rigorous, 2PL for locks), but plain reads take no row locks thanks to MVCC, so their default isolation does not come from 2PL. InnoDB SERIALIZABLE is the 2PL exception: with autocommit off it turns plain SELECT into SELECT ... FOR SHARE.

Definition: basic 2PL guarantees conflict-serializable schedules but allows cascading aborts; strict 2PL holds exclusive locks to commit or abort; rigorous (strong strict) 2PL holds all locks to the end. PostgreSQL: "Once acquired, a lock is normally held until the end of the transaction", except that rolling back to a savepoint releases locks taken after it.

text
     T1 (InnoDB SERIALIZABLE, autocommit off)       T2
1    START TRANSACTION;                              START TRANSACTION;
2    SELECT balance FROM acct WHERE id=1;
       -- becomes FOR SHARE: S lock on id=1 (growing)
3                                                    UPDATE acct SET balance=0 WHERE id=1;  -- waits (X vs S)
4    UPDATE acct SET balance=balance-10 WHERE id=1;  -- S→X upgrade
5    COMMIT;  -- all locks released at once (shrinking happens only here)
6                                                    -- granted, sees committed balance

Real scenarios: InnoDB SERIALIZABLE reporting jobs blocking writers; SQL Server under SERIALIZABLE or HOLDLOCK taking key-range locks; SQLite holding its database write lock to commit.

EngineLocks held to end of transactionPlain reads lock?
PostgreSQLAll heavyweight locks (savepoint rollback releases)No (MVCC)
MySQL InnoDBAll row and table locksNo, except SERIALIZABLE (becomes FOR SHARE)
SQL ServerX always; S only under REPEATABLE READ/SERIALIZABLEYes under locking READ COMMITTED; no with RCSI
OracleRow (TX) and table (TM) locksNever

Fix: keep the growing phase short. Lock upgrade (S then X on the same row) is the most common self-made deadlock; take the strongest lock you will need first, as the PostgreSQL manual advises: "the first lock acquired on an object in a transaction is the most restrictive mode that will be needed for that object."

Lock granularity: row, page, table, database Important ​

In plain words: you can lock a single row, a page of rows, a whole table or the whole database. Finer means more concurrency but more locks to manage.

Common misunderstanding: "Row locking is always better." Locking a million rows one by one costs memory and time; that is why SQL Server escalates to a table lock, and why a LOCK TABLE before a bulk rewrite is sometimes correct.

Definition: granularity is the size of the locked unit. Lock escalation replaces many fine locks with one coarse lock. Lock conversion (upgrade) changes the mode of a lock already held (S→X).

text
     T1 (SQL Server)                                       T2
1    BEGIN TRAN;
2    UPDATE orders SET archived=1 WHERE created < '2024-01-01';
       -- 5,000th row lock on orders: escalation to table X
3                                                          SELECT * FROM orders WHERE id=7;  -- blocked: whole table locked
4    COMMIT;                                               -- proceeds
EngineFinest data lockEscalationCoarsest
PostgreSQLRow (stored in the tuple header, no memory limit)NeverTable (LOCK TABLE), plus pg_database-level object locks
MySQL InnoDBIndex record (bitmap per page in the lock system)NeverTable (LOCK TABLES, intention locks)
MySQL MyISAMTablen/aTable
SQL ServerRow (RID/KEY) or page (PAG)Yes, at 5,000 locks per statement per table, to table (or partition with LOCK_ESCALATION = AUTO)Database
OracleRow (in the data block)NeverTable (TM lock)
SQLiteDatabase filen/aDatabase file (one writer)
MongoDB (WiredTiger)Documentn/aGlobal, database, collection intent locks

Fix: batch large updates (1,000 to 5,000 rows per transaction) so no statement escalates and no row lock lives long; on SQL Server inspect ALTER TABLE ... SET (LOCK_ESCALATION = ...) before disabling escalation.

PostgreSQL table-level lock modes Must-know ​

In plain words: before touching a table, every statement takes one of eight table-level modes. The mode is about what else may run on the table at the same time.

Common misunderstanding: "The mode names tell you what is locked." The manual is explicit: "the only real difference between one lock mode and another is the set of lock modes with which each conflicts." Self-conflict matters too: SHARE does not conflict with itself, SHARE ROW EXCLUSIVE does.

Definition: a lock is granted if it does not conflict with any mode held by another transaction on the same table ("a transaction never conflicts with itself"). The full matrix:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXPostgreSQL table-level lock conflictscolumn = mode already held by another transactionrow = requested mode (typical taker)ASRSRXSUXSSRXXAXAS ACCESS SHARESELECTRS ROW SHARESELECT ... FOR UPDATE/SHARERX ROW EXCLUSIVEINSERT, UPDATE, DELETE, MERGESUX SHARE UPDATE EXCLUSIVEVACUUM, ANALYZE, CREATE INDEX CONC.S SHARECREATE INDEXSRX SHARE ROW EXCLUSIVECREATE TRIGGER, some ALTERX EXCLUSIVEREFRESH MAT. VIEW CONCURRENTLYAX ACCESS EXCLUSIVEDROP, TRUNCATE, most ALTER TABLEX cell: the requester waits in the queue (or fails at once with NOWAIT, or after lock_timeout: 55P03).Empty cell: both granted together. A transaction never conflicts with its own locks.
Requested \ HeldACCESS SHAREROW SHAREROW EXCL.SHARE UPDATE EXCL.SHARESHARE ROW EXCL.EXCL.ACCESS EXCL.
ACCESS SHAREX
ROW SHAREXX
ROW EXCLUSIVEXXXX
SHARE UPDATE EXCLUSIVEXXXXX
SHAREXXXXX
SHARE ROW EXCLUSIVEXXXXXX
EXCLUSIVEXXXXXXX
ACCESS EXCLUSIVEXXXXXXXX

Which statement takes which lock (from the manual and each command's page):

StatementTable lockBlocks reads?Blocks writes?
SELECTACCESS SHARENoNo
SELECT ... FOR UPDATE / NO KEY UPDATE / SHARE / KEY SHAREROW SHARE (+ row locks)NoOnly on locked rows
INSERT, UPDATE, DELETE, MERGE, COPY FROMROW EXCLUSIVE (+ row locks)NoOnly on the same rows
VACUUM (not FULL), ANALYZE, CREATE INDEX CONCURRENTLY, REINDEX CONCURRENTLY, CREATE STATISTICS, COMMENT ONSHARE UPDATE EXCLUSIVENoNo
ALTER TABLE ... VALIDATE CONSTRAINT, SET STATISTICS, ATTACH PARTITION (on the parent)SHARE UPDATE EXCLUSIVENoNo
CREATE INDEX (not concurrently)SHARENoYes, for the whole build
CREATE TRIGGER, ALTER TABLE ... ADD FOREIGN KEY (both tables)SHARE ROW EXCLUSIVENoYes
REFRESH MATERIALIZED VIEW CONCURRENTLYEXCLUSIVENoYes
DROP TABLE, TRUNCATE, REINDEX, CLUSTER, VACUUM FULL, REFRESH MATERIALIZED VIEW, REPACK (PostgreSQL 19)ACCESS EXCLUSIVEYesYes
Most ALTER TABLE forms (ADD COLUMN, DROP COLUMN, ALTER COLUMN TYPE, SET NOT NULL, RENAME)ACCESS EXCLUSIVEYesYes
LOCK TABLE t (no mode given)ACCESS EXCLUSIVEYesYes
text
     T1                                           T2
1    BEGIN;
2    CREATE INDEX ON orders (customer_id);        -- SHARE, build takes 4 minutes
3                                                 SELECT count(*) FROM orders;   -- ACCESS SHARE: runs
4                                                 INSERT INTO orders ...;         -- ROW EXCLUSIVE vs SHARE: waits 4 minutes
5    COMMIT;                                      -- INSERT proceeds
     -- CREATE INDEX CONCURRENTLY takes SHARE UPDATE EXCLUSIVE instead: step 4 does not wait

Real scenarios: a plain CREATE INDEX on orders during business hours stops checkout; ALTER TABLE ... ADD COLUMN ... DEFAULT now() (volatile default) rewrites the table under ACCESS EXCLUSIVE; TRUNCATE in a test-cleanup job waits behind a dashboard query; adding a foreign key locks the referenced table against writes while it validates (use NOT VALID then VALIDATE CONSTRAINT).

Fix:

sql
-- PostgreSQL: weakest mode that does the job, bounded wait
SET lock_timeout = '2s';
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders (customer_id);   -- SHARE UPDATE EXCLUSIVE
ALTER TABLE orders ADD CONSTRAINT fk_cust FOREIGN KEY (customer_id)
  REFERENCES customers (id) NOT VALID;                                    -- short SHARE ROW EXCLUSIVE
ALTER TABLE orders VALIDATE CONSTRAINT fk_cust;                           -- SHARE UPDATE EXCLUSIVE, long but non-blocking
LOCK TABLE audit_log IN SHARE ROW EXCLUSIVE MODE;                         -- explicit, when you really need it

PostgreSQL row-level locks Must-know ​

In plain words: row locks say "nobody else may change (or lock) this row until I finish". Readers are never blocked by them.

Common misunderstanding: "FOR UPDATE is the normal way to lock a row I will update." It is the strongest mode and also blocks foreign-key checks (FOR KEY SHARE) from child-table inserts. If you will not change the key, FOR NO KEY UPDATE is enough and is what a plain UPDATE takes.

Definition: four modes, strongest first. FOR UPDATE "prevents them from being locked, modified or deleted by other transactions until the current transaction ends"; it is also taken by DELETE and by an UPDATE that changes a column with a unique index usable by a foreign key. FOR NO KEY UPDATE is "weaker: this lock will not block SELECT FOR KEY SHARE commands", and is taken by every other UPDATE. FOR SHARE is a shared lock that blocks UPDATE, DELETE, FOR UPDATE and FOR NO KEY UPDATE. FOR KEY SHARE blocks only DELETE and key-changing updates; foreign-key checks take it on the parent row. "Row-level locks do not affect data querying; they block only writers and lockers to the same row." PostgreSQL stores row locks in the tuple (xmax, with a MultiXact for several sharers), so "there is no limit on the number of rows locked at one time", but "SELECT FOR UPDATE modifies selected rows to mark them locked, and so will result in disk writes".

Requested \ HeldFOR KEY SHAREFOR SHAREFOR NO KEY UPDATEFOR UPDATE
FOR KEY SHAREX
FOR SHAREXX
FOR NO KEY UPDATEXXX
FOR UPDATEXXXX
text
     T1                                                  T2
1    BEGIN;                                              BEGIN;
2    SELECT * FROM orders WHERE id=7 FOR UPDATE;
3                                                        INSERT INTO order_items (order_id, sku) VALUES (7, 'A');
                                                           -- FK check wants FOR KEY SHARE on orders 7: WAITS
4    COMMIT;                                             -- proceeds
     -- with FOR NO KEY UPDATE at step 2, step 3 does not wait at all

Real scenarios: an order-status worker locking orders with FOR UPDATE and stalling every order_items insert; a ledger reading a parent account FOR SHARE so it cannot be deleted mid-transfer; a booking flow locking the seat row before charging the card.

EngineRow lock syntaxNotes
PostgreSQLFOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, each with NOWAIT / SKIP LOCKED, OF tableRepeatable Read/Serializable raise 40001 if the row changed since the snapshot
MySQL InnoDB 8.0+FOR UPDATE, FOR SHARE (old: LOCK IN SHARE MODE), NOWAIT, SKIP LOCKED, OF tblLocks index records it scans, plus gaps at Repeatable Read
SQL ServerTable hints UPDLOCK, XLOCK, HOLDLOCK, ROWLOCK, READPASTUPDLOCK takes U locks, which avoid S→X conversion deadlocks
OracleFOR UPDATE [OF col] [NOWAIT / WAIT n / SKIP LOCKED]No shared row lock mode; readers never wait
SQLitenoneThe whole database is the lock unit
MongoDBnone; a write to a document is atomicTransactions get WriteConflict instead of waiting

Fix in SQL, Go and Laravel:

sql
BEGIN;
SELECT status FROM orders WHERE id = $1 FOR NO KEY UPDATE;   -- lock before deciding
UPDATE orders SET status = 'shipped' WHERE id = $1;
COMMIT;

Go (worker.go, imported in full under Solutions): the same two statements inside db.BeginTx. Laravel: Order::query()->lockForUpdate()->findOrFail($id) inside DB::transaction; Laravel's sharedLock() maps to FOR SHARE on PostgreSQL. Neither helper emits FOR NO KEY UPDATE, so use ->lock('for no key update'), which accepts a raw clause.

The lock queue: ACCESS EXCLUSIVE behind a long query Must-know ​

In plain words: lock requests wait in a queue, and a request that is waiting also blocks the requests behind it. One idle transaction plus one ALTER TABLE can stop every query on a table.

Common misunderstanding: "My SELECT only conflicts with what is held, and only an old reader holds anything, so it should run." The SELECT is compatible with the holder but conflicts with the waiting ACCESS EXCLUSIVE request ahead of it, so it queues to keep the ALTER from starving.

Definition: PostgreSQL's documentation for pg_blocking_pids names both kinds of blocking:

"One server process blocks another if it either holds a lock that conflicts with the blocked process's lock request (hard block), or is waiting for a lock that would conflict with the blocked process's lock request and is ahead of it in the wait queue (soft block)." — PostgreSQL documentation, System Information Functions, pg_blocking_pids

Combine that with unbounded waits ("a transaction seeking either a table-level or row-level lock will wait indefinitely for conflicting locks to be released") and an innocent migration freezes the table. MySQL behaves the same way through metadata locks: "Write lock requests have higher priority than read lock requests," so a pending ALTER TABLE ("Waiting for table metadata lock") blocks later SELECTs.

Lock queue on table "orders" (PostgreSQL)GRANTEDWAITING (hard block)WAITING (soft block, behind the ALTER)pid 101ACCESS SHAREidle in transactionpid 202 ALTER TABLEwants ACCESSEXCLUSIVEpid 303 SELECTACCESS SHARE(compatible!)pid 304 SELECTACCESS SHARE... and every next oneconflictpg_blocking_pids(303) = {202}What happens1. pid 101 read orders and never committed; it still holds ACCESS SHARE.2. ALTER needs ACCESS EXCLUSIVE, conflicts with 101, waits with no limit (lock_timeout = 0).3. New SELECTs conflict with the waiting request, so they queue behind it: the table looks down.Fix: SET LOCAL lock_timeout = '2s' on the ALTER, retry with backoff; end idle transactions first.
text
     A (app, forgotten tx)         B (migration)                          C, D, E ... (traffic)
1    BEGIN;
2    SELECT * FROM orders LIMIT 1;
     -- idle in transaction, holds ACCESS SHARE
3                                  ALTER TABLE orders ADD COLUMN note text;
                                   -- wants ACCESS EXCLUSIVE: waits for A
4                                                                         SELECT * FROM orders WHERE id=1;  -- waits for B (soft)
5                                                                         ... connection pool fills, timeouts, 502s
6    -- A commits 10 minutes later, or B is cancelled: the queue drains in milliseconds

Real scenarios: a deploy whose migration hangs and takes the site down while doing nothing; TRUNCATE in a nightly job behind a BI query; VACUUM FULL started "for a minute" on a large table; Laravel php artisan migrate during traffic; MySQL ALTER TABLE behind a long SELECT in another session.

Fix: SET LOCAL lock_timeout = '2s' on every DDL plus a retry loop (see migrations); kill or time out idle transactions first (idle_in_transaction_session_timeout); on MySQL, SET SESSION lock_wait_timeout = 5 before DDL. The full migration playbook is in Zero-Downtime Schema Migrations.

Bounding waits: lock_timeout, statement_timeout, NOWAIT, SKIP LOCKED Must-know ​

In plain words: you choose between waiting forever (the default), waiting up to a limit, failing at once, or skipping what is busy.

Common misunderstanding: "statement_timeout is enough." It counts execution too, so a value small enough to protect against lock waits kills legitimate slow queries. PostgreSQL: "Unlike statement_timeout, this timeout can only occur while waiting for locks", and "if statement_timeout is nonzero, it is rather pointless to set lock_timeout to the same or larger value".

Definition:

ToolScopeEffect on conflictError
lock_timeout (PostgreSQL, default 0)Each lock wait in a statementFails after the limit55P03 lock_not_available, "canceling statement due to lock timeout"
statement_timeout (PostgreSQL, default 0)Whole statementFails after the limit, waiting or running57014 query_canceled
idle_in_transaction_session_timeoutIdle time inside a transactionTerminates the session, releasing its locks25P03
transaction_timeout (PostgreSQL 17+)Whole transactionTerminates the session25P04
NOWAIT (PostgreSQL, MySQL 8.0+, Oracle)One locking statementFails at oncePG 55P03; MySQL 3572 ER_LOCK_NOWAIT; Oracle ORA-00054
SKIP LOCKED (PostgreSQL, MySQL 8.0+, Oracle) / READPAST (SQL Server)One locking SELECTSilently omits locked rowsnone
innodb_lock_wait_timeout (MySQL, default 50 s)Each row lock waitRolls back the statement (whole tx if innodb_rollback_on_timeout=ON)1205 "Lock wait timeout exceeded; try restarting transaction"
lock_wait_timeout (MySQL, metadata locks)DDL and LOCK TABLES waitsFails after the limit1205
SET LOCK_TIMEOUT ms (SQL Server, default -1)Each lock waitFails after the limit1222 "Lock request time out period exceeded"
WAIT n (Oracle) / DDL_LOCK_TIMEOUTStatement / DDLFails after n secondsORA-30006 / ORA-00054

The PostgreSQL manual warns against a global lock_timeout because it "would affect all sessions"; set it per role, per transaction (SET LOCAL) or per statement. Its SELECT page defines the two clauses: "With NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately" and "With SKIP LOCKED, any selected rows that cannot be immediately locked are skipped." The MySQL manual adds that queries that skip locked rows "return an inconsistent view of the data": use SKIP LOCKED for queues, never for reports.

text
     T1                                            T2
1    BEGIN;                                        BEGIN;
2    SELECT * FROM seats WHERE id=5 FOR UPDATE;
3                                                  SET LOCAL lock_timeout = '1s';
4                                                  SELECT * FROM seats WHERE id=5 FOR UPDATE;
5                                                  -- after 1 s: ERROR 55P03 canceling statement due to lock timeout
6                                                  SELECT * FROM seats WHERE id=5 FOR UPDATE NOWAIT;
                                                   -- at once: ERROR 55P03 could not obtain lock on row in relation "seats"
7                                                  SELECT * FROM seats WHERE id IN (5,6) FOR UPDATE SKIP LOCKED;  -- returns only 6

Real scenarios: an HTTP handler that must answer within 2 seconds (lock_timeout = '500ms', then answer 409/503); a seat map that greys out seats being booked (SKIP LOCKED); a migration tool (lock_timeout + retry); a cron that should skip if a previous run still holds the row (NOWAIT).

Fix in Go and Laravel: treat 55P03 as retryable or as "busy", not as a crash.

go
var pgErr *pgconn.PgError // github.com/jackc/pgx/v5/pgconn
if errors.As(err, &pgErr) && pgErr.Code == "55P03" {
	return ErrBusy // answer 409 or retry with backoff
}
php
try {
    DB::transaction(function () use ($id) {
        DB::statement("SET LOCAL lock_timeout = '500ms'");
        $seat = Seat::query()->lock('for update nowait')->findOrFail($id);
        // ...
    });
} catch (\Illuminate\Database\QueryException $e) {
    if ($e->getCode() === '55P03') {
        abort(409, 'Seat is being booked, try again.');
    }
    throw $e;
}

Advisory locks Important ​

In plain words: a mutex with a number for a name, stored in the database's lock table. The database does not know what it protects; your code agrees on the meaning.

Common misunderstanding: "Advisory locks are safe behind any connection pool." Session-level locks belong to one connection; through PgBouncer in transaction mode or a *sql.DB pool, the unlock may go to a different connection, which does nothing and leaks the lock.

Definition: "advisory locks, because the system does not enforce their use — it is up to the application to use them correctly." Two scopes. Session level: "held until explicitly released or the session ends", do "not honor transaction semantics", and are re-entrant (each lock needs its own unlock). Transaction level: "automatically released at the end of the transaction, and there is no explicit unlock operation." Functions (PostgreSQL): pg_advisory_lock, pg_try_advisory_lock, pg_advisory_unlock, pg_advisory_unlock_all, pg_advisory_xact_lock, pg_try_advisory_xact_lock, plus _shared variants of each. Keys are one bigint or two int4. They share the lock table with regular locks, sized by max_locks_per_transaction and max_connections, and appear in pg_locks with locktype = 'advisory' and in pg_stat_activity with wait_event = 'advisory'.

text
     replica A                                      replica B
1    SELECT pg_try_advisory_lock(727001);  -- t
2                                                   SELECT pg_try_advisory_lock(727001);  -- f: skip this run
3    ... builds the nightly report ...
4                                                   SELECT pg_advisory_lock(727001);      -- blocking form: waits
5    SELECT pg_advisory_unlock(727001);    -- t
6                                                   -- returns, B now holds it

Real scenarios: one-instance cron jobs (nightly report, billing run); serialising work per tenant or per account (pg_advisory_xact_lock(hashtext('tenant:' || id))); migration tools guarding against two deploys at once (several Go and Rails migration tools do this); leader election for a single consumer.

ProductAdvisory / named lockRelease
PostgreSQLpg_advisory_lock family (session or transaction)Unlock, transaction end, or session end
MySQLGET_LOCK('name', timeout), RELEASE_LOCK, IS_FREE_LOCK (metadata-lock subsystem)Explicit or session end
SQL Serversp_getapplock / sp_releaseapplock (session or transaction owner)Explicit or owner end
OracleDBMS_LOCK.REQUEST / RELEASEExplicit, commit (if requested) or session end
RedisSET key token NX PX 30000 + compare-and-deleteExpiry or delete; a lease, not a lock
LaravelCache::lock('name', 10) atomic locks on redis, database, memcached and other driversrelease(), block(), expiry

Fix: prefer pg_try_advisory_xact_lock inside a transaction; when the work spans transactions, pin a connection (db.Conn in Go). Beware SELECT pg_advisory_lock(id) FROM foo WHERE id > 12345 LIMIT 100, which the manual flags as "danger!" because the LIMIT is not guaranteed to run before the locking function. Full code in Singleton job.

InnoDB record, gap, next-key, insert intention and AUTO-INC locks Must-know ​

In plain words: InnoDB locks entries in an index, and at Repeatable Read also the gaps between them, so nobody can insert a row into a range you read with a locking read.

Common misunderstanding: "SELECT ... WHERE c1 = 11 FOR UPDATE locks one row." On a non-unique index (or with no usable index) it also locks the gap before the next value, and without an index it locks every row it scans. "Row-level locks are actually index-record locks."

Definition (MySQL 8.4 manual):

  • Record lock: "a lock on an index record". Even a table without indexes is locked through the hidden clustered index.
  • Gap lock: "a lock on a gap between index records, or a lock on the gap before the first or after the last index record". Gap locks are "purely inhibitive": they only stop inserts, and two transactions can hold gap locks on the same gap.
  • Next-key lock: "a combination of a record lock on the index record and a gap lock on the gap before the index record". For an index with 10, 11, 13 and 20, the next-key ranges are (-inf, 10], (10, 11], (11, 13], (13, 20], (20, +inf) (the last one via the "supremum" pseudo-record).
  • Insert intention lock: a gap lock taken by INSERT before inserting; inserts at different positions in the same gap do not block each other, but they wait for a gap or next-key lock held by someone else.
  • AUTO-INC lock: "a special table-level lock taken by transactions inserting into tables with AUTO_INCREMENT columns". innodb_autoinc_lock_mode chooses 0 (traditional), 1 (consecutive) or 2 (interleaved, the default since MySQL 8.0, which avoids the table-level lock for most inserts but requires row-based replication to be safe).
  • Gap locking is disabled for searches and scans at READ COMMITTED (still used for foreign-key and duplicate-key checks), and is not needed when a unique index finds one unique row.
InnoDB next-key locks on index c1 (values 10, 11, 13, 20)T1 (REPEATABLE READ, non-unique index): SELECT * FROM t WHERE c1 = 11 FOR UPDATE;(-inf, 10](10, 11]next-key(11, 13)gap only(13, 20](20, supremum]10111320T2: INSERT c1 = 12waits: insert intention lockvs T1's gap lockT3: INSERT c1 = 15proceeds: gap (13, 20)is not lockedUnique index + equality on an existing row: record lock on 11 only, no gap. READ COMMITTED: no gap locks for searches.
text
     T1 (InnoDB REPEATABLE READ; child has ids 90, 102)   T2
1    START TRANSACTION;                                    START TRANSACTION;
2    SELECT * FROM child WHERE id > 100 FOR UPDATE;
       -- next-key (90,102] and (102, supremum]
3                                                          INSERT INTO child (id) VALUES (101);
                                                             -- insert intention waits on the gap
4                                                          -- after 50 s: ERROR 1205 Lock wait timeout exceeded
5    COMMIT;                                               -- or the insert proceeds as soon as T1 commits

Real scenarios: two concurrent "check if a slot is free, then insert" transactions that both take a gap lock and then deadlock on each other's insert intention (MySQL error 1213); bulk INSERT ... SELECT holding locks on the source table; an UPDATE ... WHERE status = 'new' without an index locking every row in the table; INSERT stalls on a busy auto-increment table with mode 0 or 1.

InnoDB lockdata_locks.LOCK_MODESHOW ENGINE INNODB STATUS text
Table intentionIX / IS (LOCK_TYPE = TABLE)TABLE LOCK table ... lock mode IX
Record onlyX,REC_NOT_GAP / S,REC_NOT_GAPlock_mode X locks rec but not gap
Gap onlyX,GAPlock_mode X locks gap before rec
Next-keyX / Slock_mode X
Insert intentionX,GAP,INSERT_INTENTIONlock_mode X locks gap before rec insert intention waiting

Fix: index the columns in your locking WHERE clauses; use unique lookups when you can; consider READ COMMITTED for OLTP workloads that do not rely on gap locks (the phantom trade-off is on Isolation Levels); keep innodb_autoinc_lock_mode = 2 with row-based binlog.

MVCC: readers do not block writers Must-know ​

In plain words: in PostgreSQL, InnoDB and Oracle a reader sees an older committed version of a row while a writer prepares a new one, so neither waits for the other. Locks are only for writer vs writer and for explicit locking reads.

Common misunderstanding: "With MVCC there are no locks." Writers still take row locks (two writers on one row queue), DDL still takes table locks, and locking reads (FOR UPDATE) behave like writers.

Definition: multi-version concurrency control keeps several versions of a row; each statement or transaction reads from a snapshot. The PostgreSQL manual's tip "Only an ACCESS EXCLUSIVE lock blocks a SELECT" is the table-level face of this. The version mechanics are in MVCC, VACUUM & Bloat.

text
     T1 (writer)                                    T2 (reader)
1    BEGIN;
2    UPDATE accounts SET balance=50 WHERE id=1;     -- row lock on id=1
3                                                   SELECT balance FROM accounts WHERE id=1;  -- 100, no wait
4                                                   SELECT balance FROM accounts WHERE id=1 FOR SHARE;  -- WAITS (locking read)
5    COMMIT;                                        -- now returns 50
EnginePlain reader vs writerWriter vs writer
PostgreSQLNever waitRow lock, second waits
MySQL InnoDBNever wait (consistent nonlocking read), except SERIALIZABLERow/next-key lock, second waits
OracleNever waitRow lock (TX), second waits
SQL Server, locking READ COMMITTED (default on-premises)Reader waits for writer's X lockWaits
SQL Server with READ_COMMITTED_SNAPSHOT (default in Azure SQL Database)No waitWaits
SQLite WAL modeReaders do not block the writer, and vice versaOne writer at a time
MongoDB WiredTigerNo wait (snapshot)One write wins, the other retries (WriteConflict)

Fix: to make a read part of a decision, lock it (FOR UPDATE/FOR NO KEY UPDATE) or use an atomic statement; do not rely on "I just read it".

Hot rows and lock-free counters Important ​

In plain words: if every request updates the same row (a global counter, a popular product's stock, a single wallet), all of them queue on that row's lock and throughput is capped by how long each holds it.

Common misunderstanding: "An atomic UPDATE x = x + 1 has no locking cost." It has no race, but it still takes a row lock to the end of the transaction. At 5 ms per transaction one row sustains about 200 commits a second, whatever the hardware.

Definition: a hot row is a row whose lock is contended by most concurrent transactions. Lock-free designs avoid a single serialisation point: sharded counters (N rows summed on read), append-only event rows aggregated later, in-memory atomics (sync/atomic, Redis INCR, which is atomic because Redis executes commands on one thread), or batching increments in the application.

text
     T1                                              T2 ... T200
1    BEGIN;
2    UPDATE stats SET views=views+1 WHERE id=1;      UPDATE stats SET views=views+1 WHERE id=1;  -- all wait
3    INSERT INTO page_log ...;   -- 4 ms
4    COMMIT;                                         -- next one gets the lock; the queue moves one at a time

Real scenarios: a "total likes" column on a viral post; inventory.stock for one flash-sale SKU; a single sequences table used instead of a database sequence; a tenant-level updated_at touched by every child write (Laravel $touches).

OptionHowGainCost
Shorten the transactionUpdate the hot row last, commit at onceLinear gainStill one queue
Sharded counterN rows per key, random shard, sum() on read~N× write throughputReads aggregate N rows
Append and aggregateInsert an event row, roll up every few secondsNo row contentionCounter lags
Redis INCR / HINCRBYSingle-threaded atomic incrementVery high throughputSeparate durability story
Sequence instead of counter tablenextval() is non-transactionalNo lock at allGaps on rollback

Fix: the sharded counter is in Hot-row counter redesign.

Per-engine behaviour ​

FeaturePostgreSQLMySQL InnoDBSQL ServerOracleSQLiteMongoDB
Smallest data lockRow (tuple header)Index record + gapRow/key, pageRow (in block)DatabaseDocument
Readers block writers?NoNo (except SERIALIZABLE)Yes under locking RC; no with RCSINoRollback journal: yes; WAL: noNo
EscalationNeverNeverAt 5,000 locksNevern/an/a
Range/phantom locksNone (SSI predicate locks are non-blocking)Gap / next-keyKey-range (SERIALIZABLE)Nonen/an/a
Lock wait defaultForever50 s rows, 1 year metadataForeverForeverbusy_timeout 0: fail at once with SQLITE_BUSYTransactions: 5 ms lock request timeout
Skip locked rowsSKIP LOCKEDSKIP LOCKEDREADPASTSKIP LOCKEDn/an/a
Advisory lockpg_advisory_*GET_LOCKsp_getapplockDBMS_LOCKnonenone
See lockspg_locks, pg_stat_activityperformance_schema.data_locks, SHOW ENGINE INNODB STATUSsys.dm_tran_locksV$LOCK, V$SESSIONnonedb.currentOp(), serverStatus().locks

SQL Server: lock escalation and table hints Important ​

SQL Server's locking guide states the escalation threshold: "Lock escalation is triggered when a Transact-SQL statement acquires at least 5,000 locks on a single reference of a table", and if escalation fails it "retries the lock escalation for each additional 1,250 locks acquired by the transaction". Successful escalation releases the row and page locks and keeps one table lock, which then blocks everyone. Table hints change locking per statement:

HintEffectTypical use and risk
NOLOCK (= READUNCOMMITTED)No shared locks for reads; still takes Sch-SDirty reads, rows read twice or missed during page splits; prefer RCSI
UPDLOCKTakes update (U) locks held to end of transaction"Read then update" without S→X conversion deadlocks
ROWLOCKAsk for row locks instead of page/tableHint only; escalation can still happen
PAGLOCK, TABLOCK, TABLOCKXCoarser locksBulk loads (TABLOCK enables minimal logging)
HOLDLOCK (= SERIALIZABLE)Holds S/key-range locks to endUpsert patterns with UPDLOCK, HOLDLOCK
READPASTSkips locked rowsQueue tables (SQL Server's SKIP LOCKED)
XLOCK, NOWAITExclusive lock; fail at onceRare

The manual adds that "All queries, including queries with READUNCOMMITTED and NOLOCK hints, acquire Sch-S (schema stability) locks during compilation and execution", so even NOLOCK waits behind a schema-modification (Sch-M) lock from ALTER TABLE. Lock timeouts raise error 1222; deadlock victims get error 1205 (the same number MySQL uses for lock wait timeout, a frequent source of confusion).

Oracle: row locks in the block, no escalation Good to know ​

"Unlike some databases, which use a lock manager to maintain a list of locks in memory, Oracle Database stores lock information in the data block that contains the locked row." — Oracle Database 19c Concepts, Data Concurrency and Consistency

The same chapter states "Oracle Database never escalates locks" and that a transaction "holds exclusive row locks for all rows inserted, updated, or deleted". A row lock is a TX lock; the table gets a TM (DML) lock in row-exclusive mode. Readers never wait. SELECT ... FOR UPDATE supports NOWAIT, WAIT n and SKIP LOCKED; failures are ORA-00054 and deadlocks ORA-00060. DDL_LOCK_TIMEOUT bounds DDL waits, and DBMS_LOCK provides named user locks.

MongoDB: multi-granularity intent locks and document-level concurrency Good to know ​

MongoDB's FAQ: it "uses multi-granularity locking that allows operations to lock at the global, database or collection level, and allows for individual storage engines to implement their own concurrency control below the collection level (e.g., at the document-level in WiredTiger)." Normal reads and writes take IS/IX on the database and collection and leave document conflicts to WiredTiger, which resolves them optimistically: one writer wins, the other retries internally, or, inside a multi-document transaction, fails with WriteConflict (a TransientTransactionError you retry). A transaction that cannot get a lock waits at most maxTransactionLockRequestTimeoutMillis (5 ms by default) and aborts. Exclusive collection or database locks appear for some DDL such as collMod and index-build phases. Inspect with db.currentOp() and db.serverStatus().locks.

Redis and SQLite: serial by design Good to know ​

Redis needs no data locks because "Redis uses a mostly single threaded design": one thread executes commands one at a time, so INCR, HINCRBY, LPUSH and a MULTI/EXEC block are atomic. Optimistic check-and-set uses WATCH. A "distributed lock" in Redis (SET key token NX PX ms, Redlock) is a lease with an expiry, not a database lock; see Redis. SQLite locks the whole database file: many readers, one writer (BEGIN IMMEDIATE takes the write lock up front); contention shows as SQLITE_BUSY, softened by PRAGMA busy_timeout; see SQLite in Depth. CockroachDB supports SELECT ... FOR UPDATE and FOR SHARE and uses them to queue conflicting writers early instead of aborting them, but contention still often ends in a 40001 retry; see Distributed SQL.

Mechanics ​

Where locks live Important ​

PostgreSQL keeps heavyweight locks in a shared-memory lock table. The manual: "Both advisory locks and regular locks are stored in a shared memory pool whose size is defined by the configuration variables max_locks_per_transaction and max_connections." Running out gives ERROR: out of shared memory with HINT: You might need to increase max_locks_per_transaction (SQLSTATE 53200), typically from a transaction touching thousands of partitions or a script taking many advisory locks. Weak relation locks are first recorded in a per-backend fast-path array (pg_locks.fastpath = true) without touching the shared table. Row locks are not in the lock table at all: they are written into the tuple (xmax, infomask bits, MultiXact for several lockers). That is why pg_locks "normally" does not show row locks; a waiter shows up waiting on the holder's transactionid and, while queued for a specific row, holding a tuple lock. InnoDB keeps its lock system in memory with one bitmap per locked page, which is why it does not need escalation.

Every knob Must-know ​

SettingProductDefaultMeaning
lock_timeoutPostgreSQL0 (off)Max wait for any single lock
statement_timeoutPostgreSQL0Max statement duration
idle_in_transaction_session_timeoutPostgreSQL0Kill sessions idle inside a transaction
transaction_timeoutPostgreSQL 17+0Max transaction duration
deadlock_timeoutPostgreSQL1sWait before checking for deadlock; also the log_lock_waits threshold
log_lock_waitsPostgreSQLon in the current (19) manualLog waits longer than deadlock_timeout
log_lock_failuresPostgreSQL 18+offLog NOWAIT lock failures
max_locks_per_transactionPostgreSQL64Sizes the shared lock table
innodb_lock_wait_timeoutMySQL50 (seconds)Row lock wait limit, session-settable
innodb_rollback_on_timeoutMySQLOFFON rolls back the whole transaction on 1205
innodb_deadlock_detectMySQLONOff relies on innodb_lock_wait_timeout
innodb_autoinc_lock_modeMySQL2AUTO-INC lock behaviour
innodb_status_output_locksMySQLOFFAdds lock detail to the InnoDB monitor
lock_wait_timeoutMySQL31536000 (1 year)Metadata lock wait limit
LOCK_TIMEOUTSQL Server-1 (forever)SET LOCK_TIMEOUT 2000 per session
LOCK_ESCALATIONSQL ServerTABLEPer table: TABLE, AUTO, DISABLE
DDL_LOCK_TIMEOUTOracle0DDL wait limit in seconds
busy_timeoutSQLite0How long to retry on SQLITE_BUSY
maxTransactionLockRequestTimeoutMillisMongoDB5Lock wait inside transactions

Error codes you will catch Must-know ​

CodeProductMeaningRetry?
55P03 lock_not_availablePostgreSQLlock_timeout fired or NOWAIT failedYes, with backoff, or answer "busy"
57014 query_canceledPostgreSQLstatement_timeout or pg_cancel_backendMaybe
40P01 deadlock_detectedPostgreSQLDeadlock victimYes, whole transaction (Deadlocks)
25P03 / 25P04PostgreSQLIdle-in-transaction / transaction timeout ended the sessionReconnect, fix the code
53200 out_of_memoryPostgreSQLLock table fullNo: raise max_locks_per_transaction or touch fewer objects
1205 ER_LOCK_WAIT_TIMEOUTMySQLRow or metadata lock wait timeout; only the statement is rolled back by defaultYes, but roll back the transaction yourself
3572 ER_LOCK_NOWAITMySQLNOWAIT could not lockAnswer "busy"
1213 ER_LOCK_DEADLOCKMySQLDeadlock, transaction rolled backYes
1222SQL ServerLOCK_TIMEOUT exceededYes
1205SQL ServerDeadlock victimYes
ORA-00054 / ORA-00060OracleResource busy (NOWAIT / timeout) / deadlockYes
SQLITE_BUSYSQLiteAnother connection holds the write lockYes (busy_timeout)
WriteConflict (112)MongoDBConcurrent write in a transactionYes (TransientTransactionError)

Seeing locks in PostgreSQL: pg_locks, pg_stat_activity, pg_blocking_pids, wait events Must-know ​

pg_locks has one row per lock held or awaited: locktype (relation, tuple, transactionid, virtualxid, advisory, object, page, extend...), relation, page, tuple, transactionid, pid, mode (e.g. AccessExclusiveLock), granted, fastpath and waitstart (when the wait began). The manual warns that joining it to itself to find blockers "is very difficult to get right in detail", which is why pg_blocking_pids(pid) exists; it reports both hard and soft blockers, returns 0 for a prepared transaction, and "Frequent calls to this function could have some impact on database performance". pg_stat_activity shows each session's state (active, idle, idle in transaction), xact_start, query_start, wait_event_type and wait_event.

wait_event_typeMeansTypical wait_event
LockWaiting for a heavyweight lockrelation, transactionid (a row held by another tx), tuple, advisory, extend, virtualxid
LWLockWaiting for a lightweight lock (latch)LockManager, BufferContent, WALWrite, ProcArray
BufferWaiting for a data buffer or pinBufferCleanup (VACUUM behind a pin), BufferExclusive
IOWaiting for diskDataFileRead, WALSync
ClientWaiting for the applicationClientRead (idle in transaction looks like this)
IPC, Timeout, Activity, ExtensionInter-process, sleeps, idle background loops, extension waitsParallelFinish, PgSleep...

log_lock_waits "Controls whether a log message is produced when a session waits longer than deadlock_timeout to acquire a lock"; the current manual lists the default as on. The log line names both sides:

text
LOG:  process 2202 still waiting for AccessExclusiveLock on relation 16391 of database 5 after 1000.123 ms
DETAIL:  Process holding the lock: 2101. Wait queue: 2202, 2303, 2304.
STATEMENT:  ALTER TABLE orders ADD COLUMN note text;

Seeing locks in InnoDB: data_locks, data_lock_waits, SHOW ENGINE INNODB STATUS Important ​

MySQL 8.0+ exposes locks in the Performance Schema: "The data_locks table shows data locks held and requested"; data_lock_waits pairs each blocked request with the blocking one; metadata_locks shows MDL; sys.innodb_lock_waits joins them into a readable view; information_schema.INNODB_TRX lists open transactions with trx_started and trx_mysql_thread_id. SHOW ENGINE INNODB STATUS has a TRANSACTIONS section (each transaction, LOCK WAIT state, the lock it waits for) and LATEST DETECTED DEADLOCK; set innodb_status_output_locks = ON to add the per-transaction lock list ("The Lock Monitor is the same as the Standard Monitor except that it includes additional lock information").

sql
-- MySQL 8.0+: who waits for whom
SELECT w.REQUESTING_ENGINE_TRANSACTION_ID AS waiting_trx,
       w.BLOCKING_ENGINE_TRANSACTION_ID   AS blocking_trx,
       r.LOCK_MODE AS wants, b.LOCK_MODE AS holds, b.OBJECT_NAME, b.INDEX_NAME, b.LOCK_DATA
FROM performance_schema.data_lock_waits w
JOIN performance_schema.data_locks r ON r.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID
JOIN performance_schema.data_locks b ON b.ENGINE_LOCK_ID = w.BLOCKING_ENGINE_LOCK_ID;
-- or simply: SELECT * FROM sys.innodb_lock_waits\G

Diagnosing lock waits, step by step ​

  1. Confirm it is a lock wait. SELECT pid, state, wait_event_type, wait_event, now()-query_start AS waiting, left(query,80) FROM pg_stat_activity WHERE wait_event_type = 'Lock'; If waits are LWLock or IO, it is not this page's problem.

  2. Find who blocks each waiter. SELECT pid, pg_blocking_pids(pid) AS blocked_by FROM pg_stat_activity WHERE wait_event_type = 'Lock';

  3. Find the root blocker: the session that blocks others but waits for nobody.

    sql
    SELECT a.pid, a.state, a.usename, a.application_name, a.client_addr,
           now() - a.xact_start AS xact_age, left(a.query, 80) AS last_query
    FROM pg_stat_activity a
    WHERE cardinality(pg_blocking_pids(a.pid)) = 0
      AND a.pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity
                    WHERE wait_event_type = 'Lock');
  4. Read the root. idle in transaction with an old xact_start means application code left a transaction open (a missing commit, a network call inside a transaction, a debugger). active with a long query means a heavy statement; a soft blocker (a waiting ALTER) means the queue problem.

  5. See the objects. SELECT locktype, relation::regclass, mode, granted, waitstart, pid FROM pg_locks WHERE pid = ANY(ARRAY[...]) ORDER BY granted DESC;

  6. Act. SELECT pg_cancel_backend(pid); cancels the current query (the transaction aborts if inside one); SELECT pg_terminate_backend(pid); ends the session and releases all its locks. Prefer cancelling the waiting DDL over killing the app's session.

  7. Prevent. Add lock_timeout to DDL, idle_in_transaction_session_timeout to app roles, keep transactions free of network calls, keep log_lock_waits on so the next incident leaves a log line.

On MySQL: sys.innodb_lock_waits (or the data_lock_waits join above), then INFORMATION_SCHEMA.INNODB_TRX for the blocker's age and thread, SHOW PROCESSLIST for Waiting for table metadata lock, performance_schema.metadata_locks for MDL holders, and KILL <thread_id>.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
DDL freezing a tablelock_timeout + retrySET LOCAL lock_timeout, backoff loopNever causes an outageMigration may need several attempts
Workers double-processing jobsFOR UPDATE SKIP LOCKEDClaim in a short transactionNo waiting, no duplicatesNot FIFO-strict; inconsistent view
Same cron on every replicaAdvisory lockpg_try_advisory_xact_lockNo extra infraOnly inside one database
Read-decide-write racesRow lock or atomic updateFOR NO KEY UPDATE, or one UPDATE ... WHERECorrect under concurrencyWaits on hot rows
Hot counterSharded or append-only counterN rows, sum on readN× throughputSlower reads, eventual totals
"Who is blocking?"Blocker reportpg_blocking_pids + pg_stat_activitySupported APISmall overhead per call

Migrations with lock_timeout and retry ​

The ALTER gives up after 2 seconds instead of freezing the table, then retries with growing backoff. SET LOCAL keeps the setting inside this transaction only.

sql
BEGIN;
SET LOCAL lock_timeout = '2s';
SET LOCAL statement_timeout = '60s';
ALTER TABLE orders ADD COLUMN IF NOT EXISTS shipped_at timestamptz;   -- metadata-only, fast once granted
COMMIT;
-- on ERROR 55P03: sleep 1s, 2s, 4s ... and run again

Go, before (no bound) and after:

go
// Package before shows two habits that look harmless in staging and hurt in
// production: DDL with no lock_timeout, and read-then-write with no row lock.
package before

import (
	"context"
	"database/sql"
)

// Migrate runs while traffic flows. ALTER TABLE needs ACCESS EXCLUSIVE, so if
// one long transaction is open on orders, this statement waits, and every
// query that arrives after it queues behind it. Nothing bounds the wait.
func Migrate(ctx context.Context, db *sql.DB) error {
	_, err := db.ExecContext(ctx, `ALTER TABLE orders ADD COLUMN shipped_at timestamptz`)
	return err
}

// Ship reads a row and writes it back in two separate statements. Two workers
// can both see status = 'paid' and both ship the same order.
func Ship(ctx context.Context, db *sql.DB, id int64) error {
	var status string
	if err := db.QueryRowContext(ctx, `SELECT status FROM orders WHERE id = $1`, id).Scan(&status); err != nil {
		return err
	}
	if status != "paid" {
		return nil
	}
	_, err := db.ExecContext(ctx, `UPDATE orders SET status = 'shipped' WHERE id = $1`, id)
	return err
}

// NightlyReport has no guard: every replica of the service runs it at once.
func NightlyReport(ctx context.Context, db *sql.DB) error {
	_, err := db.ExecContext(ctx, `INSERT INTO daily_report SELECT * FROM build_report()`)
	return err
}
go
// Package after bounds every wait for a lock and takes the weakest lock that
// is still correct.
package after

import (
	"context"
	"database/sql"
	"errors"
	"time"
)

// lockNotAvailable is SQLSTATE 55P03, raised when lock_timeout expires.
const lockNotAvailable = "55P03"

// sqlStater matches pgx's *pgconn.PgError and lib/pq's *pq.Error without
// importing either driver.
type sqlStater interface{ SQLState() string }

func isLockTimeout(err error) bool {
	var s sqlStater
	return errors.As(err, &s) && s.SQLState() == lockNotAvailable
}

// Migrate gives up after 2s of waiting instead of freezing the table, then
// retries with backoff. SET LOCAL lasts only for this transaction.
func Migrate(ctx context.Context, db *sql.DB, attempts int) error {
	var err error
	for i := 0; i < attempts; i++ {
		if err = migrateOnce(ctx, db); err == nil || !isLockTimeout(err) {
			return err
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Duration(i+1) * time.Second):
		}
	}
	return err
}

func migrateOnce(ctx context.Context, db *sql.DB) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback() //nolint:errcheck // no-op after Commit

	if _, err := tx.ExecContext(ctx, `SET LOCAL lock_timeout = '2s'`); err != nil {
		return err
	}
	if _, err := tx.ExecContext(ctx, `ALTER TABLE orders ADD COLUMN IF NOT EXISTS shipped_at timestamptz`); err != nil {
		return err
	}
	return tx.Commit()
}

Laravel: in a migration, DB::statement("SET lock_timeout = '2s'") at the top of up() (migrations run inside a transaction on PostgreSQL when the grammar supports it, so SET LOCAL also works), and let your deploy script retry php artisan migrate on 55P03. The service-side retry wrapper for the same SQLSTATE is in After.php below.

Job queue with SKIP LOCKED ​

Each worker grabs different rows; nobody waits for another worker. The claim commits at once, the job runs outside the transaction, and a reaper resets rows stuck in running past a deadline.

go
package after

import (
	"context"
	"database/sql"
)

// ClaimJobs hands each worker a different batch of pending jobs without
// making workers wait for each other. Rows another worker has locked are
// skipped, not waited for. The claim commits at once, so the row lock is
// held for milliseconds; the job itself runs outside the transaction.
func ClaimJobs(ctx context.Context, db *sql.DB, limit int) ([]int64, error) {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return nil, err
	}
	defer tx.Rollback() //nolint:errcheck // no-op after Commit

	rows, err := tx.QueryContext(ctx, `
		UPDATE jobs SET status = 'running', locked_at = now(), attempts = attempts + 1
		WHERE id IN (
			SELECT id FROM jobs
			WHERE status = 'pending' AND run_at <= now()
			ORDER BY run_at
			LIMIT $1
			FOR UPDATE SKIP LOCKED
		)
		RETURNING id`, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var ids []int64
	for rows.Next() {
		var id int64
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		ids = append(ids, id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return ids, tx.Commit()
}
php
<?php

namespace App\Services;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class ClaimJobs
{
    /**
     * Give this worker up to $limit pending jobs that no other worker holds.
     * lock() takes a raw locking clause; SKIP LOCKED works on PostgreSQL
     * and MySQL 8.0+. The transaction ends right after the claim.
     */
    public function claim(int $limit = 10): Collection
    {
        return DB::transaction(function () use ($limit) {
            $jobs = DB::table('jobs_queue')
                ->where('status', 'pending')
                ->where('run_at', '<=', now())
                ->orderBy('run_at')
                ->limit($limit)
                ->lock('for update skip locked')
                ->get();

            if ($jobs->isNotEmpty()) {
                DB::table('jobs_queue')
                    ->whereIn('id', $jobs->pluck('id'))
                    ->update(['status' => 'running', 'locked_at' => now()]);
            }

            return $jobs;
        });
    }
}

Laravel's own database queue driver pops jobs with FOR UPDATE SKIP LOCKED where the server supports it; see Laravel Queue Internals. An index on (status, run_at) keeps the inner SELECT from scanning (and, on InnoDB, from locking) the whole table.

Singleton job with an advisory lock ​

Go uses a session lock on a pinned *sql.Conn, because the work spans statements outside one transaction; the unlock uses context.WithoutCancel so a cancelled job still releases.

go
package after

import (
	"context"
	"database/sql"
)

// reportLockKey is an arbitrary application-chosen number; pick one per job.
const reportLockKey int64 = 727001

// NightlyReport runs on one replica only. A session-level advisory lock
// belongs to a connection, so the lock, the work and the unlock must all use
// the same *sql.Conn, not the pool.
func NightlyReport(ctx context.Context, db *sql.DB) (ran bool, err error) {
	conn, err := db.Conn(ctx)
	if err != nil {
		return false, err
	}
	defer conn.Close()

	var got bool
	if err := conn.QueryRowContext(ctx, `SELECT pg_try_advisory_lock($1)`, reportLockKey).Scan(&got); err != nil {
		return false, err
	}
	if !got {
		return false, nil // another replica holds it
	}
	defer func() {
		// Use a fresh context so a cancelled ctx still releases the lock.
		_, _ = conn.ExecContext(context.WithoutCancel(ctx), `SELECT pg_advisory_unlock($1)`, reportLockKey)
	}()

	_, err = conn.ExecContext(ctx, `INSERT INTO daily_report SELECT * FROM build_report()`)
	return err == nil, err
}

Laravel uses the transaction-level variant, which is safe behind a transaction-mode pooler:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class NightlyReport extends Command
{
    protected $signature = 'report:nightly';

    protected $description = 'Build the daily report on exactly one app server';

    // Any 64-bit number the whole application agrees on for this job.
    private const LOCK_KEY = 727001;

    public function handle(): int
    {
        // Transaction-level advisory lock: released automatically at COMMIT
        // or ROLLBACK, so it is safe behind a transaction-mode pooler.
        $ran = DB::transaction(function () {
            $got = DB::selectOne('SELECT pg_try_advisory_xact_lock(?) AS got', [self::LOCK_KEY])->got;

            if (! $got) {
                return false; // another server is already running it
            }

            DB::statement('INSERT INTO daily_report SELECT * FROM build_report()');

            return true;
        });

        $this->info($ran ? 'Report built.' : 'Skipped: another instance holds the lock.');

        return self::SUCCESS;
    }
}

Laravel's scheduler offers ->withoutOverlapping() and ->onOneServer(), which use cache atomic locks (Cache::lock) instead of the database; with a shared Redis or database cache they give the same guarantee across servers.

Hot-row counter redesign ​

sql
CREATE TABLE post_like_shards (
  post_id bigint NOT NULL,
  shard   smallint NOT NULL,
  n       bigint NOT NULL DEFAULT 0,
  PRIMARY KEY (post_id, shard)
);
-- write: random shard 0..15, one atomic upsert
INSERT INTO post_like_shards (post_id, shard, n) VALUES (42, 7, 1)
ON CONFLICT (post_id, shard) DO UPDATE SET n = post_like_shards.n + EXCLUDED.n;
-- read: no locks
SELECT sum(n) FROM post_like_shards WHERE post_id = 42;
go
package after

import (
	"context"
	"database/sql"
	"math/rand/v2"
)

// counterShards spreads one logical counter over N rows so that concurrent
// increments rarely touch the same row and rarely queue on its row lock.
const counterShards = 16

// IncrementLikes adds delta to a random shard. Each statement is a single
// atomic UPDATE (an upsert), so no read-modify-write race exists.
func IncrementLikes(ctx context.Context, db *sql.DB, postID int64, delta int) error {
	shard := rand.IntN(counterShards)
	_, err := db.ExecContext(ctx, `
		INSERT INTO post_like_shards (post_id, shard, n) VALUES ($1, $2, $3)
		ON CONFLICT (post_id, shard) DO UPDATE SET n = post_like_shards.n + EXCLUDED.n`,
		postID, shard, delta)
	return err
}

// Likes sums the shards. A plain SELECT takes no row locks, so readers never
// wait for the incrementers.
func Likes(ctx context.Context, db *sql.DB, postID int64) (int64, error) {
	var n int64
	err := db.QueryRowContext(ctx,
		`SELECT COALESCE(sum(n), 0) FROM post_like_shards WHERE post_id = $1`, postID).Scan(&n)
	return n, err
}
php
<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;

class LikeCounter
{
    private const SHARDS = 16;

    /** Spread increments over 16 rows so they rarely wait on one row lock. */
    public function increment(int $postId, int $delta = 1): void
    {
        DB::table('post_like_shards')->upsert(
            [['post_id' => $postId, 'shard' => random_int(0, self::SHARDS - 1), 'n' => $delta]],
            ['post_id', 'shard'],
            ['n' => DB::raw('post_like_shards.n + excluded.n')]
        );
    }

    /** Plain reads take no row locks and never wait for incrementers. */
    public function count(int $postId): int
    {
        return (int) DB::table('post_like_shards')->where('post_id', $postId)->sum('n');
    }
}

Read-decide-write on one row ​

go
package after

import (
	"context"
	"database/sql"
	"errors"
)

// Ship locks the row before deciding. FOR NO KEY UPDATE is enough because the
// key is not changing, and it does not block foreign-key checks, which take
// FOR KEY SHARE on the same row.
func Ship(ctx context.Context, db *sql.DB, id int64) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback() //nolint:errcheck // no-op after Commit

	var status string
	err = tx.QueryRowContext(ctx,
		`SELECT status FROM orders WHERE id = $1 FOR NO KEY UPDATE`, id).Scan(&status)
	if errors.Is(err, sql.ErrNoRows) {
		return nil
	}
	if err != nil {
		return err
	}
	if status != "paid" {
		return nil
	}
	if _, err := tx.ExecContext(ctx, `UPDATE orders SET status = 'shipped' WHERE id = $1`, id); err != nil {
		return err
	}
	return tx.Commit()
}

Laravel, before and after (lockForUpdate, sharedLock, SET LOCAL lock_timeout, retry on 55P03):

php
<?php

namespace App\Services;

use App\Models\Order;

class ShippingService
{
    // Read, decide, write: three steps with nothing holding the row between
    // them. Two queue workers can both pass the status check.
    public function ship(int $orderId): void
    {
        $order = Order::findOrFail($orderId);

        if ($order->status !== 'paid') {
            return;
        }

        $order->update(['status' => 'shipped']);
    }
}
php
<?php

namespace App\Services;

use App\Models\Order;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

class ShippingService
{
    public function ship(int $orderId): void
    {
        DB::transaction(function () use ($orderId) {
            // Never wait longer than 2s for any lock in this transaction.
            DB::statement("SET LOCAL lock_timeout = '2s'");

            // FOR UPDATE: nobody else can lock, change or delete this row
            // until we commit.
            $order = Order::query()->lockForUpdate()->findOrFail($orderId);

            if ($order->status !== 'paid') {
                return;
            }

            // FOR SHARE: the customer row may be read by others but not
            // changed while we use it. Writers wait, readers do not.
            $customer = DB::table('customers')
                ->where('id', $order->customer_id)
                ->sharedLock()
                ->first();

            $order->update([
                'status' => 'shipped',
                'ship_to' => $customer->address,
            ]);
        });
    }

    /** Run a callback, retrying when lock_timeout fires (SQLSTATE 55P03). */
    public function shipWithRetry(int $orderId, int $attempts = 3): void
    {
        for ($i = 1; ; $i++) {
            try {
                $this->ship($orderId);

                return;
            } catch (QueryException $e) {
                if ($i >= $attempts || $e->getCode() !== '55P03') {
                    throw $e;
                }
                usleep($i * 200_000);
            }
        }
    }
}

Finding who blocks whom ​

An Artisan command that lists blocked sessions and their blockers:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ListBlocked extends Command
{
    protected $signature = 'db:blocked';

    protected $description = 'Show sessions waiting on a lock and the sessions blocking them';

    public function handle(): int
    {
        // pg_blocking_pids() is the supported way to find the blockers;
        // joining pg_locks to itself has to re-implement the conflict table.
        $rows = DB::select(<<<'SQL'
            SELECT
                waiting.pid                          AS blocked_pid,
                waiting.wait_event_type              AS wait_type,
                now() - waiting.query_start          AS waiting_for,
                left(waiting.query, 60)              AS blocked_query,
                blocker.pid                          AS blocking_pid,
                blocker.state                        AS blocker_state,
                now() - blocker.xact_start           AS blocker_xact_age,
                left(blocker.query, 60)              AS blocker_query
            FROM pg_stat_activity AS waiting
            JOIN LATERAL unnest(pg_blocking_pids(waiting.pid)) AS b(pid) ON true
            JOIN pg_stat_activity AS blocker ON blocker.pid = b.pid
            WHERE waiting.wait_event_type = 'Lock'
            ORDER BY waiting.query_start
        SQL);

        if ($rows === []) {
            $this->info('No blocked sessions.');

            return self::SUCCESS;
        }

        // Which lock objects are not yet granted, straight from pg_locks.
        $pending = DB::select(
            'SELECT pid, locktype, mode, relation::regclass::text AS relation
             FROM pg_locks WHERE NOT granted'
        );

        $this->table(
            ['blocked', 'wait', 'for', 'query', 'blocker', 'state', 'xact age', 'blocker query'],
            array_map(fn ($r) => (array) $r, $rows)
        );
        $this->line(count($pending).' ungranted lock request(s) in pg_locks.');

        return self::FAILURE;
    }
}

The Go and Laravel angle ​

The database/sql documentation explains why the singleton pins a connection: "Once DB.Begin is called, the returned Tx is bound to a single connection", and a *sql.DB is a pool, so two calls on it may run in different sessions. Row locks and SET LOCAL live inside a Tx; session-level advisory locks need a *sql.Conn. The migration code detects 55P03 through a small SQLState() interface that both pgx (*pgconn.PgError) and lib/pq errors satisfy, so it needs no driver import. Always pass a context with a deadline: cancelling it makes the driver send a cancel request, which ends a lock wait from the client side.

Laravel's query builder documents sharedLock() ("prevents the selected rows from being modified until your transaction is committed") and lockForUpdate() (prevents rows "from being modified or from being selected with another shared lock"), and recommends wrapping pessimistic locks in a transaction. lock() accepts a raw clause ('for update skip locked', 'for no key update'). The second argument of DB::transaction retries only on deadlocks and concurrency errors it detects, not on lock timeouts, hence the explicit wrapper in After.php.

Choosing ​

SituationRecommended lockExtra techniqueReason
Update one row after reading it (status machine)FOR NO KEY UPDATE (PostgreSQL), FOR UPDATE (InnoDB)Short transaction, lock_timeoutWeakest correct lock; FK inserts not blocked
Simple counter or stock decrementNo explicit lockUPDATE ... SET x = x - 1 WHERE id = ? AND x > 0Atomic statement, shortest lock
Very hot counterNone on one rowSharded counter, Redis INCR, append + aggregateRemoves the serialisation point
Parent must not disappear while I insert childrenFOR KEY SHARE / FKLet the FK do itWeakest mode that protects the key
Work queueFOR UPDATE SKIP LOCKED (READPAST on SQL Server)Index on (status, run_at), reaperNo waiting between workers
User-facing "is this seat free"FOR UPDATE NOWAITReturn 409 on 55P03/3572Fail fast instead of hanging a request
Schema change on a hot tableWhatever the DDL needslock_timeout + retry, CONCURRENTLY, NOT VALIDAvoids the lock queue outage
One job instance across replicaspg_try_advisory_xact_lockOr Cache::lock, onOneServer()No extra table, auto-release
Bulk rewrite of a tableLOCK TABLE ... IN EXCLUSIVE MODE or batchesBatches of 1,000–5,000 rowsAvoid escalation and long row locks
Reports on OLTP dataNoneMVCC snapshot or a replicaReaders should never lock
Range must stay empty (no phantom inserts)InnoDB next-key (Repeatable Read) or PostgreSQL Serializable / exclusion constraintUnique or exclusion constraintConstraints beat range locks

In architecture: from a single process to a distributed system ​

Locks are a single-database tool. Their guarantees end at the database's edge, and every architecture step changes what you can use instead.

Monolith: one process, one database ​

Everything on this page applies directly. The simplest correct use: one request = one short transaction; lock rows you will change with FOR NO KEY UPDATE; never make HTTP calls while holding a row lock; DDL with lock_timeout. Example: a Laravel shop where CheckoutController runs DB::transaction with lockForUpdate() on the cart's product rows, sorted by id to avoid deadlocks, then commits before calling the payment gateway (payment result recorded in a second transaction). Background jobs use the database queue driver, which already uses SKIP LOCKED.

Modular monolith and multiple databases ​

Modules that share one database can still share a transaction and its locks, but each module should lock only its own tables: if billing locks orders rows, the modules are coupled through lock waits and lock order. When a module moves to its own schema or database, cross-module locks disappear; use advisory lock keys with a module prefix (hashtext('billing:invoice:' || id)) for coordination that stays inside one database, and messages for anything that crosses databases. Example: inventory reserves stock with a row lock in its own schema and publishes StockReserved via an outbox, instead of orders locking inventory.products directly.

Microservices: no locks across service boundaries ​

A row lock cannot be held across a network call to another service without turning that service's latency into your lock hold time, and it cannot span two databases at all. What survives: each service locks its own rows locally; cross-service invariants use sagas with semantic locks (a PENDING status that other operations respect, see Saga Pattern), idempotency keys, and reservations with expiry. Example flow: Order service inserts order PENDING → publishes OrderCreated → Inventory service runs UPDATE stock SET reserved = reserved + 1 WHERE sku = ? AND available - reserved >= 1 (one atomic statement, row lock held for microseconds) → publishes StockReserved → Payment charges → Order sets CONFIRMED; a timeout releases the reservation. Leader election or singletons across services use a lease (etcd, ZooKeeper, Consul, a Redis SET NX PX with fencing tokens), not a database lock held for hours.

Distributed data: replicas, caches, sharded and distributed SQL ​

Locks are taken on the primary only. A PostgreSQL hot standby cannot take FOR UPDATE (it is read-only), and an ACCESS EXCLUSIVE lock on the primary is replayed on standbys, where it can cancel long standby queries ("canceling statement due to conflict with recovery"). A cache in front of the database is outside every lock: a value read from Redis may be stale while a row lock is held. Sharded systems (Citus, Vitess) lock per shard; a transaction touching two shards takes locks on both and needs 2PC to commit atomically. Distributed SQL (CockroachDB, Spanner, YugabyteDB) keeps lock tables per range, uses FOR UPDATE to queue writers, and resolves most contention with transaction restarts (40001); clock uncertainty adds waits too. See Distributed SQL, Consensus & 2PC and Replication.

Scaling path: 1×, 10×, 100× ​

At 1× row locks are invisible; the first incident is usually a migration behind an idle transaction, fixed with lock_timeout and idle_in_transaction_session_timeout. At 10× hot rows appear (counters, popular SKUs, per-tenant summaries): shard counters, move totals to append-and-aggregate, shorten transactions, add a pooler and watch LWLock waits on LockManager and ProcArray. At 100× you partition by key so hot data spreads, move queues off the primary table (or keep SKIP LOCKED with partitioned queue tables), push singletons to a lease service, and accept that cross-entity invariants become asynchronous (reservations, sagas) instead of locks.

Lab ​

Two or three terminals per experiment. Expected output is in comments.

Setup.

bash
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker run -d --name my -e MYSQL_ROOT_PASSWORD=my -e MYSQL_DATABASE=lab -p 3306:3306 mysql:8.4
# PostgreSQL terminals: docker exec -it pg psql -U postgres
# MySQL terminals:      docker exec -it my mysql -uroot -pmy lab
sql
-- PostgreSQL
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100), (2, 100);
CREATE TABLE jobs (id int PRIMARY KEY, status text NOT NULL DEFAULT 'pending');
INSERT INTO jobs SELECT g, 'pending' FROM generate_series(1, 4) g;

-- MySQL (the manual's own example)
CREATE TABLE child (id int NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB;
INSERT INTO child (id) VALUES (90), (102);

Experiment 1: a FOR UPDATE wait (PostgreSQL).

text
     A                                                   B
1    BEGIN;                                              BEGIN;
2    SELECT * FROM accounts WHERE id=1 FOR UPDATE;       -- 1 | 100
3                                                        SELECT * FROM accounts WHERE id=1;             -- 1 | 100, no wait (MVCC)
4                                                        SELECT * FROM accounts WHERE id=1 FOR UPDATE;  -- hangs
5    UPDATE accounts SET balance=90 WHERE id=1; COMMIT;
6                                                        -- returns 1 | 90 (re-reads the new version at Read Committed)
7                                                        COMMIT;

Experiment 2: lock_timeout and NOWAIT fail instead of hanging (PostgreSQL).

text
     A                                                   B
1    BEGIN; UPDATE accounts SET balance=0 WHERE id=2;
2                                                        SET lock_timeout = '1s';
3                                                        UPDATE accounts SET balance=1 WHERE id=2;
                                                         -- after 1 s: ERROR:  canceling statement due to lock timeout
4                                                        SELECT * FROM accounts WHERE id=2 FOR UPDATE NOWAIT;
                                                         -- ERROR:  could not obtain lock on row in relation "accounts"
5    ROLLBACK;

Experiment 3: the lock queue and pg_blocking_pids (PostgreSQL, four terminals).

text
     A                          B                                       C                          D (observer)
1    BEGIN;
2    SELECT count(*) FROM accounts;   -- holds ACCESS SHARE, stays open
3                               ALTER TABLE accounts ADD COLUMN note text;   -- hangs
4                                                                       SELECT * FROM accounts;   -- hangs too!
5                                                                                                  SELECT pid, pg_blocking_pids(pid), wait_event_type, wait_event, left(query,40)
                                                                                                   FROM pg_stat_activity WHERE wait_event_type = 'Lock';
     -- B's row: blocked by {A}  (hard block, wait_event = relation)
     -- C's row: blocked by {B}  (soft block: C is compatible with A but queued behind B)
6    COMMIT;                    -- ALTER completes                      -- SELECT completes

Repeat with SET lock_timeout = '2s'; before the ALTER in B: after 2 s B fails with 55P03 and C runs immediately.

Experiment 4: a gap lock blocks an insert (MySQL InnoDB).

text
     A                                                   B
1    START TRANSACTION;                                  SET SESSION innodb_lock_wait_timeout = 5;
2    SELECT * FROM child WHERE id > 100 FOR UPDATE;      -- 102
3                                                        START TRANSACTION;
4                                                        INSERT INTO child (id) VALUES (101);   -- hangs
5    SELECT INDEX_NAME, LOCK_TYPE, LOCK_MODE, LOCK_STATUS, LOCK_DATA FROM performance_schema.data_locks;
     -- TABLE  IX                          GRANTED
     -- PRIMARY X                          GRANTED  supremum pseudo-record
     -- PRIMARY X                          GRANTED  102
     -- PRIMARY X,GAP,INSERT_INTENTION     WAITING  102
6                                                        -- after 5 s: ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
7    ROLLBACK;                                           ROLLBACK;

Run it again with SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; in A before step 1: step 4 succeeds at once, because gap locking is disabled for searches at Read Committed.

Experiment 5: advisory lock mutual exclusion (PostgreSQL).

text
     A                                                   B
1    SELECT pg_try_advisory_lock(42);   -- t
2                                                        SELECT pg_try_advisory_lock(42);   -- f
3                                                        SELECT pg_advisory_lock(42);       -- hangs (wait_event = advisory)
4    SELECT locktype, objid, mode, granted FROM pg_locks WHERE locktype = 'advisory';
     -- advisory | 42 | ExclusiveLock | t
     -- advisory | 42 | ExclusiveLock | f
5    SELECT pg_advisory_unlock(42);     -- t
6                                                        -- returns; B holds it now
7                                                        BEGIN; SELECT pg_advisory_xact_lock(7); COMMIT;   -- released by COMMIT, no unlock needed

Experiment 6: SKIP LOCKED workers (PostgreSQL).

text
     A                                                   B
1    BEGIN;                                              BEGIN;
2    SELECT id FROM jobs WHERE status='pending' ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED;   -- 1, 2
3                                                        SELECT id FROM jobs WHERE status='pending' ORDER BY id LIMIT 2 FOR UPDATE SKIP LOCKED;  -- 3, 4 at once
4                                                        -- without SKIP LOCKED, B would wait for A and then get 1, 2 again
5    COMMIT;                                             COMMIT;

Common misconceptions ​

BeliefReality
"ROW EXCLUSIVE locks rows"It is a table-level mode taken by writers; row locks are stored in the tuple
"A plain SELECT never waits"It waits for ACCESS EXCLUSIVE, held or queued
"MVCC means no locks"Writers lock rows, DDL locks tables, locking reads lock rows
"Lock waits time out by themselves"PostgreSQL waits forever by default; MySQL metadata locks wait a year
"FOR UPDATE is the default row lock to use"FOR NO KEY UPDATE is what UPDATE takes and does not block FK checks
"statement_timeout protects against lock waits"It also kills slow queries; use lock_timeout for waits
"Advisory locks work with any pool"Session locks belong to a connection; use the xact variants or pin a connection
"NOLOCK makes SQL Server reads safe and fast"It allows dirty, missing and duplicated rows; RCSI is the safe fix
"ROWLOCK prevents escalation"It is a hint; escalation at 5,000 locks can still happen
"InnoDB FOR UPDATE on one value locks one row"On a non-unique or missing index it locks gaps and scanned rows
"An atomic UPDATE x = x + 1 has no contention"No race, but it queues on the row lock
"pg_locks shows all row locks"Row locks live on disk; waiters appear as transactionid/tuple waits
"Killing the waiting migration loses data"Cancelling a waiting DDL is safe; it never started changing anything

Cheat sheet ​

TopicRemember
Table lock that blocks SELECTOnly ACCESS EXCLUSIVE (DROP, TRUNCATE, VACUUM FULL, most ALTER)
CREATE INDEXSHARE blocks writes; CONCURRENTLY does not
Row lock for updatesFOR NO KEY UPDATE unless the key changes
Lock queueA waiting request blocks later conflicting requests (soft block)
DDLSET LOCAL lock_timeout = '2s' + retry
Fail fastNOWAIT (55P03 / 3572 / ORA-00054)
QueuesFOR UPDATE SKIP LOCKED (SQL Server READPAST)
Singletonspg_try_advisory_xact_lock(key)
Who blockspg_blocking_pids(pid) + pg_stat_activity
Lock logginglog_lock_waits, threshold deadlock_timeout
InnoDB lock waitinnodb_lock_wait_timeout 50 s, error 1205, statement-only rollback
InnoDB rangesNext-key = record + gap before; disabled for searches at Read Committed
InnoDB viewperformance_schema.data_locks / data_lock_waits, SHOW ENGINE INNODB STATUS
SQL ServerEscalation at 5,000 locks; UPDLOCK for read-then-update
Hot rowsThroughput ≈ 1 / lock hold time; shard or append

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Which PostgreSQL table lock modes does a plain SELECT conflict with? Good to know ​

Answer

Answer: Only ACCESS EXCLUSIVE. But it can also queue behind a waiting ACCESS EXCLUSIVE request (soft block).

2 — Why does CREATE INDEX block inserts while CREATE INDEX CONCURRENTLY does not? Important ​

Answer

Answer: The first takes SHARE, which conflicts with ROW EXCLUSIVE taken by writers; the second takes SHARE UPDATE EXCLUSIVE, which does not.

3 — A child-table insert hangs while a worker processes the parent order. What lock is probably involved and what change fixes it? Important ​

Answer

Answer: The worker holds FOR UPDATE on the parent; the FK check needs FOR KEY SHARE, which conflicts only with FOR UPDATE. Use FOR NO KEY UPDATE.

4 — What is the difference between lock_timeout and statement_timeout? Must-know ​

Answer

Answer: lock_timeout bounds each wait for a lock; statement_timeout bounds the whole statement including execution. Setting lock_timeout at or above statement_timeout is pointless.

5 — Why can pg_try_advisory_lock leak a lock when called through *sql.DB? Good to know ​

Answer

Answer: A session-level lock belongs to one connection; the pool may run the unlock on a different connection, which does nothing. Use *sql.Conn or the transaction-level function.

6 — In InnoDB at Repeatable Read, an index on c1 holds 10, 11, 13, 20. WHERE c1 = 11 FOR UPDATE on a non-unique index: can another session insert 12? 15? Good to know ​

Answer

Answer: 12 waits (gap (11,13) is locked; its insert intention lock conflicts). 15 proceeds.

7 — What does X,GAP,INSERT_INTENTION with LOCK_STATUS = WAITING in performance_schema.data_locks tell you? Good to know ​

Answer

Answer: An INSERT is waiting to insert into a gap that another transaction holds a gap or next-key lock on.

8 — Why do locks differ from latches in how you diagnose them? Important ​

Answer

Answer: Locks appear in pg_locks and last to transaction end; latches (LWLocks, spinlocks, buffer pins) last microseconds and appear only as LWLock/Buffer wait events.

9 — A MySQL transaction gets error 1205. Has the transaction been rolled back? Important ​

Answer

Answer: By default only the statement is rolled back (innodb_rollback_on_timeout=OFF); the application must roll back or retry the transaction itself.

10 — Why is NOLOCK not a fix for blocking in SQL Server? Must-know ​

Answer

Answer: It reads uncommitted data and can miss or double-read rows; read committed snapshot isolation removes reader/writer blocking without those anomalies.

11 — A like counter row limits throughput to about 200 updates a second. Name two redesigns. Must-know ​

Answer

Answer: A sharded counter (N rows, sum on read), append-and-aggregate, or an in-memory atomic such as Redis INCR.

Glossary ​

TermMeaning
Concurrency controlMechanisms that make concurrent transactions behave correctly
Pessimistic lockingPrevent conflicts by locking before acting
Optimistic concurrency controlDetect conflicts at write/commit time and retry
LockTransaction-duration guard on data or objects, with modes and deadlock detection
LatchShort guard on in-memory structures; no deadlock detection
Lightweight lock (LWLock)PostgreSQL latch for shared-memory structures, shared/exclusive
SpinlockBusy-wait latch held for a few instructions
Buffer pinReference count keeping a buffer page in memory while read
Heavyweight lockPostgreSQL's regular lock manager lock, shown in pg_locks
Shared lock (S)Many holders may read
Exclusive lock (X)One holder may write
Update lock (U)SQL Server mode for read-then-update, avoids conversion deadlocks
Intention lock (IS/IX)Table-level marker that row locks are held or wanted inside
Two-phase locking (2PL)Acquire all locks before releasing any
Strict 2PLHold exclusive locks until commit or abort
Lock granularitySize of the locked unit: row, page, table, database
Page-level lockLock on one data page; in PostgreSQL a short buffer-content lock
Lock escalationReplacing many fine locks with one coarse lock (SQL Server)
Lock conversion / lock upgradeChanging a held lock to a stronger mode (S→X)
ACCESS SHAREPostgreSQL table mode for SELECT
ROW SHAREPostgreSQL table mode for SELECT ... FOR ...
ROW EXCLUSIVEPostgreSQL table mode for DML
SHARE UPDATE EXCLUSIVEPostgreSQL mode for VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY
SHAREPostgreSQL mode for CREATE INDEX; blocks writes
SHARE ROW EXCLUSIVEPostgreSQL self-conflicting mode for CREATE TRIGGER, ADD FOREIGN KEY
EXCLUSIVEPostgreSQL mode allowing only reads
ACCESS EXCLUSIVEPostgreSQL mode that blocks everything
LOCK TABLEExplicit table lock statement; default ACCESS EXCLUSIVE
FOR UPDATEStrongest row lock
FOR NO KEY UPDATERow lock for non-key updates; compatible with FOR KEY SHARE
FOR SHAREShared row lock blocking updates and deletes
FOR KEY SHAREWeakest row lock, used by FK checks
MultiXactPostgreSQL structure recording several lockers of one row
Lock queueOrdered list of waiters for a lock
Hard block / soft blockBlocked by a holder / blocked by an earlier waiter
lock_timeoutPostgreSQL limit on each lock wait (55P03)
statement_timeoutPostgreSQL limit on statement duration (57014)
idle_in_transaction_session_timeoutEnds sessions idle inside a transaction
NOWAITFail at once if a lock is not available
SKIP LOCKEDSkip rows that cannot be locked at once
READPASTSQL Server hint equivalent to SKIP LOCKED
Advisory lockApplication-defined lock on a number
pg_try_advisory_lockNon-blocking session advisory lock
pg_advisory_xact_lockTransaction-scoped advisory lock
pg_locksPostgreSQL view of held and awaited locks
pg_stat_activityPostgreSQL view of sessions, states and wait events
pg_blocking_pidsFunction returning the pids blocking a session
wait_event_typeCategory of what a backend waits on: Lock, LWLock, Buffer, IO, Client...
log_lock_waitsLogs waits longer than deadlock_timeout
deadlock_timeoutWait before deadlock check; lock-wait log threshold
DeadlockCycle of waits resolved by aborting a victim
fast-path lockWeak relation lock recorded per backend, pg_locks.fastpath
max_locks_per_transactionSizes PostgreSQL's shared lock table
Record lockInnoDB lock on one index record
Gap lockInnoDB lock on the gap between index records; blocks inserts only
Next-key lockInnoDB record lock plus the gap before it
SupremumInnoDB pseudo-record above the largest index value
Insert intention lockInnoDB gap lock taken by INSERT before inserting
AUTO-INC lockInnoDB table-level lock for auto-increment values
innodb_autoinc_lock_mode0 traditional, 1 consecutive, 2 interleaved (default)
innodb_lock_wait_timeoutInnoDB row lock wait limit (50 s, error 1205)
SHOW ENGINE INNODB STATUSInnoDB monitor output with TRANSACTIONS and deadlock sections
performance_schema.data_locksMySQL table of held and requested data locks
data_lock_waitsMySQL table pairing blocked and blocking lock requests
Metadata lock (MDL)MySQL lock on table definitions; DDL waits on it
NOLOCKSQL Server hint for dirty reads without shared locks
UPDLOCKSQL Server hint taking update locks held to transaction end
ROWLOCKSQL Server hint requesting row-level locks
Sch-S / Sch-MSQL Server schema stability / modification locks
TX / TM lockOracle row-transaction lock / table DML lock
WiredTigerMongoDB storage engine with document-level concurrency
WriteConflictMongoDB error when concurrent transactions write the same document
Single-threaded executionRedis runs commands one at a time, so each is atomic
MVCCMultiple row versions so readers do not block writers
Hot rowA row most transactions must lock, capping throughput
Lock-free counterCounter design that avoids one contended row (shards, append, atomics)
Lock contentionTime transactions spend waiting for locks held by others

References ​

Built by Morteza Negahi