Vineet Ganti
Locks, Deadlocks, Double Bookings and Connection Pools
All posts

Data Engineering/Database Engineering · Part 8 of 14

·18 min read

Locks, Deadlocks, Double Bookings and Connection Pools

How databases keep concurrent work safe: shared and exclusive locks, who really dies in a deadlock, four ways to stop a double booking, why OFFSET gets slower with every page, and a connection leak reproduced for real.

DatabasesPostgreSQLConcurrencyBackend

Post 1 described what isolation promises. This post is about the machinery that keeps those promises, and the mistakes applications make around it.

The course's lectures here are the most practical in the series: locks, a deadlock, a seat-booking app, pagination and connection pools. Re-running them turned up several claims that need adjusting, including who dies in a deadlock, and a bug in the course's own booking code, which I reproduced to see what it does.

#Shared and exclusive locks

A lock is how a transaction says "this is mine for now". There are two basic kinds:

An exclusive lock says nobody else may touch this. A shared lock says this mustn't change while I read it, and anyone else can do the same. The course's example is a bank report: while it runs, writers wait, which is why a bank's site might grey out features at midnight.

Here's the real behaviour on Postgres:

Who waits for a shared lock?✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN
BEGIN
Session A wants a stable value while it works.
accounts, seen from a third connection
idbalance
1100
Step 1 of 8

Locks also come at different sizes. Row locks are the fine-grained ones. A table lock covers everything, and ALTER TABLE needs the strongest of them. SQL Server has lock escalation, where a query touching thousands of rows trades them for one table lock to save memory. Try this box to see what different statements hold. The last preset shows something the course points out: in Postgres a row lock lives in the row itself, in xmax, and not in a lock table.

See your own locksruns in your browser
One session, so nothing can block here, but you can read what you hold. Compare what each statement takes in pg_locks.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

#Deadlocks

Two sessions each hold something the other wants:

Neither can continue, so the database has to kill one. The course says the last one entering the deadlock fails. I wanted to test that, because the docs describe something else: a backend that has waited deadlock_timeout (1 second by default) runs a deadlock check, and if it finds a cycle, it aborts itself. So who dies should depend on whose check finds the cycle first.

Here are the same statements with different timing. Compare the tabs:

Who dies in a deadlock?✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN
BEGIN
Two sessions, each about to take a row.
test, seen from a third connection
pk
(no rows)
Step 1 of 7

In the first tab, A waited for over a second, its check found no cycle, and then B closed the loop and died a second later. That's what the course saw. In the second tab, B closed the loop within A's first second, so A's check fired first, found the cycle, and A died, although A entered the wait first.

So "last in" is usually true when people type by hand, since they're slower than a second. Your application should treat any transaction as a possible victim, catch error 40P01, and retry. The best prevention is to take locks in the same order everywhere.

#Waiting on an uncommitted key

A related case from the same lecture: inserting a key that another transaction has inserted and not committed. The database can't tell yet whether your key is free.

Waiting on someone else's uncommitted key✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN
BEGIN
A opens a transaction.
test, seen from a third connection
pk
(no rows)
Step 1 of 4

The waiter's fate depends entirely on the other transaction.

#Two-phase locking

Two-phase locking is a rule: a transaction first acquires locks, then releases them, and it never acquires one after releasing one.

Real databases use the strict form and hold everything until commit. The course uses it to introduce a classic problem.

#The double booking problem

Two people look at a seat, both see it free, and both book it. A check followed by a write isn't atomic: anything can happen between them. The course builds this as an Express app, with a debugger pausing between the SELECT and the UPDATE to force the race. Here's the same race directly, with each fix on its own tab:

Two people book the same seat✅ recorded on PostgreSQL 18.6
1 · Session Ana
BEGIN
BEGIN
Ana opens the booking page.
seats, seen from a third connection
idisbookedname
10NULL
20NULL
Step 1 of 8
ApproachWhat happensGood when
No lockBoth succeed, and the last write winsNever
SELECT ... FOR UPDATEThe second waits, then finds nothingSeveral steps depend on the check
UPDATE ... WHERE isbooked = 0The second gets UPDATE 0One statement can do it all

