Postgres Foreign Key Locks: Why Missing Child Indexes Cause Table-Level ShareRowExclusiveLocks
Deleting or updating a parent row acquires ShareRowExclusiveLock on child tables when foreign key columns lack indexes, causing massive lock wait queues and cascade transaction aborts. How index coverage and row-level locks prevent concurrency collapse.
In a high-throughput e-commerce platform processing thousands of order cancellations and inventory updates per second, a routine customer purge script caused widespread service disruption. Application API threads waiting on simple DELETE or UPDATE queries timed out by the hundreds, connection pools hit their maximum limits, and Postgres CPU spiked to 100 percent. Diagnostic logs revealed hundreds of transactions blocked on ShareRowExclusiveLock wait events.
The culprit was not a complex multi-table query or an missing primary key, but a missing index on a child foreign key column, forcing Postgres to acquire restrictive table-level locks during parent row deletions.
1. How Foreign Key Verification Works in Postgres
Relational databases guarantee referential integrity: every foreign key reference in a child table must correspond to an existing row in the referenced parent table. When a row in the parent table is deleted or its referenced key updated, Postgres must verify that no child rows violate the foreign key constraint.
Consider the classic customer and orders schema:
CREATE TABLE customers (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
status VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT REFERENCES customers(id) ON DELETE CASCADE,
amount NUMERIC(10, 2) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
When Postgres creates the foreign key constraint, it does not automatically build an index on orders(customer_id). While it creates a unique B-tree index on the parent primary key (customers.id), the child column remains completely unindexed unless the developer explicitly creates one.
2. The Lock Escalation Cascade
When an application executes a deletion on the parent table:
DELETE FROM customers WHERE id = 48210;
Postgres must check the orders table to see if any rows reference customer_id = 48210:
- If an index exists on
orders(customer_id), Postgres uses an index scan to locate matching rows in microseconds. It takes standard row-level locks on the matching child tuples and deletes them (for CASCADE) or aborts (for RESTRICT). - If no index exists on
orders(customer_id), Postgres must execute a full sequential scan across the entireorderstable.
To ensure that concurrent transactions do not insert new rows referencing the deleted customer while the sequential scan runs, Postgres acquires a ShareRowExclusiveLock on the entire child table:
Lock Mode Conflict Matrix:
ShareRowExclusiveLock conflicts with:
- RowShareLock (SELECT FOR SHARE)
- RowExclusiveLock (INSERT, UPDATE, DELETE)
- ShareLock (CREATE INDEX)
- ShareRowExclusiveLock
- ExclusiveLock
- AccessExclusiveLock
Because ShareRowExclusiveLock conflicts directly with RowExclusiveLock, every concurrent INSERT, UPDATE, and DELETE on the orders table is immediately blocked until the parent deletion transaction commits or aborts. If orders has 50 million rows, the sequential scan takes several seconds, queueing up thousands of concurrent customer orders behind the lock.
3. Detecting Missing Foreign Key Indexes
To detect foreign keys that lack supporting indexes before they bring down production, query the Postgres catalog tables pg_constraint, pg_attribute, and pg_index:
SELECT
c.conrelid::regclass AS child_table,
c.conname AS foreign_key_name
FROM pg_constraint c
WHERE c.contype = 'f'
AND NOT EXISTS (
SELECT 1
FROM pg_index i
WHERE i.indrelid = c.conrelid
AND i.indkey[0:(c.conkey[1]-1)] = c.conkey
)
ORDER BY child_table;
Any rows returned by this query represent foreign keys whose parent modifications require sequential scans and table-level lock acquisitions.
4. Remediation Strategies
A. Create Supporting Indexes Concurrently
Add B-tree indexes on all foreign key columns in child tables. Always use the CONCURRENTLY option in production to avoid acquiring an AccessExclusiveLock during index creation:
-- Build index without blocking live writes:
CREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders(customer_id);
B. Composite Foreign Keys and Prefix Matching
If a foreign key consists of multiple columns (e.g. tenant_id, user_id), the supporting index must have the foreign key columns as leading columns. An index on (user_id, tenant_id) cannot efficiently satisfy a foreign key constraint defined on (tenant_id, user_id).
C. Partitioned Tables and Cascade Foreign Keys
On declarative partitioned tables in Postgres 12 and newer, creating a foreign key on the partitioned parent automatically propagates to child partitions. However, verify that index creation is also propagated to each partition so that individual partition scans do not stall.
Summary
Postgres does not create foreign key indexes automatically. A single missing index on a high-cardinality child table turns routine parent deletes into full sequential scans, acquiring table-level ShareRowExclusiveLocks that halt all concurrent write operations. Auditing system catalogs for missing foreign key indexes and indexing child columns concurrently guarantees low-latency constraint validation and high transactional throughput.