# Transactions Deep Dive: MVCC, Locks, Isolation, and Two-Phase Commit


**Database Pipelines — Part 3/5**

Part 2 showed row versions in heap pages and commits riding the WAL. **Transactions** are the programming model on top: reads and writes that succeed together or not at all, while other sessions run. This part covers **ACID**, **isolation**, **MVCC**, **two-phase locking (2PL)** ideas, and **two-phase commit (2PC)** for multi-participant atomicity. Still using customers/orders. Concepts are engine-generic; syntax leans on **PostgreSQL**.

This is **Part 3 of 5** in the Database Pipelines series.

## Three different “two-letter” ideas

![MVCC and 2PL for local concurrency vs 2PC for distributed commit](https://cdn.hashnode.com/uploads/covers/6ae9f3d1eac8486c74422bf9/1bfff8ff-379f-429c-9219-e4953d284cb5.png)

People conflate mechanisms that solve different problems:

| Mechanism | Problem it addresses |
| --- | --- |
| **MVCC** | Which **row versions** a reader may see without blocking every writer |
| **2PL** (two-phase locking) | Classical lock acquire/release discipline so concurrent schedules stay serializable-ish |
| **2PC** (two-phase commit) | Whether **multiple participants** all commit or all abort as one global decision |

PostgreSQL leans on **MVCC** for ordinary reads, still uses **locks** for writers and some reads (`FOR UPDATE`), and implements **2PC** mainly for external transaction managers via `PREPARE TRANSACTION`—**not** as the default app coding style.

## ACID in practice

- **Atomicity.** `BEGIN` … `COMMIT` applies all bounded local writes, or `ROLLBACK` applies none.
- **Consistency.** Declared constraints still hold after commit.
- **Isolation.** Concurrent transactions interact only as allowed by the isolation level.
- **Durability.** After commit, effects survive crashes because WAL said so (Part 2).

```sql
BEGIN;

UPDATE orders
SET status = 'paid'
WHERE order_id = 1001
  AND status = 'pending';

INSERT INTO payments (order_id, amount_cents)
VALUES (1001, 4999);

COMMIT;
```

(Assume a `payments` table in a real schema.) This is a **local** transaction—one PostgreSQL database—not 2PC.

## Isolation levels

SQL isolation levels trade anomalies for concurrency. Stricter levels forbid more anomalies, often with more conflicts or retries.

| Level | Rough promise |
| --- | --- |
| Read Uncommitted | May allow dirty reads; many engines effectively upgrade this |
| Read Committed | See committed data; successive selects may see new commits |
| Repeatable Read | Stable view of already-read data (engine-specific details) |
| Serializable | Appear to run one-after-another |

**PostgreSQL:** default is **Read Committed**. `REPEATABLE READ` uses a transaction snapshot. `SERIALIZABLE` may abort with a serialization failure you must retry. Dirty reads are not offered the way the loosest SQL label suggests—read the [transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html) chapter rather than assuming MySQL-like behavior.

For the Fairfax report while another session marks orders paid: Read Committed can return different sets on two selects in one transaction; a snapshot isolation mode keeps one view for the transaction.

## MVCC: versions and snapshots

![MVCC: writers create versions; readers choose by snapshot](https://cdn.hashnode.com/uploads/covers/6ae9f3d1eac8486c74422bf9/27c51d59-027d-4223-ad37-0625b40c74e5.png)

**MVCC** keeps multiple row versions (Part 2). Each transaction uses a **snapshot** (statement- or transaction-scoped) to decide visibility.

In PostgreSQL, fields such as `xmin` / `xmax` record which transactions created or expired a version. Readers skip invisible versions instead of always waiting on writers—while writers may still block writers, and some modes add extra checks.

Implications: long transactions delay vacuum; “I updated status but the report lags” is often isolation timing; hot rows churn versions.

## Locks remain necessary

MVCC does not remove locking. Row locks serialize writers on the same `order_id`. `SELECT … FOR UPDATE` pins rows for payment capture. Foreign keys lock parents. Deadlocks abort one side—retry with backoff.

```sql
BEGIN;
SELECT * FROM orders WHERE order_id = 1001 FOR UPDATE;
UPDATE orders SET status = 'paid' WHERE order_id = 1001;
COMMIT;
```

Classical **2PL** says: grow the lock set, then shrink—no lock–unlock–lock patterns that break serializability proofs. Real engines mix MVCC with selective locking rather than textbook 2PL alone; the label is still useful when reading concurrency literature.

## Two-phase commit (2PC)

![Two-phase commit: prepare votes, commit or abort, in-doubt on failure](https://cdn.hashnode.com/uploads/covers/6ae9f3d1eac8486c74422bf9/3a0e21df-02cd-480e-8f89-de3c20b28a0b.png)

When **one business commit** must span **more than one transactional resource** (two databases, database + message queue with XA, etc.), local `COMMIT` is not enough. **2PC** introduces a **coordinator** and **participants**:

### Phase 1 — Prepare

1. Coordinator asks each participant to **prepare**.
2. Each participant does everything that might still fail for commit: flush enough state that it can promise “I can commit or abort on command,” and records a **durable prepared** vote.
3. Participant answers **yes** (prepared) or **no**.

If any vote is no (or times out before prepare completes), the coordinator instructs everyone that is not prepared—or that can still abort—to **abort**.

### Phase 2 — Commit or abort

- If **all** required participants voted yes, the coordinator records its global decision and sends **commit** (`COMMIT PREPARED` in PostgreSQL).
- Otherwise it sends **abort** (`ROLLBACK PREPARED`).

After a participant has **entered prepared state**, it must not unilaterally forget the transaction: it is **in doubt** until the coordinator’s decision arrives. It may hold locks and block vacuum (PostgreSQL warns about this explicitly).

### Failure, blocking, and operations

- Crash **before** prepare completes: treat like local abort paths.
- Crash **after** prepare, **before** the participant learns the outcome: on restart the participant must **ask the coordinator** (or a transaction log) what to do. This is the classic **blocking** downside of basic 2PC: a missing coordinator stalls prepared work.
- **Do not assume** “coordinator timeout ⇒ safe to abort after prepare.” Once prepared, aborting without the global decision can fork reality (one side committed, one aborted). Timeouts before prepare are different from timeouts after prepare.
- Prepared transactions that linger interfere with cleanup and can contribute toward wraparound risk in PostgreSQL—resolve them quickly.

### PostgreSQL: `PREPARE TRANSACTION` is not normal app default

```sql
BEGIN;
-- local statements on this database
PREPARE TRANSACTION 'orders-pay-1001';
-- later, usually from a transaction manager:
COMMIT PREPARED 'orders-pay-1001';
-- or ROLLBACK PREPARED 'orders-pay-1001';
```

Official docs state this is for **external transaction managers**, not interactive apps. Default `max_prepared_transactions = 0` disables the feature until you opt in. Ordinary services should prefer **single-database transactions**, **outbox patterns**, or **sagas** unless they truly run a TM.

2PC is **not** a substitute for MVCC, and MVCC is **not** distributed atomic commit.

## Bridging back to the Fairfax query

```sql
SELECT c.email, o.order_id, o.total_cents
FROM customers AS c
JOIN orders AS o
  ON o.customer_id = c.customer_id
WHERE c.city = 'Fairfax'
  AND o.status = 'paid'
  AND o.created_at >= TIMESTAMP '2026-01-01';
```

Under Read Committed, each statement sees newly committed data. Under a transaction snapshot, the join is stable for the txn. Neither replaces correct **write** transactions—or 2PC when payment authorization lives in another system that must commit atomically with `orders`.

## What to practice

1. Keep multi-step local writes in explicit transactions.
2. Choose isolation for reader correctness; retry serialization failures.
3. Keep transactions short so versions and locks clear.
4. Reach for 2PC only with a real coordinator and monitoring for in-doubt txns—not as a default ORM setting.

## Limits and next

Distributed sagas and every SQL anomaly name are out of scope. Part 4 turns to **caching**: buffer pools, OS cache, cache-aside, invalidation, and stampede control—without treating every engine the same.

## References

- [PostgreSQL Documentation: Transaction Isolation](https://www.postgresql.org/docs/current/transaction-iso.html)  
- [PostgreSQL Documentation: Concurrency Control (MVCC)](https://www.postgresql.org/docs/current/mvcc.html)  
- [PostgreSQL Documentation: Explicit Locking](https://www.postgresql.org/docs/current/explicit-locking.html)  
- [PostgreSQL Documentation: PREPARE TRANSACTION](https://www.postgresql.org/docs/current/sql-prepare-transaction.html) — 2PC participant API; not for ordinary apps  
- [PostgreSQL Documentation: Two-Phase Transactions](https://www.postgresql.org/docs/current/two-phase.html)  
- [PostgreSQL Documentation: COMMIT PREPARED](https://www.postgresql.org/docs/current/sql-commit-prepared.html)  

---

## About the author

I write about Applied AI, MCP, Azure AI Search, and RAG. Follow me on [Dev.to](https://dev.to/who_ai) and [Hashnode](https://hashnode.com/@whoai) for more.

