liveBook · Manning

Streaming replication

As explained in PostgreSQL Mistakes and How to Avoid Them

Streaming replication continuously transfers and replays a database server's write-ahead log changes to another database server.

Streaming replication transfers and replays PostgreSQL write-ahead-log changes from a primary to a standby. It provides reliable native replication, but creates a distributed system whose replicas can expose different points in time. section 5.6

The stale-read account mistake

Suppose alpha is primary and beta is a read-only standby configured with a 60-second apply delay. Beta reports an account balance of 100; alpha then updates it to 90. Before beta catches up, another application request reads 100 from beta and writes 150 to alpha, applying a bonus to stale data. The business loses 10 and grants an unintended 50. PostgreSQL preserves ACID safety within its database operations, but the application has split one logical decision across nodes with inconsistent views. 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 executable account-table setup and the sequence of reads and writes that exposes replication lag. section 5.6

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Demonstrates configured apply delay, divergent query results, and the resulting business error, stopping short of replication internals.
Examples
Uses PostgreSQL alpha and beta nodes, a delayed account standby, balance reads, primary updates, and an erroneous bonus calculation.
What it assumes
Assumes PostgreSQL and transaction fundamentals while clarifying that server-level ACID guarantees do not make cross-node application workflows atomic.
What you can do after
Diagnose stale-read failures by comparing primary and standby results and recognizing application-level consistency violations.
How it connects
Connects streaming replication to logical replication, distributed systems, CAP, PACELC, ACID, replication lag, and read replicas.

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.