liveBook · Manning

Distributed transaction

As explained in PostgreSQL Mistakes and How to Avoid Them

A distributed transaction is an atomic unit of work whose operations execute across multiple database nodes.

A distributed transaction is one atomic unit of work whose operations run on multiple database nodes. PostgreSQL protects transactions within a server, but an application spanning nodes must preserve atomicity itself. section 5.6

The replica-read mistake

Suppose primary alpha changes an account balance from 100 to 90 while standby beta still reports 100. Reading beta and then applying a +50 update on alpha produces 150: the application acted on an inconsistent view and violated the intended business transaction. section 5.6

Two-phase commit can coordinate the operation, but it carries operational costs:

  • Use PREPARE TRANSACTION and associated commands to implement the two phases. section 5.6
  • Keep prepared transactions short-lived; latency and replication lag make them difficult to manage. section 5.6
  • Expect locks and abandoned prepared work after application crashes or restarts. section 5.6
  • Running exclusively on the primary avoids read-replica benefits. section 5.6
CREATE TABLE test.accounts (
    id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    balance numeric NOT NULL,
    updated_at timestamp with time zone DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE

INSERT INTO test.accounts (balance) VALUES (100);
TABLE test.accounts;
INSERT 0 1
 id | balance |         updated_at
----+---------+-----------------------------
  1 |     100 | 2024-01-17 19:08:31.0284+00
(1 row)

Inspect the account setup and follow the primary-versus-standby balance changes that expose the cross-node consistency failure. section 5.6

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Defines the failure, demonstrates stale replica behavior, and introduces 2PC while deferring implementation detail.
Examples
Uses alpha and beta account reads, balance updates, and a stale standby to demonstrate an inconsistent cross-node operation.
What it assumes
Assumes database and ACID fundamentals while clarifying that server-local guarantees do not automatically span nodes.
What you can do after
Diagnose/debug with it by recognizing stale-replica decisions and evaluating whether 2PC costs are acceptable.
How it connects
Connects distributed transactions with ACID, atomicity, consistency, isolation, replication lag, read replicas, and two-phase commit.

Also explained in

Compare how 4 books explain distributed transaction →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.