ML
Database

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.

November 28, 202610 min readPostgresDatabaseLockingConcurrencyPerformance

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 entire orders table.

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.

SharePostLinkedIn

Reader Discussion

9 replies// weighed in

TopNewestAuthor
Add to the thread
Disagree, agree harder, or share your own experience…
Email instead →markdown okbe kind
  1. Highlighted by author
    Victor Petrov· Senior BackendAgrees

    "removing indexes is the third-year move" — saving this. first year you add, second year you tune, third year you realise half of them have been dead weight slowing every write since that one feature got cut.

    Nov 30, 2026·2 days later
  2. Aya Fujimoto· Database EngineerPushback

    small note on Postgres covering indexes — INCLUDE columns don't get the same treatment as key columns for HOT updates and dedup. people assume index-only scan == free, but the heap visibility map can still send you back to disk. measure first.

    Dec 02, 2026·4 days later
  3. Dan O'Connor· Eng ManagerStory

    N+1 cost us a P1 incident last Black Friday. ONE endpoint was firing 3,400 queries per cart load. Looked fine in dev (3 carts), looked fine in staging (50 carts), production hit 9k QPS to the DB and cardiac arrest. Add load tests.

    Dec 01, 2026·3 days later
  4. Linh Phạm· Java DeveloperAgrees

    @Version optimistic locking is the 80/20 of CRUD apps. genuinely think JPA should make it default-on with a @NoVersion opt-out. the number of last-write-wins races I've debugged in spring boot apps that didn't set it is too damn high

    Dec 03, 2026·5 days later
  5. Mateus Silva· Backend DevAsks

    Q — SELECT FOR UPDATE SKIP LOCKED as a job queue: still a good fit in 2026 or do you reach for a real broker (sqs, rabbit, etc) past a certain QPS? we run ~400 jobs/sec on PG and it's been chill but I'm nervous

    Dec 04, 2026·6 days later
    • Aya Fujimoto· Database Engineer

      We do 11k jobs/sec on PG with SKIP LOCKED + LISTEN/NOTIFY. The thing that breaks first is your job table bloat — set up partman + auto-vacuum tuning before you scale.

      Dec 05, 2026
    • ML
      Minh LeAuthor

      Plus one. The cliff isn't the QPS — it's the visibility-of-dead-rows pattern. SKIP LOCKED holds up if you're disciplined about cleanup.

      Dec 06, 2026
  6. Isabella Costa· Junior EngineerKind words

    saved this. sharing at standup tomorrow — we've had exactly this problem for 2 sprints and nobody on the team had framed it this way 🙏

    Nov 30, 2026·2 days later
  7. Kenta Yamada· Tech LeadAsks

    would love a war-story follow-up. principles are clear; the actual debugging session is where the interesting stuff lives. there's a real shortage of "here's the dashboard, here's the thread we pulled, here's where we got stuck for 90 mins" content.

    Dec 02, 2026·4 days later

Worked on something similar? Email ducminhldm@gmail.com — I read every one. The good ones become future posts.

Comments seeded · live discussion via email