Skip to content

Foreign Keys, Isolation Levels & Advanced Locking ​

Foreign Key Index Requirements ​

The rule most teams miss (PostgreSQL): the referenced (parent) column must carry a PRIMARY KEY or UNIQUE constraint, so it is always indexed. The referencing (child) column is not indexed automatically. (MySQL InnoDB differs: it creates an index on the FK column for you when none exists.)

What the missing child index costs:

  • INSERT/UPDATE on the child: the FK check looks the value up in the parent's key index, so a child index does not speed it up (it only adds write cost).
  • DELETE/UPDATE of a parent key: the FK trigger must prove no child row still references it (SELECT ... FOR KEY SHARE on the child). Without a child index this is a sequential scan of the child table; with ON DELETE CASCADE the cascaded delete needs the same lookup.
sql
-- PostgreSQL 18 (psql): runnable as is
CREATE TABLE customers (id BIGINT PRIMARY KEY, name TEXT);
INSERT INTO customers SELECT g, 'c' || g FROM generate_series(1, 20001) g;

CREATE TABLE orders (
  id          BIGINT PRIMARY KEY,
  customer_id BIGINT REFERENCES customers(id),  -- no index is created on this column
  amount      NUMERIC
);
INSERT INTO orders
SELECT g, 1 + (random() * 9999)::INT, random() * 1000
FROM generate_series(1, 2000000) g;
ANALYZE orders;

-- Customer 20001 has no orders, but the FK trigger still has to prove it.
BEGIN;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) DELETE FROM customers WHERE id = 20001;
ROLLBACK;

-- Fix. CONCURRENTLY does not block writes on orders (cannot run inside a transaction block).
CREATE INDEX CONCURRENTLY idx_orders_customer ON orders(customer_id);

BEGIN;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) DELETE FROM customers WHERE id = 20001;
ROLLBACK;

Measured (postgres:18 in Docker on a dev machine, 2M child rows; your numbers will differ):

text
Without idx_orders_customer:  Trigger for constraint orders_customer_id_fkey: calls=1   Execution Time: 57.286 ms
With    idx_orders_customer:  Trigger for constraint orders_customer_id_fkey: calls=1   Execution Time:  0.231 ms
Bulk insert of the 2M orders:  9.1 s without the child index, 12.1 s with it (index maintenance cost)

The gap grows with child-table size and with long transactions, because the trigger scan also locks the matching child rows. Adding an FK to an existing large table: ALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID; then ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk; (a plain ADD FOREIGN KEY blocks writes while it validates every row).


Isolation Levels & Index Access Patterns ​

PostgreSQL 18MySQL 8.4 InnoDB
DefaultREAD COMMITTEDREPEATABLE READ
READ UNCOMMITTEDaccepted but behaves as READ COMMITTEDreal (dirty reads)
REPEATABLE READsnapshot isolation; snapshot fixed at the first non-transaction-control statement; no phantoms; a conflicting concurrent update fails with 40001consistent-read snapshot; locking reads (FOR UPDATE, UPDATE, DELETE) take next-key (record + gap) locks on the index range they scan
SERIALIZABLESSI: no extra blocking, 40001 on a dangerous dependency cycle, the application must retrywith autocommit off, plain reads become locking reads (SELECT ... FOR SHARE), so readers block writers

READ COMMITTED in PostgreSQL: every statement sees the data committed when that statement started. A row-locking statement that meets a row changed by a concurrent transaction waits, then re-evaluates the row's current version against its WHERE clause (and skips it if it no longer matches).

sql
-- PostgreSQL 18, Phiên A (setup trong DATABASE RIÊNG, vì bảng orders của khối FK phía trên có cột khác: CREATE TABLE orders(id BIGINT PRIMARY KEY, status TEXT);
-- INSERT INTO orders SELECT g, 'pending' FROM generate_series(1, 1000) g;)
BEGIN;
SELECT * FROM orders WHERE status = 'pending' FOR UPDATE;   -- locks 1000 rows
-- keep this transaction open, run Phiên B, then:
COMMIT;
sql
-- PostgreSQL 18, Phiên B (run while Phiên A is open)
UPDATE orders SET status = 'shipped' WHERE id = 500;        -- waits for Phiên A's row lock
-- Đã chạy trên PostgreSQL 18: B chờ khoảng 2 s (đến khi A COMMIT) rồi cập nhật thành công; `pg_blocking_pids` của B có đúng một pid (A), `wait_event_type = Lock`.
-- Re-check chỉ xảy ra với điều kiện trong WHERE của B: nếu A đổi status của hàng 503 thành 'done' thì
-- UPDATE orders SET status = 'shipped' WHERE id = 503 AND status = 'pending'; cập nhật 0 hàng (đã chạy),
-- còn WHERE id = 500 chỉ lọc theo id nên B vẫn ghi đè status dù A đã đổi nó (đã chạy).

Find who blocks whom: SELECT pid, pg_blocking_pids(pid), wait_event_type, query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0; and set lock_timeout for sessions that must not wait forever.


SERIALIZABLE Range Locking ​

