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 for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why locks exist and the trade-off | Why concurrency control exists |
| 2PL, strict 2PL, granularity, intention locks: where the words come from | Where it comes from |
| One concept per block with a timeline and a fix | The concept catalogue |
| The eight PostgreSQL table modes and which statement takes which | PostgreSQL table-level lock modes |
FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE | PostgreSQL row-level locks |
Why a whole table freezes behind one ALTER TABLE | The lock queue |
| Record, gap, next-key, insert intention, AUTO-INC | InnoDB locks |
| SQL Server escalation and hints, Oracle, SQLite, MongoDB, Redis | Per-engine behaviour |
Knobs, error codes, pg_locks, wait events, SHOW ENGINE INNODB STATUS | Mechanics |
| A stuck system, step by step | Diagnosing lock waits |
| Migrations, job queues, singleton jobs, hot counters in SQL + Go + Laravel | Solving the classic problems |
| Which lock for which situation | Choosing |
| Locks across services, replicas and shards | In architecture |
| Reproduce it in two terminals | Lab |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The lock families. Each row is unpacked below.
| Kind | In plain words | Example | Who waits |
|---|---|---|---|
| Latch (LWLock, spinlock, buffer pin) | Microsecond guard on an in-memory structure | Two backends touching the same buffer page | Nobody 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 EXCLUSIVE | Conflicting statements on the whole table |
| Row-level lock | "Nobody else may change this row" | SELECT ... FOR UPDATE | Writers 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 UPDATE | Inserts into the range |
| Intention lock (IS/IX) | A table-level note "I lock rows in here" | Any InnoDB row lock | Only whole-table lock requests |
| Advisory lock | A named mutex the database stores for you | pg_try_advisory_lock(42) | Other callers of the same key |
| Metadata lock (MySQL) | Guards the table definition | ALTER TABLE vs open transactions | DDL, and everything queued behind it |
PostgreSQL table modes in one line each (weakest to strongest).
| Mode | Taken by | Blocks |
|---|---|---|
| ACCESS SHARE | SELECT | only ACCESS EXCLUSIVE |
| ROW SHARE | SELECT ... FOR UPDATE/SHARE | EXCLUSIVE, ACCESS EXCLUSIVE |
| ROW EXCLUSIVE | INSERT, UPDATE, DELETE, MERGE | SHARE and stronger |
| SHARE UPDATE EXCLUSIVE | VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY | itself and stronger |
| SHARE | CREATE INDEX | all writes |
| SHARE ROW EXCLUSIVE | CREATE TRIGGER, some ALTER TABLE | writes and itself |
| EXCLUSIVE | REFRESH MATERIALIZED VIEW CONCURRENTLY | everything except plain reads |
| ACCESS EXCLUSIVE | DROP, TRUNCATE, VACUUM FULL, most ALTER TABLE | everything, including SELECT |
The five rules to act on.
| Situation | Do this |
|---|---|
| Any DDL on a busy table | SET LOCAL lock_timeout = '2s' and retry with backoff |
| Workers taking jobs from a table | FOR 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 increments | Shard it, or append events and aggregate; do not queue on one row |
| Something is stuck | pg_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 locks | More or stronger locks |
|---|---|
| More concurrency, higher throughput | Transactions wait in queues |
| Anomalies possible unless you add checks | Anomalies prevented by construction |
| Errors at commit (retry) in optimistic schemes | Waits, timeouts and deadlocks instead of retries |
| Cheap for read-heavy workloads | Cheap for short, conflicting writes on few rows |
| Hard to reason about every interleaving | Hard 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
- "A plain SELECT never waits." It takes ACCESS SHARE, which conflicts with ACCESS EXCLUSIVE, so
ALTER TABLE,TRUNCATE,DROPandVACUUM FULLblock it, and a waiting ACCESS EXCLUSIVE request blocks it too. - "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.
- "A lock wait will time out on its own." PostgreSQL's
lock_timeoutdefaults to 0 (wait forever). InnoDB'sinnodb_lock_wait_timeoutis 50 seconds, and MySQL's metadata-locklock_wait_timeoutdefaults 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.
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 stepReal 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) | |
|---|---|---|
| Protects | Tables, rows, objects, advisory keys | Shared-memory structures, buffer pages |
| Held for | Until transaction end (usually) | Microseconds |
| Deadlock detection | Yes | No |
| Visible in | pg_locks, performance_schema.data_locks | wait_event_type = LWLock, Buffer; InnoDB SEMAPHORES section |
| You control it | Yes (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 \ Held | X | IX | S | IS |
|---|---|---|---|---|
| X | Conflict | Conflict | Conflict | Conflict |
| IX | Conflict | Compatible | Conflict | Compatible |
| S | Conflict | Conflict | Compatible | Compatible |
| IS | Conflict | Compatible | Compatible | Compatible |
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.
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; -- grantedReal 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.
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 balanceReal 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.
| Engine | Locks held to end of transaction | Plain reads lock? |
|---|---|---|
| PostgreSQL | All heavyweight locks (savepoint rollback releases) | No (MVCC) |
| MySQL InnoDB | All row and table locks | No, except SERIALIZABLE (becomes FOR SHARE) |
| SQL Server | X always; S only under REPEATABLE READ/SERIALIZABLE | Yes under locking READ COMMITTED; no with RCSI |
| Oracle | Row (TX) and table (TM) locks | Never |
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).
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| Engine | Finest data lock | Escalation | Coarsest |
|---|---|---|---|
| PostgreSQL | Row (stored in the tuple header, no memory limit) | Never | Table (LOCK TABLE), plus pg_database-level object locks |
| MySQL InnoDB | Index record (bitmap per page in the lock system) | Never | Table (LOCK TABLES, intention locks) |
| MySQL MyISAM | Table | n/a | Table |
| SQL Server | Row (RID/KEY) or page (PAG) | Yes, at 5,000 locks per statement per table, to table (or partition with LOCK_ESCALATION = AUTO) | Database |
| Oracle | Row (in the data block) | Never | Table (TM lock) |
| SQLite | Database file | n/a | Database file (one writer) |
| MongoDB (WiredTiger) | Document | n/a | Global, 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:
| Requested \ Held | ACCESS SHARE | ROW SHARE | ROW EXCL. | SHARE UPDATE EXCL. | SHARE | SHARE ROW EXCL. | EXCL. | ACCESS EXCL. |
|---|---|---|---|---|---|---|---|---|
| ACCESS SHARE | X | |||||||
| ROW SHARE | X | X | ||||||
| ROW EXCLUSIVE | X | X | X | X | ||||
| SHARE UPDATE EXCLUSIVE | X | X | X | X | X | |||
| SHARE | X | X | X | X | X | |||
| SHARE ROW EXCLUSIVE | X | X | X | X | X | X | ||
| EXCLUSIVE | X | X | X | X | X | X | X | |
| ACCESS EXCLUSIVE | X | X | X | X | X | X | X | X |
Which statement takes which lock (from the manual and each command's page):
| Statement | Table lock | Blocks reads? | Blocks writes? |
|---|---|---|---|
SELECT | ACCESS SHARE | No | No |
SELECT ... FOR UPDATE / NO KEY UPDATE / SHARE / KEY SHARE | ROW SHARE (+ row locks) | No | Only on locked rows |
INSERT, UPDATE, DELETE, MERGE, COPY FROM | ROW EXCLUSIVE (+ row locks) | No | Only on the same rows |
VACUUM (not FULL), ANALYZE, CREATE INDEX CONCURRENTLY, REINDEX CONCURRENTLY, CREATE STATISTICS, COMMENT ON | SHARE UPDATE EXCLUSIVE | No | No |
ALTER TABLE ... VALIDATE CONSTRAINT, SET STATISTICS, ATTACH PARTITION (on the parent) | SHARE UPDATE EXCLUSIVE | No | No |
CREATE INDEX (not concurrently) | SHARE | No | Yes, for the whole build |
CREATE TRIGGER, ALTER TABLE ... ADD FOREIGN KEY (both tables) | SHARE ROW EXCLUSIVE | No | Yes |
REFRESH MATERIALIZED VIEW CONCURRENTLY | EXCLUSIVE | No | Yes |
DROP TABLE, TRUNCATE, REINDEX, CLUSTER, VACUUM FULL, REFRESH MATERIALIZED VIEW, REPACK (PostgreSQL 19) | ACCESS EXCLUSIVE | Yes | Yes |
Most ALTER TABLE forms (ADD COLUMN, DROP COLUMN, ALTER COLUMN TYPE, SET NOT NULL, RENAME) | ACCESS EXCLUSIVE | Yes | Yes |
LOCK TABLE t (no mode given) | ACCESS EXCLUSIVE | Yes | Yes |
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 waitReal 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:
-- 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 itPostgreSQL 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 \ Held | FOR KEY SHARE | FOR SHARE | FOR NO KEY UPDATE | FOR UPDATE |
|---|---|---|---|---|
| FOR KEY SHARE | X | |||
| FOR SHARE | X | X | ||
| FOR NO KEY UPDATE | X | X | X | |
| FOR UPDATE | X | X | X | X |
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 allReal 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.
| Engine | Row lock syntax | Notes |
|---|---|---|
| PostgreSQL | FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, FOR KEY SHARE, each with NOWAIT / SKIP LOCKED, OF table | Repeatable 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 tbl | Locks index records it scans, plus gaps at Repeatable Read |
| SQL Server | Table hints UPDLOCK, XLOCK, HOLDLOCK, ROWLOCK, READPAST | UPDLOCK takes U locks, which avoid S→X conversion deadlocks |
| Oracle | FOR UPDATE [OF col] [NOWAIT / WAIT n / SKIP LOCKED] | No shared row lock mode; readers never wait |
| SQLite | none | The whole database is the lock unit |
| MongoDB | none; a write to a document is atomic | Transactions get WriteConflict instead of waiting |
Fix in SQL, Go and Laravel:
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.
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 millisecondsReal 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:
| Tool | Scope | Effect on conflict | Error |
|---|---|---|---|
lock_timeout (PostgreSQL, default 0) | Each lock wait in a statement | Fails after the limit | 55P03 lock_not_available, "canceling statement due to lock timeout" |
statement_timeout (PostgreSQL, default 0) | Whole statement | Fails after the limit, waiting or running | 57014 query_canceled |
idle_in_transaction_session_timeout | Idle time inside a transaction | Terminates the session, releasing its locks | 25P03 |
transaction_timeout (PostgreSQL 17+) | Whole transaction | Terminates the session | 25P04 |
NOWAIT (PostgreSQL, MySQL 8.0+, Oracle) | One locking statement | Fails at once | PG 55P03; MySQL 3572 ER_LOCK_NOWAIT; Oracle ORA-00054 |
SKIP LOCKED (PostgreSQL, MySQL 8.0+, Oracle) / READPAST (SQL Server) | One locking SELECT | Silently omits locked rows | none |
innodb_lock_wait_timeout (MySQL, default 50 s) | Each row lock wait | Rolls 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 waits | Fails after the limit | 1205 |
SET LOCK_TIMEOUT ms (SQL Server, default -1) | Each lock wait | Fails after the limit | 1222 "Lock request time out period exceeded" |
WAIT n (Oracle) / DDL_LOCK_TIMEOUT | Statement / DDL | Fails after n seconds | ORA-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.
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 6Real 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.
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
}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'.
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 itReal 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.
| Product | Advisory / named lock | Release |
|---|---|---|
| PostgreSQL | pg_advisory_lock family (session or transaction) | Unlock, transaction end, or session end |
| MySQL | GET_LOCK('name', timeout), RELEASE_LOCK, IS_FREE_LOCK (metadata-lock subsystem) | Explicit or session end |
| SQL Server | sp_getapplock / sp_releaseapplock (session or transaction owner) | Explicit or owner end |
| Oracle | DBMS_LOCK.REQUEST / RELEASE | Explicit, commit (if requested) or session end |
| Redis | SET key token NX PX 30000 + compare-and-delete | Expiry or delete; a lease, not a lock |
| Laravel | Cache::lock('name', 10) atomic locks on redis, database, memcached and other drivers | release(), 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
INSERTbefore 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_modechooses 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.
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 commitsReal 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 lock | data_locks.LOCK_MODE | SHOW ENGINE INNODB STATUS text |
|---|---|---|
| Table intention | IX / IS (LOCK_TYPE = TABLE) | TABLE LOCK table ... lock mode IX |
| Record only | X,REC_NOT_GAP / S,REC_NOT_GAP | lock_mode X locks rec but not gap |
| Gap only | X,GAP | lock_mode X locks gap before rec |
| Next-key | X / S | lock_mode X |
| Insert intention | X,GAP,INSERT_INTENTION | lock_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.
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| Engine | Plain reader vs writer | Writer vs writer |
|---|---|---|
| PostgreSQL | Never wait | Row lock, second waits |
| MySQL InnoDB | Never wait (consistent nonlocking read), except SERIALIZABLE | Row/next-key lock, second waits |
| Oracle | Never wait | Row lock (TX), second waits |
SQL Server, locking READ COMMITTED (default on-premises) | Reader waits for writer's X lock | Waits |
SQL Server with READ_COMMITTED_SNAPSHOT (default in Azure SQL Database) | No wait | Waits |
| SQLite WAL mode | Readers do not block the writer, and vice versa | One writer at a time |
| MongoDB WiredTiger | No 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.
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 timeReal 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).
| Option | How | Gain | Cost |
|---|---|---|---|
| Shorten the transaction | Update the hot row last, commit at once | Linear gain | Still one queue |
| Sharded counter | N rows per key, random shard, sum() on read | ~N× write throughput | Reads aggregate N rows |
| Append and aggregate | Insert an event row, roll up every few seconds | No row contention | Counter lags |
Redis INCR / HINCRBY | Single-threaded atomic increment | Very high throughput | Separate durability story |
| Sequence instead of counter table | nextval() is non-transactional | No lock at all | Gaps on rollback |
Fix: the sharded counter is in Hot-row counter redesign.
Per-engine behaviour
| Feature | PostgreSQL | MySQL InnoDB | SQL Server | Oracle | SQLite | MongoDB |
|---|---|---|---|---|---|---|
| Smallest data lock | Row (tuple header) | Index record + gap | Row/key, page | Row (in block) | Database | Document |
| Readers block writers? | No | No (except SERIALIZABLE) | Yes under locking RC; no with RCSI | No | Rollback journal: yes; WAL: no | No |
| Escalation | Never | Never | At 5,000 locks | Never | n/a | n/a |
| Range/phantom locks | None (SSI predicate locks are non-blocking) | Gap / next-key | Key-range (SERIALIZABLE) | None | n/a | n/a |
| Lock wait default | Forever | 50 s rows, 1 year metadata | Forever | Forever | busy_timeout 0: fail at once with SQLITE_BUSY | Transactions: 5 ms lock request timeout |
| Skip locked rows | SKIP LOCKED | SKIP LOCKED | READPAST | SKIP LOCKED | n/a | n/a |
| Advisory lock | pg_advisory_* | GET_LOCK | sp_getapplock | DBMS_LOCK | none | none |
| See locks | pg_locks, pg_stat_activity | performance_schema.data_locks, SHOW ENGINE INNODB STATUS | sys.dm_tran_locks | V$LOCK, V$SESSION | none | db.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:
| Hint | Effect | Typical use and risk |
|---|---|---|
NOLOCK (= READUNCOMMITTED) | No shared locks for reads; still takes Sch-S | Dirty reads, rows read twice or missed during page splits; prefer RCSI |
UPDLOCK | Takes update (U) locks held to end of transaction | "Read then update" without S→X conversion deadlocks |
ROWLOCK | Ask for row locks instead of page/table | Hint only; escalation can still happen |
PAGLOCK, TABLOCK, TABLOCKX | Coarser locks | Bulk loads (TABLOCK enables minimal logging) |
HOLDLOCK (= SERIALIZABLE) | Holds S/key-range locks to end | Upsert patterns with UPDLOCK, HOLDLOCK |
READPAST | Skips locked rows | Queue tables (SQL Server's SKIP LOCKED) |
XLOCK, NOWAIT | Exclusive lock; fail at once | Rare |
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
| Setting | Product | Default | Meaning |
|---|---|---|---|
lock_timeout | PostgreSQL | 0 (off) | Max wait for any single lock |
statement_timeout | PostgreSQL | 0 | Max statement duration |
idle_in_transaction_session_timeout | PostgreSQL | 0 | Kill sessions idle inside a transaction |
transaction_timeout | PostgreSQL 17+ | 0 | Max transaction duration |
deadlock_timeout | PostgreSQL | 1s | Wait before checking for deadlock; also the log_lock_waits threshold |
log_lock_waits | PostgreSQL | on in the current (19) manual | Log waits longer than deadlock_timeout |
log_lock_failures | PostgreSQL 18+ | off | Log NOWAIT lock failures |
max_locks_per_transaction | PostgreSQL | 64 | Sizes the shared lock table |
innodb_lock_wait_timeout | MySQL | 50 (seconds) | Row lock wait limit, session-settable |
innodb_rollback_on_timeout | MySQL | OFF | ON rolls back the whole transaction on 1205 |
innodb_deadlock_detect | MySQL | ON | Off relies on innodb_lock_wait_timeout |
innodb_autoinc_lock_mode | MySQL | 2 | AUTO-INC lock behaviour |
innodb_status_output_locks | MySQL | OFF | Adds lock detail to the InnoDB monitor |
lock_wait_timeout | MySQL | 31536000 (1 year) | Metadata lock wait limit |
LOCK_TIMEOUT | SQL Server | -1 (forever) | SET LOCK_TIMEOUT 2000 per session |
LOCK_ESCALATION | SQL Server | TABLE | Per table: TABLE, AUTO, DISABLE |
DDL_LOCK_TIMEOUT | Oracle | 0 | DDL wait limit in seconds |
busy_timeout | SQLite | 0 | How long to retry on SQLITE_BUSY |
maxTransactionLockRequestTimeoutMillis | MongoDB | 5 | Lock wait inside transactions |
Error codes you will catch Must-know
| Code | Product | Meaning | Retry? |
|---|---|---|---|
55P03 lock_not_available | PostgreSQL | lock_timeout fired or NOWAIT failed | Yes, with backoff, or answer "busy" |
57014 query_canceled | PostgreSQL | statement_timeout or pg_cancel_backend | Maybe |
40P01 deadlock_detected | PostgreSQL | Deadlock victim | Yes, whole transaction (Deadlocks) |
25P03 / 25P04 | PostgreSQL | Idle-in-transaction / transaction timeout ended the session | Reconnect, fix the code |
53200 out_of_memory | PostgreSQL | Lock table full | No: raise max_locks_per_transaction or touch fewer objects |
1205 ER_LOCK_WAIT_TIMEOUT | MySQL | Row or metadata lock wait timeout; only the statement is rolled back by default | Yes, but roll back the transaction yourself |
3572 ER_LOCK_NOWAIT | MySQL | NOWAIT could not lock | Answer "busy" |
1213 ER_LOCK_DEADLOCK | MySQL | Deadlock, transaction rolled back | Yes |
1222 | SQL Server | LOCK_TIMEOUT exceeded | Yes |
1205 | SQL Server | Deadlock victim | Yes |
ORA-00054 / ORA-00060 | Oracle | Resource busy (NOWAIT / timeout) / deadlock | Yes |
SQLITE_BUSY | SQLite | Another connection holds the write lock | Yes (busy_timeout) |
WriteConflict (112) | MongoDB | Concurrent write in a transaction | Yes (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_type | Means | Typical wait_event |
|---|---|---|
Lock | Waiting for a heavyweight lock | relation, transactionid (a row held by another tx), tuple, advisory, extend, virtualxid |
LWLock | Waiting for a lightweight lock (latch) | LockManager, BufferContent, WALWrite, ProcArray |
Buffer | Waiting for a data buffer or pin | BufferCleanup (VACUUM behind a pin), BufferExclusive |
IO | Waiting for disk | DataFileRead, WALSync |
Client | Waiting for the application | ClientRead (idle in transaction looks like this) |
IPC, Timeout, Activity, Extension | Inter-process, sleeps, idle background loops, extension waits | ParallelFinish, 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:
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").
-- 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\GDiagnosing lock waits, step by step
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 areLWLockorIO, it is not this page's problem.Find who blocks each waiter.
SELECT pid, pg_blocking_pids(pid) AS blocked_by FROM pg_stat_activity WHERE wait_event_type = 'Lock';Find the root blocker: the session that blocks others but waits for nobody.
sqlSELECT 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');Read the root.
idle in transactionwith an oldxact_startmeans application code left a transaction open (a missing commit, a network call inside a transaction, a debugger).activewith a long query means a heavy statement; a soft blocker (a waitingALTER) means the queue problem.See the objects.
SELECT locktype, relation::regclass, mode, granted, waitstart, pid FROM pg_locks WHERE pid = ANY(ARRAY[...]) ORDER BY granted DESC;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.Prevent. Add
lock_timeoutto DDL,idle_in_transaction_session_timeoutto app roles, keep transactions free of network calls, keeplog_lock_waitson 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
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| DDL freezing a table | lock_timeout + retry | SET LOCAL lock_timeout, backoff loop | Never causes an outage | Migration may need several attempts |
| Workers double-processing jobs | FOR UPDATE SKIP LOCKED | Claim in a short transaction | No waiting, no duplicates | Not FIFO-strict; inconsistent view |
| Same cron on every replica | Advisory lock | pg_try_advisory_xact_lock | No extra infra | Only inside one database |
| Read-decide-write races | Row lock or atomic update | FOR NO KEY UPDATE, or one UPDATE ... WHERE | Correct under concurrency | Waits on hot rows |
| Hot counter | Sharded or append-only counter | N rows, sum on read | N× throughput | Slower reads, eventual totals |
| "Who is blocking?" | Blocker report | pg_blocking_pids + pg_stat_activity | Supported API | Small 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.
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 againGo, before (no bound) and after:
// 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
}// 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.
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
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.
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
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
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;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
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
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
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
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
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
| Situation | Recommended lock | Extra technique | Reason |
|---|---|---|---|
| Update one row after reading it (status machine) | FOR NO KEY UPDATE (PostgreSQL), FOR UPDATE (InnoDB) | Short transaction, lock_timeout | Weakest correct lock; FK inserts not blocked |
| Simple counter or stock decrement | No explicit lock | UPDATE ... SET x = x - 1 WHERE id = ? AND x > 0 | Atomic statement, shortest lock |
| Very hot counter | None on one row | Sharded counter, Redis INCR, append + aggregate | Removes the serialisation point |
| Parent must not disappear while I insert children | FOR KEY SHARE / FK | Let the FK do it | Weakest mode that protects the key |
| Work queue | FOR UPDATE SKIP LOCKED (READPAST on SQL Server) | Index on (status, run_at), reaper | No waiting between workers |
| User-facing "is this seat free" | FOR UPDATE NOWAIT | Return 409 on 55P03/3572 | Fail fast instead of hanging a request |
| Schema change on a hot table | Whatever the DDL needs | lock_timeout + retry, CONCURRENTLY, NOT VALID | Avoids the lock queue outage |
| One job instance across replicas | pg_try_advisory_xact_lock | Or Cache::lock, onOneServer() | No extra table, auto-release |
| Bulk rewrite of a table | LOCK TABLE ... IN EXCLUSIVE MODE or batches | Batches of 1,000–5,000 rows | Avoid escalation and long row locks |
| Reports on OLTP data | None | MVCC snapshot or a replica | Readers should never lock |
| Range must stay empty (no phantom inserts) | InnoDB next-key (Repeatable Read) or PostgreSQL Serializable / exclusion constraint | Unique or exclusion constraint | Constraints 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.
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-- 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).
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).
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).
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 completesRepeat 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).
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).
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 neededExperiment 6: SKIP LOCKED workers (PostgreSQL).
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
| Belief | Reality |
|---|---|
| "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
| Topic | Remember |
|---|---|
Table lock that blocks SELECT | Only ACCESS EXCLUSIVE (DROP, TRUNCATE, VACUUM FULL, most ALTER) |
CREATE INDEX | SHARE blocks writes; CONCURRENTLY does not |
| Row lock for updates | FOR NO KEY UPDATE unless the key changes |
| Lock queue | A waiting request blocks later conflicting requests (soft block) |
| DDL | SET LOCAL lock_timeout = '2s' + retry |
| Fail fast | NOWAIT (55P03 / 3572 / ORA-00054) |
| Queues | FOR UPDATE SKIP LOCKED (SQL Server READPAST) |
| Singletons | pg_try_advisory_xact_lock(key) |
| Who blocks | pg_blocking_pids(pid) + pg_stat_activity |
| Lock logging | log_lock_waits, threshold deadlock_timeout |
| InnoDB lock wait | innodb_lock_wait_timeout 50 s, error 1205, statement-only rollback |
| InnoDB ranges | Next-key = record + gap before; disabled for searches at Read Committed |
| InnoDB view | performance_schema.data_locks / data_lock_waits, SHOW ENGINE INNODB STATUS |
| SQL Server | Escalation at 5,000 locks; UPDLOCK for read-then-update |
| Hot rows | Throughput ≈ 1 / lock hold time; shard or append |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Concurrency control | Mechanisms that make concurrent transactions behave correctly |
| Pessimistic locking | Prevent conflicts by locking before acting |
| Optimistic concurrency control | Detect conflicts at write/commit time and retry |
| Lock | Transaction-duration guard on data or objects, with modes and deadlock detection |
| Latch | Short guard on in-memory structures; no deadlock detection |
| Lightweight lock (LWLock) | PostgreSQL latch for shared-memory structures, shared/exclusive |
| Spinlock | Busy-wait latch held for a few instructions |
| Buffer pin | Reference count keeping a buffer page in memory while read |
| Heavyweight lock | PostgreSQL'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 2PL | Hold exclusive locks until commit or abort |
| Lock granularity | Size of the locked unit: row, page, table, database |
| Page-level lock | Lock on one data page; in PostgreSQL a short buffer-content lock |
| Lock escalation | Replacing many fine locks with one coarse lock (SQL Server) |
| Lock conversion / lock upgrade | Changing a held lock to a stronger mode (S→X) |
| ACCESS SHARE | PostgreSQL table mode for SELECT |
| ROW SHARE | PostgreSQL table mode for SELECT ... FOR ... |
| ROW EXCLUSIVE | PostgreSQL table mode for DML |
| SHARE UPDATE EXCLUSIVE | PostgreSQL mode for VACUUM, ANALYZE, CREATE INDEX CONCURRENTLY |
| SHARE | PostgreSQL mode for CREATE INDEX; blocks writes |
| SHARE ROW EXCLUSIVE | PostgreSQL self-conflicting mode for CREATE TRIGGER, ADD FOREIGN KEY |
| EXCLUSIVE | PostgreSQL mode allowing only reads |
| ACCESS EXCLUSIVE | PostgreSQL mode that blocks everything |
| LOCK TABLE | Explicit table lock statement; default ACCESS EXCLUSIVE |
| FOR UPDATE | Strongest row lock |
| FOR NO KEY UPDATE | Row lock for non-key updates; compatible with FOR KEY SHARE |
| FOR SHARE | Shared row lock blocking updates and deletes |
| FOR KEY SHARE | Weakest row lock, used by FK checks |
| MultiXact | PostgreSQL structure recording several lockers of one row |
| Lock queue | Ordered list of waiters for a lock |
| Hard block / soft block | Blocked by a holder / blocked by an earlier waiter |
| lock_timeout | PostgreSQL limit on each lock wait (55P03) |
| statement_timeout | PostgreSQL limit on statement duration (57014) |
| idle_in_transaction_session_timeout | Ends sessions idle inside a transaction |
| NOWAIT | Fail at once if a lock is not available |
| SKIP LOCKED | Skip rows that cannot be locked at once |
| READPAST | SQL Server hint equivalent to SKIP LOCKED |
| Advisory lock | Application-defined lock on a number |
| pg_try_advisory_lock | Non-blocking session advisory lock |
| pg_advisory_xact_lock | Transaction-scoped advisory lock |
| pg_locks | PostgreSQL view of held and awaited locks |
| pg_stat_activity | PostgreSQL view of sessions, states and wait events |
| pg_blocking_pids | Function returning the pids blocking a session |
| wait_event_type | Category of what a backend waits on: Lock, LWLock, Buffer, IO, Client... |
| log_lock_waits | Logs waits longer than deadlock_timeout |
| deadlock_timeout | Wait before deadlock check; lock-wait log threshold |
| Deadlock | Cycle of waits resolved by aborting a victim |
| fast-path lock | Weak relation lock recorded per backend, pg_locks.fastpath |
| max_locks_per_transaction | Sizes PostgreSQL's shared lock table |
| Record lock | InnoDB lock on one index record |
| Gap lock | InnoDB lock on the gap between index records; blocks inserts only |
| Next-key lock | InnoDB record lock plus the gap before it |
| Supremum | InnoDB pseudo-record above the largest index value |
| Insert intention lock | InnoDB gap lock taken by INSERT before inserting |
| AUTO-INC lock | InnoDB table-level lock for auto-increment values |
| innodb_autoinc_lock_mode | 0 traditional, 1 consecutive, 2 interleaved (default) |
| innodb_lock_wait_timeout | InnoDB row lock wait limit (50 s, error 1205) |
| SHOW ENGINE INNODB STATUS | InnoDB monitor output with TRANSACTIONS and deadlock sections |
| performance_schema.data_locks | MySQL table of held and requested data locks |
| data_lock_waits | MySQL table pairing blocked and blocking lock requests |
| Metadata lock (MDL) | MySQL lock on table definitions; DDL waits on it |
| NOLOCK | SQL Server hint for dirty reads without shared locks |
| UPDLOCK | SQL Server hint taking update locks held to transaction end |
| ROWLOCK | SQL Server hint requesting row-level locks |
| Sch-S / Sch-M | SQL Server schema stability / modification locks |
| TX / TM lock | Oracle row-transaction lock / table DML lock |
| WiredTiger | MongoDB storage engine with document-level concurrency |
| WriteConflict | MongoDB error when concurrent transactions write the same document |
| Single-threaded execution | Redis runs commands one at a time, so each is atomic |
| MVCC | Multiple row versions so readers do not block writers |
| Hot row | A row most transactions must lock, capping throughput |
| Lock-free counter | Counter design that avoids one contended row (shards, append, atomics) |
| Lock contention | Time transactions spend waiting for locks held by others |
References
- PostgreSQL documentation: Explicit Locking, pg_locks, LOCK, SELECT (locking clause), Client Connection Defaults, Lock Management, Error Reporting and Logging, Monitoring Statistics (wait events), System Information Functions (pg_blocking_pids), System Administration Functions (advisory locks)
- PostgreSQL source: src/backend/storage/lmgr/README
- MySQL 8.4 Reference Manual: InnoDB Locking, Metadata Locking, The data_locks Table, InnoDB Standard Monitor and Lock Monitor Output, InnoDB Startup Options and System Variables
- Microsoft: Transaction locking and row versioning guide, Table hints (Transact-SQL)
- Oracle Database 19c Concepts: Data Concurrency and Consistency
- MongoDB: FAQ: Concurrency
- Redis: Diagnosing latency issues, Transactions
- Go:
database/sql - Laravel 13: Query Builder: Pessimistic Locking, Database: Transactions