Prevent Overlapping Reservations with PostgreSQL Exclusion Constraints
A reservation service has to stop two bookings from claiming the same room at the same time, even when requests arrive together.…
When your application inserts a row with a non-null foreign-key value, PostgreSQL checks that a matching row exists in the referenced table. A foreign key requires a value in one table to match a key in another. While the transaction stays open, PostgreSQL protects that matching row with a row-level FOR KEY SHARE lock, which prevents a delete or key change from proceeding at the same time. If another transaction is deleting that row or changing its key, the inserting backend waits. If the inserting transaction already holds the lock, the transaction trying to delete or change the key waits instead.
PostgreSQL locks only the matching row rather than the whole table, so ordinary reads and updates to other columns continue without blocking. When you know which statements conflict, you can tell a foreign-key lock wait apart from a slow lookup or another insert bottleneck, and you can narrow down what is causing the delay.
PostgreSQL uses row-level lock modes to coordinate transactions that touch the same row at the same time. When PostgreSQL checks a foreign key, it takes the equivalent of a FOR KEY SHARE lock on the matching row in the referenced table. As PostgreSQL’s explicit-locking documentation explains, this lock stops another transaction from deleting the row or changing its key, while still allowing other key-share locks and updates that leave the key alone. An official PostgreSQL commit message documents foreign-key triggers taking FOR KEY SHARE, though the exact implementation depends on your PostgreSQL version.
This distinction matters when several transactions write at once. Two transactions inserting into the child table can both hold compatible key-share locks on the same parent key. A transaction running a plain SELECT on the parent row does not block, and a transaction updating a non-key column, such as the parent’s note, can also proceed because it does not request a conflicting lock. By contrast, a transaction that deletes the parent row or updates its referenced key conflicts with the key-share lock and waits until the lock is released.
PostgreSQL holds that lock until the transaction commits or rolls back, even after the INSERT statement itself returns. If a transaction inserts a child row and stays open, it keeps protecting the referenced key the whole time. Statements like INSERT, UPDATE, and DELETE also acquire table-level locks on the tables they modify, which are separate from the row-level lock PostgreSQL takes for the foreign-key check.
This two-session example shows how an insert can hold up a change to a parent row. Here, parent.id is a primary key, and any non-null parent_id in child must match it:
CREATE TABLE parent (
id integer PRIMARY KEY,
note text
);
CREATE TABLE child (
parent_id integer REFERENCES parent(id)
);
INSERT INTO parent VALUES (7, 'parent');
In Session A, insert a child row and leave the transaction open:
BEGIN;
INSERT INTO child VALUES (7);
-- Keep the transaction open.
In Session B, try to delete that parent row:
DELETE FROM parent WHERE id = 7;
Session B waits because Session A still holds a key-share lock on parent.id = 7. Once Session A commits, Session B wakes up and continues. With the default NO ACTION rule, Session B’s delete then fails because the child row now references that parent. The lock keeps the insert’s check from overlapping with the parent change, and the foreign-key action decides whether the delete can succeed once the wait ends. You can read more in PostgreSQL’s documentation on referential actions and constraint timing.
The wait goes the other way if the parent change starts first. If Session B deletes the parent row or changes its key and keeps its transaction open, Session A waits during its foreign-key check until Session B finishes. If Session B commits and no matching key remains, PostgreSQL rejects Session A’s insert with a foreign-key violation instead of letting it commit without a matching parent row.
PostgreSQL acquires this lock automatically as part of the foreign-key check, so your application does not need to run SELECT ... FOR UPDATE to trigger it. That automatic check is separate from explicitly locking rows yourself. For that mechanism, see how PostgreSQL SELECT FOR UPDATE locks rows.
Start by checking whether the backend is waiting on a lock. pg_stat_activity shows the running statement and its wait state, and pg_blocking_pids(pid) lists the backends blocking a lock request. Replace the placeholder below with the stalled backend’s PID:
SELECT
pid,
state,
wait_event_type,
wait_event,
pg_blocking_pids(pid) AS blocking_pids,
query
FROM pg_stat_activity
WHERE pid = ;
If wait_event_type is Lock, the backend is waiting for a heavyweight lock. That status alone does not prove a foreign key caused the wait. Compare the waiting statement with what the blocking backend is running and check whether its transaction is still open. PostgreSQL’s documentation for pg_blocking_pids explains how the function identifies blocking backends.
You can inspect held locks in pg_locks, though it does not list every row-level lock. PostgreSQL typically reports a row-lock wait as a wait on the transaction ID of the backend holding that lock. Call pg_blocking_pids() to find the blocking backend instead of joining pg_locks to reconstruct the row-lock wait queue. Then check how long that blocking transaction has been open, because a fast INSERT can finish right away and still hold its lock while later work keeps the transaction open.
If the backend is not waiting on a lock, look elsewhere. A foreign key must point to a unique key, such as a primary key or a column with a unique constraint. When PostgreSQL deletes a parent row or changes its key, it also searches the child table for referencing rows. PostgreSQL does not automatically index the child’s foreign-key columns. Adding an index on those columns can speed up parent-side checks when your workload and query plan justify it, though it does not guarantee faster child inserts. See PostgreSQL’s foreign-key constraint guidance for details.
By default, PostgreSQL checks a foreign key after each command. If you define the constraint as deferrable and declare it INITIALLY DEFERRED, PostgreSQL waits until the end of the transaction to check it. Deferring the check changes when PostgreSQL runs it, but PostgreSQL still enforces the relationship, and concurrent transactions can still run into lock contention.
Large data loads also consume memory for foreign-key checks. As PostgreSQL’s bulk-loading guidance explains, PostgreSQL queues a pending trigger-event entry for every loaded row when the target table already has foreign keys. A very large load can accumulate enough entries to trigger swapping or fail outright. You can split the load into smaller transactions to keep that memory use down, or you can drop the foreign-key constraints before loading and recreate them afterward. While a constraint is dropped, PostgreSQL does not enforce that relationship, so only take that route if your setup can tolerate the temporary gap in enforcement.
Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.
Take a look at vroni.com