PostgreSQL SERIALIZABLE (SSI) does not block. It records predicate locks (SIReadLock) on what a transaction read, at tuple, then index-page, then whole-relation granularity (promoted when max_pred_locks_per_transaction and related limits are exceeded; a sequential scan takes a relation-level lock). A transaction is cancelled with SQLSTATE 40001 only when these read/write dependencies form a dangerous cycle, and the failure can surface at COMMIT. A lone writer that touches rows another transaction read does not fail by itself.

sql
-- PostgreSQL 18 (psql): setup, runnable as is
CREATE TABLE o2 (id BIGINT PRIMARY KEY, customer_id INT, status TEXT);
CREATE INDEX ON o2(status);
INSERT INTO o2 SELECT g, g % 100, CASE WHEN g % 10 = 0 THEN 'pending' ELSE 'done' END
FROM generate_series(1, 10000) g;
ANALYZE o2;

Case 1: one reader, one writer. Both commit (measured).

sql
-- PostgreSQL 18, Phiên A
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM o2 WHERE status = 'pending';   -- 1000
SELECT pg_sleep(3);
COMMIT;                                              -- succeeds
sql
-- PostgreSQL 18, Phiên B (start about 1 s after Phiên A)
BEGIN ISOLATION LEVEL SERIALIZABLE;
INSERT INTO o2 VALUES (99999, 1001, 'pending');      -- no wait, no error
COMMIT;                                              -- succeeds

Case 2: both read the same range, then each writes into it. One of them fails at COMMIT (measured).

sql
-- PostgreSQL 18, Phiên A and Phiên B run the same script with a different id (88881 / 88882), started together
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM o2 WHERE status = 'pending';
SELECT pg_sleep(2);
INSERT INTO o2 VALUES (88881, 1, 'pending');         -- use 88882 in Phiên B
COMMIT;
text
ERROR:  could not serialize access due to read/write dependencies among transactions
DETAIL:  Reason code: Canceled on identification as a pivot, during commit attempt.
HINT:  The transaction might succeed if retried.

Inspect predicate locks while a SERIALIZABLE transaction is open: SELECT locktype, relation::regclass, mode, count(*) FROM pg_locks WHERE mode = 'SIReadLock' GROUP BY 1, 2, 3; (index-page and relation locks appear).

Detecting serialization failures: pg_stat_database has no counter for them (its deadlocks column counts deadlocks only, and pg_stat_database_conflicts counts replication-standby query conflicts, not SQLSTATE 40001). Count 40001 in the application metrics or in the server log (log_min_error_statement), and always wrap SERIALIZABLE transactions in a retry loop. Many failures mean the read sets are too wide: use narrower indexed predicates, shorter transactions, or READ COMMITTED with explicit SELECT ... FOR UPDATE where that is enough.


Phantom Reads & Index Gaps ​

PostgreSQL REPEATABLE READ does not show phantoms: every query in the transaction reads the snapshot taken at its first statement, indexed or not (measured below). MySQL InnoDB REPEATABLE READ also gives a stable snapshot for plain SELECT, but protects a locking read with next-key locks, so a concurrent insert into the scanned index range waits instead of being merely invisible.

sql
-- PostgreSQL 18, Phiên A (setup: the o2 table from "SERIALIZABLE Range Locking")
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM o2 WHERE status = 'pending';   -- 1000
SELECT pg_sleep(3);
SELECT count(*) FROM o2 WHERE status = 'pending';   -- still 1000
COMMIT;
sql
-- PostgreSQL 18, Phiên B (start about 1 s after Phiên A)
INSERT INTO o2 VALUES (99999, 1001, 'pending'), (99998, 1002, 'pending');   -- commits immediately
sql
-- MySQL 8.4, Phiên A (setup: CREATE TABLE o2 (id BIGINT PRIMARY KEY, customer_id INT, status VARCHAR(20), KEY idx_status (status)) ENGINE=InnoDB; with 1000 rows, 100 of them 'pending')
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
START TRANSACTION;
SELECT COUNT(*) FROM o2 WHERE status = 'pending' FOR UPDATE;   -- 100
SELECT lock_type, lock_mode, COUNT(*) FROM performance_schema.data_locks WHERE object_name = 'o2' GROUP BY lock_type, lock_mode;
-- keep the transaction open, run Phiên B, then COMMIT;
sql
-- MySQL 8.4, Phiên B (run while Phiên A is open)
SET SESSION innodb_lock_wait_timeout = 2;
INSERT INTO o2 VALUES (9001, 1, 'pending');
-- ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

Measured on mysql:8.4: data_locks showed 1 table IX lock and 101 RECORD X locks (next-key locks covering the pending entries plus the gap after the last one), and the insert timed out. PostgreSQL never blocks the insert; it only hides it from the older snapshot (and under SERIALIZABLE may cancel one transaction, see the previous section).

Phải nhớ

  • PostgreSQL does not create an index on the FK child column; add one (CREATE INDEX CONCURRENTLY) when you delete or update parent keys or join through the FK. InnoDB creates it automatically.
  • PostgreSQL: READ COMMITTED default, REPEATABLE READ has no phantoms, SERIALIZABLE never blocks but needs a retry loop for 40001. MySQL: REPEATABLE READ default, locking reads take next-key locks that block inserts into the range.
  • Add an FK to a big table with NOT VALID, then VALIDATE CONSTRAINT, so writes are not blocked during validation.