Skip to main content
cd ../lexicon
sys/docs/lexicon/phantom-read-anomaly-serializable-isolation.md
Lexicon

Phantom Read Anomaly (Serializable Isolation)

Difficulty: Advanced
2 min read
Definition
A database isolation anomaly where a transaction sees different rows when re-executing the same query due to concurrent insertions or deletions.

Phantom reads occur when a transaction T1 executes a range query (e.g., SELECT * WHERE age > 25) and later re-executes the same query within the same transaction, but observes additional rows (phantoms) that were inserted by a concurrent transaction T2 that committed between T1’s query executions. Unlike non-repeatable reads which affect existing rows, phantom reads involve the appearance or disappearance of entire row sets matching predicate conditions.

The fundamental challenge lies in predicate locking—traditional row-level locks cannot prevent phantoms because the conflicting rows didn’t exist during the initial query. Database systems implement phantom prevention through techniques like next-key locking (gap locks + record locks in InnoDB), predicate locks on index ranges, or serialization conflict detection in snapshot isolation variants like PostgreSQL’s SSI. In distributed databases, phantom prevention becomes significantly more complex due to the need for distributed predicate coordination across multiple nodes and the interaction with distributed consensus protocols.

Phantom anomalies are particularly insidious in financial systems and inventory management where aggregate calculations must remain consistent throughout a transaction’s lifetime. For instance, a bank transfer system calculating account balances while concurrent transactions create new accounts could observe inconsistent totals, leading to constraint violations or audit failures. Modern systems like CockroachDB and FoundationDB provide serializable isolation by default specifically to prevent phantom reads, though at significant performance costs due to increased contention and abort rates.

The prevention of phantom reads represents one of the most expensive aspects of true ACID compliance, as it requires either extensive locking mechanisms that can severely limit concurrency, or sophisticated conflict detection algorithms that may force frequent transaction retries. This trade-off between correctness and performance drives many distributed systems to offer weaker isolation levels as default configurations, leaving phantom read prevention as an opt-in capability for applications that absolutely require serializable semantics.