Table-Level Locks & Advisory Locks
Use table locks and advisory locks for migrations and application coordination.
In plain words
Some changes need the whole table to themselves, and advisory locks are agreed-upon "I'm doing this" flags for your own jobs.
Think of it like…
A meeting room: normal use (reading and writing on the whiteboard) can happen together, but repainting the room needs everyone out, and anyone arriving while the painter waits must also wait. Advisory locks are a sign-up sheet on the door that only works because everyone agrees to check it.
Where you’ve seen it
Three app servers run the same nightly billing cron. Each starts with SELECT pg_try_advisory_lock(hashtext('nightly_billing')); the first gets true and runs the job, the others get false and exit immediately. The job ends with pg_advisory_unlock, and if the server crashes, the lock is released automatically when its session ends, so tomorrow's run isn't blocked.
Words you’ll hear
- ACCESS SHARE / ROW EXCLUSIVE
- Table locks taken by SELECT / by INSERT, UPDATE, DELETE; they don't conflict with each other.
- ACCESS EXCLUSIVE
- Taken by most ALTER TABLE, DROP, TRUNCATE, VACUUM FULL; conflicts with everything, even SELECT.
- Lock queue
- Waiting lock requests in order; a waiting ACCESS EXCLUSIVE blocks everyone who arrives after it.
- Advisory lock
- An application-defined lock on a 64-bit key, held per session or per transaction.
Visual diagram
Theory & example queries
Table lock modes and the lock queue
PostgreSQL has eight table lock modes. The everyday ones don't conflict: many sessions can read (ACCESS SHARE) and write rows (ROW EXCLUSIVE) at once, with row locks resolving conflicts on individual rows. CREATE INDEX takes SHARE, which blocks writes but not reads, and CREATE INDEX CONCURRENTLY takes a weaker lock that blocks neither. Most ALTER TABLE forms, DROP, TRUNCATE and VACUUM FULL need ACCESS EXCLUSIVE.
Locks are granted in queue order, so a waiting ACCESS EXCLUSIVE request blocks every later request on that table, even plain SELECTs that are compatible with the current holder. A two-millisecond ALTER can cause a multi-minute outage if it queues behind a long-running query. Always run DDL with SET lock_timeout = '3s' (and retry), and find blockers with SELECT pid, pg_blocking_pids(pid), query FROM pg_stat_activity WHERE wait_event_type = 'Lock';.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SET lock_timeout = '3s';ALTER TABLE ordersADD COLUMN gift_message text;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Representative lock-timeout result
Note: Assumes another transaction holds a conflicting lock. If the lock is available within 3 seconds, ALTER TABLE reports success instead.
If the lock isn't granted within 3 seconds, the statement fails instead of blocking traffic, and the migration tool retries later.
Key takeaway: ACCESS EXCLUSIVE blocks all; a queued one blocks everyone behind it, so use lock_timeout.
Advisory locks for coordination
Advisory locks lock a number you choose (one bigint or two integers), often derived from a name with hashtext. pg_advisory_lock(k) waits for the lock and holds it until pg_advisory_unlock or the session ends; pg_try_advisory_lock(k) returns true or false immediately; pg_advisory_xact_lock(k) is released automatically at COMMIT or ROLLBACK. Uses include single-instance cron jobs, serialising work per customer (pg_advisory_xact_lock(customer_id)), and migration tools such as Flyway and Rails migrations, which use one to stop two deploys migrating at once.
Watch for connection pooling: session-level advisory locks belong to a database connection, and with PgBouncer in transaction mode, the next transaction on that connection may be someone else's, so the lock leaks or is released by the wrong code. Prefer transaction-level locks there. Locks are visible in pg_locks with locktype = 'advisory'. MySQL offers similar named locks with GET_LOCK('name', timeout) and RELEASE_LOCK('name').
BEGIN;SELECT pg_advisory_xact_lock(4821);UPDATE walletsSET balance = balance - 250WHERE customer_id = 4821;INSERT INTO ledger (customer_id, amount)VALUES (4821, -250);COMMIT;PostgreSQL is the lesson baseline unless noted otherwise.
Open a transaction so changes can be checked and committed or rolled back together.
Representative serialized transaction
Note: Assumes wallet 4821 exists with enough balance; competing transactions using the same advisory key wait, while other keys can proceed.
Other transactions for customer 4821 wait; other customers proceed in parallel.
Key takeaway: try-lock for single-run jobs, xact locks with poolers, keys from hashtext or ids.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Know what each statement locks
Reads and row writes coexist; most ALTER, DROP and TRUNCATE need ACCESS EXCLUSIVE.
SELECT: ACCESS SHARE · ALTER: ACCESS EXCLUSIVEWhen to use it & trade-offs
What it is
Besides row locks, databases take table-level locks automatically: in PostgreSQL every SELECT holds ACCESS SHARE, every INSERT, UPDATE or DELETE holds ROW EXCLUSIVE, and ALTER TABLE, DROP and TRUNCATE need ACCESS EXCLUSIVE, which conflicts with everything. Advisory locks are different: the database doesn't take them for you; your application asks for a lock on a number, such as pg_advisory_xact_lock(42), to coordinate work like "only one server runs the billing job".
Why it matters: Two production problems come from table locks: a migration's ALTER TABLE waiting behind a long query and blocking all traffic queued behind it, and jobs running twice because several servers started them. Understanding lock modes and the lock queue prevents the first; advisory locks solve the second without extra infrastructure. Both come up in backend and DevOps interviews.
When to reach for it
- Making sure a cron job runs on only one server
- Serialising balance changes per customer
- Safe schema migrations with lock_timeout
When to avoid or be careful
- DDL without lock_timeout on busy tables
- Session-level advisory locks behind PgBouncer transaction pooling
- LOCK TABLE in application code paths
Ways to coordinate concurrent work
Strengths: Fine-grained; automatic with the data.
Watch out: Only covers rows that already exist.
Strengths: No extra infrastructure; released on disconnect.
Watch out: Purely cooperative; session locks misbehave with transaction pooling.
Strengths: Simple and absolute.
Watch out: Blocks other work; easy to cause outages.
Interview signals & numbers to know
When this topic comes up
- “A migration took the site down for a few minutes”
- “The job ran twice on two servers”
- “How do you prevent concurrent runs?”
- Lock queues
- pg_advisory_lock
Benchmarks & rules of thumb
- 8
- table lock modes in PostgreSQL
- 3 s
- a typical lock_timeout for migrations
- 64-bit
- advisory lock key size
Common mistakes & follow-ups
Common interview mistakes
- Running ALTER TABLE during a long analytics query, so the ALTER queues and every request behind it times out.
- Taking pg_advisory_lock through PgBouncer in transaction mode and never releasing it on the right connection.
- Using pg_advisory_lock (waiting) for a cron guard, so the other servers queue up and run the job afterwards.
Likely interviewer follow-ups
- Why can a fast ALTER TABLE block all queries on a table?
- How would you ensure a scheduled job runs only once across several servers?
- What's the difference between session and transaction advisory locks?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Table-Level Locks & Advisory Locks with hands-on SQL practice and interview Q&A.