The third row is elegant, and the course's second lecture on it raises a fair worry: why does this work at all? The docs explain: at read committed, a waiting UPDATE re-evaluates its WHERE clause against the row version the first transaction committed. The course calls this being at the mercy of the implementation. The fourth tab proves the point: raise the level to repeatable read, and the same statement fails with a serialization error instead. So it's safe either way, but your code must handle what happens. The course prefers FOR UPDATE for being explicit, and that's a reasonable default.

Three ways not to wait✅ recorded on PostgreSQL 18.6
1 · Session A
BEGIN
BEGIN
Session A is halfway through booking.
Step 1 of 7

SKIP LOCKED is more useful than it looks. It's how you build a job queue on a table: each worker takes the next row nobody holds.

#A bug in the booking app

The course's index.mjs has a subtle bug that's worth more than the demo itself. It takes a client from the pool, begins a transaction, and if the seat is taken, returns early, without a rollback or a release(). I reproduced that with a pool of 2:

✅ ran here · PostgreSQL 18.6 · what the early return does
-- three requests for a taken seat, through a pool of 2, with an early return that skips release()
request 1: seat already booked
request 2: seat already booked
request 3: ERROR timeout exceeded when trying to connect

pg_stat_activity: 2 idle in transaction

Two requests for a taken seat used up the pool, and the third timed out. On the server those connections are idle in transaction, which is worse than idle: each holds a transaction open, stopping VACUUM from cleaning up and holding any locks it took. With the default of no timeout, the third request would simply hang forever.

The fix is try ... finally, with release() in the finally.

#Optimistic and pessimistic control

The course keeps coming back to this choice, which post 1 met as SERIALIZABLE against FOR UPDATE:

Locks cost memory and queueing, which is why some systems go lock-free and detect conflicts instead. A common application-level form is a version column: UPDATE ... SET v = v + 1 WHERE id = 1 AND v = 7, and a row count of 0 means someone got there first. Neither is better. It depends on how often conflicts really happen.

#Read-only transactions

A student asked what BEGIN READ ONLY buys. The course's answer: mostly protection, with a small amount of optimisation.

✅ ran here · PostgreSQL 18.6
BEGIN READ ONLY;

INSERT INTO t VALUES (1);
ERROR:  cannot execute INSERT in a read-only transaction

ROLLBACK;

BEGIN;

SELECT pg_current_xact_id_if_assigned() AS id_after_a_read;
 id_after_a_read 
-----------------
                
(1 row)

SELECT count(*) FROM t;
 count 
-------
     0
(1 row)

SELECT pg_current_xact_id_if_assigned() AS id_still;
 id_still 
----------
         
(1 row)

INSERT INTO t VALUES (1);

SELECT pg_current_xact_id_if_assigned() AS id_after_a_write;
 id_after_a_write 
------------------
             1954
(1 row)

COMMIT;

The first half is the protection. The second half shows the optimisation is mostly automatic: Postgres doesn't even assign a transaction id until the first write, so a read-only transaction skips that cost anyway.

#Why OFFSET gets slower

The obvious pagination is LIMIT 10 OFFSET n. The trap is what OFFSET does: the database can't jump to the 100,000th row. It has to produce all of them and throw them away.

The fix is keyset pagination: instead of a position, ask for what comes after the last row you saw. That's one index descent, at any depth:

✅ ran here · PostgreSQL 18.6
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY ON) SELECT id, title FROM news ORDER BY id DESC OFFSET 1000000 LIMIT 10;
                                     QUERY PLAN                                     
------------------------------------------------------------------------------------
 Limit (actual rows=10.00 loops=1)
   Buffers: shared hit=9106
   ->  Index Scan Backward using news_pkey on news (actual rows=1000010.00 loops=1)
         Index Searches: 1
         Buffers: shared hit=9106
 Planning:
   Buffers: shared hit=67
 Planning Time: 0.308 ms
 Execution Time: 68.122 ms
(9 rows)

EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY ON) SELECT id, title FROM news WHERE id < 1000000 ORDER BY id DESC LIMIT 10;
                                  QUERY PLAN                                   
-------------------------------------------------------------------------------
 Limit (actual rows=10.00 loops=1)
   Buffers: shared hit=5
   ->  Index Scan Backward using news_pkey on news (actual rows=10.00 loops=1)
         Index Cond: (id < 1000000)
         Index Searches: 1
         Buffers: shared hit=5
 Planning:
   Buffers: shared hit=3
 Planning Time: 0.321 ms
 Execution Time: 0.037 ms
(10 rows)

The plans say it all: rows=1000010 against rows=10, and 9,106 pages against 5. Over a range of depths:

At 1.9M rows skipped: OFFSET 479 ms · keyset 0.029 ms ✅ measured on PostgreSQL 18.6

Try it on 200,000 rows:

Offset or keyset?runs in your browser
200,000 stories. Compare the rows read in each plan, then try a deeper OFFSET.
Real PostgreSQL loads when you press Run: about 6 MB, once per visit.

Speed isn't the only problem. Offsets count positions, so a row inserted between two page loads shifts everything along:

A row inserted between two pages✅ recorded on PostgreSQL 18.6
1 · Session Reader
SELECT id, title FROM news ORDER BY id DESC OFFSET 0 LIMIT 3
idtitle
10story 10
9story 9
8story 8
Page one: stories 10, 9 and 8.
Step 1 of 4

Story 8 appears on both pages. With keyset pagination, step 4 carried on correctly. The trade-off is that you can't jump to page 500 directly, which most feeds don't need.

#Connection pooling

Opening a database connection means a TCP handshake, maybe TLS, authentication, and on Postgres a new process. A stateless route that does all that for each request pays that cost every time. A pool keeps connections open and lends them out.

Request or acknowledgmentData

The course measures this from an Express app and sees about a 50% saving. Measuring the database part alone, against a local container, the gap was bigger:

✅ ran here · PostgreSQL 18.6
-- 1,000 lookups, one at a time
new connection per request   12.63 ms each
from a pool                  1.11 ms each

Sizing matters too. Here are 200 requests arriving at once, each query taking 20 ms:

At 50 connections in the pool: 91 ms ✅ measured on PostgreSQL 18.6

With one connection, the slowest requests waited over 4 seconds. Fifty brought that under 100 ms. That's the best case, because these queries only sleep on the server. Real queries compete for CPU and disk, so past some point more connections only add contention, and every Postgres connection is a process. Bigger isn't automatically better.

The pg driver's settings are the ones to know:

SettingDefaultMeaning
max10The most connections the pool will open
connectionTimeoutMillis0How long to wait for a free one. 0 means forever
idleTimeoutMillis10,000How long an idle connection stays open

And two usage rules:

  • pool.query() borrows and returns a connection for you, and is fine for single statements.
  • For a transaction you need pool.connect(), so that every statement runs on the same connection, then release().

A student asked why one connection can't serve many queries at once. The course's answer is that the protocol is strictly request and response on a connection, so a second query must wait for the first. A pool gives you real concurrency by having several connections.

#Things that can trip you up

  • Taking locks in different orders. That's where most deadlocks come from.
  • Not retrying. Any transaction can be the deadlock victim, so handle 40P01 and 40001.
  • A check, then a write. Without a lock or a single statement, this is a race, however fast it is.
  • Long transactions. Locks are held until commit, so do slow work, such as calling an API, outside the transaction.
  • idle in transaction. Look for it in pg_stat_activity. It usually means a leak.
  • connectionTimeoutMillis: 0. A leak then hangs requests rather than failing them.
  • OFFSET on big tables. It looks fine in development, where pages are shallow.
  • Keyset on a non-unique column. Include the primary key as a tie-breaker, or rows can be skipped.

#Reproduce this yourself

  1. ✅ Open two psql sessions on any Postgres, and follow each replay step by step, in the order shown.
  2. ✅ For the deadlock timing, type slowly for the first tab, and paste the two statements within a second for the second tab. You can also set deadlock_timeout higher to make the window wider.
  3. ✅ To reproduce the leak in Node:
    js
    const pool = new pg.Pool({ max: 2, connectionTimeoutMillis: 1500 });
    const book = async () => {
      const c = await pool.connect();
      await c.query("BEGIN");
      const r = await c.query("SELECT * FROM seats WHERE id = 1 AND isbooked = 0 FOR UPDATE");
      if (r.rowCount === 0) return "seat already booked"; // no ROLLBACK, no release
      c.release();
    };
    
  4. ✅ Check for leaks with SELECT state, count(*) FROM pg_stat_activity GROUP BY state;.
  5. 🎓 The course's Express app and its browser benchmark aren't reproduced here. I measured the database calls directly.

#Glossary

TermMeaning
Shared lockLets others read, stops writers
Exclusive lockStops everyone else
DeadlockTransactions each waiting for the other
deadlock_timeoutHow long to wait before checking for a deadlock
Two-phase lockingAll locks are acquired before any is released
FOR UPDATE, FOR SHARELocking reads
NOWAIT, SKIP LOCKEDFail at once, or skip rows that are locked
Keyset paginationAsking for rows after the last one seen
Connection poolA set of open connections lent to requests
Lock escalationTrading many row locks for one table lock

#Summary

Locks are the pessimistic side of concurrency control: shared for readers who need stability, exclusive for writers, and in Postgres neither for ordinary reads. Cycles of waits become deadlocks, and timing decides the victim, so applications must be ready to retry. A check followed by a write is a race, fixed by locking the read or by putting the check in the write. OFFSET reads everything it skips, so keyset pagination wins at any depth. Pools remove the cost of connecting, as long as every code path gives the connection back.

#Concepts at a glance

ConceptIn one lineWhy it matters
Lock compatibilityShared with shared, nothing with exclusivePredicts who waits
Plain readTakes no row lock in PostgresMVCC keeps readers out of the way
Deadlock victimWhoever's check finds the cycleAny transaction can be aborted
FOR UPDATELocks the rows it readsMakes check-then-write safe
Check in the UPDATEOne atomic statement, read the row countNo separate lock needed
SKIP LOCKEDTake what's freeA job queue on a table
Keyset paginationContinue from the last row seenFlat cost, no duplicates
PoolReuse connectionsRemoves the cost of connecting
release() in finallyEvery path gives it backStops pool exhaustion

#Test yourself

In Postgres, session A holds FOR SHARE on a row. What happens to a plain SELECT, another FOR SHARE, and an UPDATE from session B?

The plain SELECT runs, since it takes no row lock. Another FOR SHARE runs, since shared locks are compatible. The UPDATE waits until A finishes. It isn't given an error.

Two sessions deadlock. Which one does Postgres abort?

The one whose deadlock check finds the cycle. Each backend checks once it has waited deadlock_timeout. If the cycle closes after the first session's check ran, the second one dies. If it closes before, the first one does.

Why does UPDATE seats SET ... WHERE id = 1 AND isbooked = 0 stop a double booking at read committed?

The second UPDATE waits for the row lock, then re-evaluates its WHERE clause against the committed row. It no longer matches, so it updates 0 rows, and the application sees that count.

Why does fetching page 100,000 with OFFSET take so long, even with an index?

OFFSET has to produce every skipped row and discard it. The plan shows it reading a million rows to return 10. Keyset pagination starts at the right place in the index instead.

A pool of 10 connections, and requests start hanging. Nothing's wrong with the database. What do you check first?

Look for leaks: code paths that take a client and don't release it, often an early return. pg_stat_activity showing idle in transaction is the usual sign. Then check connectionTimeoutMillis, because 0 hangs forever.

#Open questions and gaps

  • I measured the pool from a Node script, not through the course's Express app, so the absolute numbers differ, and the 11 times figure is against a local container.
  • The pool-size chart uses queries that only sleep, so it shows queueing and not contention.
  • 🎓 SQL Server's lock escalation is from the course and not run here.

#Sources