This resume is also available in English.

6. Deploying the system13 / 14 · All columns

Columns › 6. Deploying the system › Part 40

PostgreSQL Read/Write Splitting: Replication Lag, Routing and What to Watch For

PostgreSQL 讀寫分離:複寫延遲、路由與要小心的地方

Read/write splitting sends reads to read-only replicas, at the price of replicas always being a little behind the primary. This article covers streaming replication and synchronous_commit, measuring lag, reading your own writes, routing options, query conflicts on standbys, failover, replication slots and monitoring.

  • 資料庫
  • PostgreSQL
  • 讀寫分離
  • Go
In this article
  1. What this article solves
  2. Step 1: Make sure read/write splitting is the right fix
  3. Step 2: How streaming replication works
  4. Step 3: Asynchronous and synchronous, the five synchronous_commit levels
  5. Step 4: Measuring replication lag
  6. Step 5: Reading your own writes
  7. Step 6: Two pools and LSN waiting in Go
  8. Step 7: If a read leads to a write, read on the primary
  9. Step 8: Where to put the routing
  10. Step 9: Long queries and query conflicts on replicas
  11. Step 10: Failover, split brain and replication slots
  12. Step 11: Connection pools, monitoring and alerts
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

The previous article, “Using Redis Well: Caching, Counters, Locks and the Pitfalls”, used a cache to absorb a large number of repeated reads. Not every read belongs in a cache, though: the order list has too many filter combinations, back-office queries differ every time, and reports scan large amounts of data. These reads still end up at the database. When most of the primary's CPU and I/O goes on reads like these, the next common step is read/write splitting: add one or more read replicas, keep sending writes to the primary, and move reads that can tolerate a little staleness to the replicas. This article explains how that works in PostgreSQL, when it is worth doing, when it is not, and the places where it most often goes wrong.

What this article solves

During a promotion, the database behind the order service of the series' shop (example.com/shop, with the services api-gateway, order, payment and inventory) sat above 90% CPU for hours. A look at pg_stat_statements, introduced in “Adding Indexes Safely: Indexing Large Tables Without an Outage”, showed that writes accounted for little more than a tenth of the total time; the rest was the "my orders" list, order details, customer-service searches and the morning operations report. Indexes had already been fixed and popular products were already in Redis, so the team added a streaming replica and moved the reads to it. CPU came down, and then a series of new problems appeared:

  • After placing an order, users were redirected to the order details page, which said "order not found"; a refresh made it appear.
  • The payment result page said "awaiting payment", and some users paid a second time.
  • Some inventory code read the stock level from the replica, decided there was enough, and then decremented it on the primary; during the promotion it oversold.
  • The operations report was cancelled halfway through with canceling statement due to conflict with recovery.
  • One day the replica's machine died unnoticed, and two days later the primary's disk filled up with WAL and ordering stopped altogether.

None of this is PostgreSQL's fault. It is what read/write splitting comes with: a replica is always a little behind the primary, and it is another machine that can break, be slowed down, and affect the primary. This article goes through:

  1. Which situations suit read/write splitting and when not to do it.
  2. How streaming replication works and what a replica cannot do.
  3. The five synchronous_commit levels, what each waits for and what it costs.
  4. How to measure replication lag, and two metrics that are easy to misread.
  5. Four ways to read your own writes, and where each fits.
  6. A Go implementation (pgx v5) with two pools and LSN waiting, tested against a real primary and replica.
  7. Why a read that leads to a write must happen on the primary.
  8. Routing in the application, in the connection string or in a proxy.
  9. Long queries on replicas and query conflicts.
  10. Failover, split brain and replication slots.
  11. Connection pools, monitoring and alerts.

The SQL and error messages in this article were all run on PostgreSQL 17 with one primary and one replica (streaming replication set up with pg_basebackup -R).

Step 1: Make sure read/write splitting is the right fix

Read/write splitting solves something specific: most of the primary's load comes from reads, and those reads can accept data that is a few hundred milliseconds to a few seconds old. It does not make writes faster and it does not make a badly written query faster; it only runs the same queries on a different machine.

Where it fits:

  • Many reads, few writes, with enough reads that one machine's CPU or memory is not enough. Product pages, order lists, search and back-office queries are typical.
  • Reads that tolerate lag. If a new order shows up in "my orders" a second late, users rarely notice; a product review appearing two seconds late does not matter.
  • Heavy but non-urgent queries, such as reports, exports and analysis. Isolating them on a dedicated replica stops them competing with online transactions.
  • You need a replica anyway. A standby kept for high availability is idle most of the time, so letting it take some reads comes almost for free.

Where it does not fit, or where something else comes first:

SymptomWhy a replica does not helpDo this first
A few queries take most of the timeA slow query is just as slow on another machineFind the missing indexes and rewrite the queries, as in “Adding Indexes Safely: Indexing Large Tables Without an Outage”
The same data is read again and againThe replica runs it every time as wellCache it, see “Using Redis Well: Caching, Counters, Locks and the Pitfalls”
The bottleneck is writes (WAL, locks, hot UPDATE rows)Every write runs on the primary and is replayed again on every replicaWrite less, batch, separate hot and cold data, and shard only as a last resort
The database is small and fits in memoryAnother machine to run for very little gainTune the primary's size, connection count and queries first
Most reads must be "definitely current"Those reads end up back on the primaryCheck whether they really need to be current; if they do, a replica can take very little
Running out of connectionsThe problem is too many connections, not too many queriesPools and PgBouncer, see “database/sql, Transactions and Connection Pools in Go”

The costs to include: another machine (usually several), another set of pools, application code that decides where each query goes, a new class of "inconsistent data" bugs, and several ways in which a troubled replica affects the primary (steps 9 and 10). These costs are worth paying once you have confirmed that the bottleneck really is reads.

Step 2: How streaming replication works

Every change in PostgreSQL is first written to the WAL (write-ahead log), which is what lets it recover after a crash. Streaming replication sends that log to another machine as it is written, and that machine keeps "replaying" the same changes:

order service writes and reads Primary Standby Data files WAL (log first) walsender Replay to data files WAL written, flushed walreceiver write WAL write / flush replay Read-only queries see only what has been replayed A successful commit only means the primary flushed it; by default nobody waits for replay

Figure: the application writes to the primary and the change goes to the WAL first; the primary's walsender streams the WAL to the standby's walreceiver, which writes and flushes it and then replays it into the data files. Queries on the standby can only see what has been replayed.

The terms map onto the columns used later:

  • write: the standby has received the WAL and handed it to the operating system.
  • flush: the standby has written the WAL to durable storage.
  • replay (apply): the standby has applied the WAL's changes to its data; queries only see the replayed part.

Each position is an LSN (log sequence number), such as 0/4774028: a byte position in the WAL that can be compared directly, and subtracted to get the distance in bytes.

This is physical replication: the replica is a byte-for-byte copy of the primary, with every database, every table and every index. That brings some limits: primary and replica must run the same PostgreSQL major version; you cannot create extra tables or indexes on the replica (an index "just for reports on the replica" is not possible; it has to be built on the primary and then every replica has it); and hot_standby, which is on by default, is what lets the replica accept read-only queries. Replicating only some tables, or adding indexes on the destination, is the territory of logical replication, which this article does not cover.

The simplest way to create a replica is pg_basebackup:

pg_basebackup -h primary.db.internal -U replicator \
  -D /var/lib/postgresql/data -X stream -R -C -S replica1

-R writes standby.signal and a primary_conninfo pointing back at the primary, so the data directory starts up as a replica; -C -S replica1 also creates a replication slot named replica1 on the primary (step 10 covers its benefits and risks). The primary needs a role with the REPLICATION attribute, and pg_hba.conf must allow replication connections.

Every transaction on a replica is read-only. Running these on our replica gave the following errors:

INSERT INTO orders ...           → ERROR:  cannot execute INSERT in a read-only transaction
SELECT nextval('order_no_seq')   → ERROR:  cannot execute nextval() in a read-only transaction
CREATE TEMP TABLE t (x int)      → ERROR:  cannot execute CREATE TABLE in a read-only transaction
LISTEN order_paid                → ERROR:  cannot execute LISTEN during recovery
SELECT ... FOR UPDATE            → ERROR:  cannot execute SELECT FOR UPDATE in a read-only transaction

This list decides which code cannot move to a replica: anything that takes a sequence value, reports that create temporary tables, background jobs that wait on LISTEN, and queries that lock rows. In pgx the error carries SQLSTATE 25006 (read_only_sql_transaction). Seeing it almost always means a routing bug, and it deserves its own alert.

Step 3: Asynchronous and synchronous, the five synchronous_commit levels

By default streaming replication is asynchronous: the primary reports "committed" once the WAL is flushed locally, without waiting for any replica. So there is always a gap between "committed" and "visible on the replica". That gap is replication lag.

Making the primary wait for a replica takes two settings together: synchronous_standby_names lists which replicas are synchronous, and synchronous_commit decides how far a commit waits.

Which step must finish before the commit returns WAL written Primary flush Standby write Standby flush Standby replay off local remote_write on remote_apply Without synchronous_standby_names, local, remote_write and remote_apply all behave like on

Figure: at commit, off waits for nothing; local waits for the primary's flush; remote_write also waits for the synchronous standby's write; on waits for its flush; remote_apply waits until it has replayed. The longer the wait, the higher the latency.

LevelWhat the commit waits forCan data be lost if the primary crashes?Visible on the sync standby at once?Suits
offNot even the local flushA short stretch of transactions already reported as committed may disappearNoData that can be recomputed, such as statistics
localLocal flushNot while the primary's disk survives; failing over may lose the latest onesNoIndividual unimportant transactions when a sync standby exists
remote_writeSync standby has received it and written it to the OSOnly if the standby's operating system also crashesNoSynchronous replication with lower latency
on (default)Sync standby has flushed itOnly if the primary and every sync standby lose their storageNoMoney and other data that must not be lost
remote_applySync standby has replayed itSame as onYesA few transactions that must be readable on the replica straight away

Things to watch:

  • Without synchronous_standby_names, only on and off differ; local, remote_write and remote_apply all behave like on, which only waits for the local flush. Many people assume remote_apply gives them current reads when no replica has been listed as synchronous at all.
  • synchronous_commit can be set for a single transaction: SET LOCAL synchronous_commit = remote_apply inside a transaction makes only that one wait. That lets the whole site stay asynchronous and pay the waiting cost only for a few critical writes.
  • If the synchronous standby stops, commits stop. We paused replay on the only synchronous standby and committed an order with remote_apply; the session had statement_timeout = '2s', yet the commit hung for more than two minutes and only finished once replay resumed. statement_timeout does not interrupt this wait. So synchronous replication needs at least two candidate standbys, for example synchronous_standby_names = 'ANY 1 (replica1, replica2)', where a reply from either counts.
  • The replica you read from must be the synchronous one. With ANY 1 (replica1, replica2), remote_apply only guarantees that one of them has replayed; reading the other may still return old data.

The upshot: replicas used for read/write splitting usually stay asynchronous, and the application's routing deals with lag (step 5). Synchronous replication is mainly about not losing data, not about consistent reads.

Step 4: Measuring replication lag

Lag has two dimensions: how much data behind (bytes) and how long behind (time). On the primary, for each replica:

SELECT application_name, client_addr, state, sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_bytes,
       write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

On the replica, about itself:

SELECT pg_is_in_recovery(),
       pg_last_wal_receive_lsn(),
       pg_last_wal_replay_lsn(),
       pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn()) AS behind_bytes,
       now() - pg_last_xact_replay_timestamp() AS replay_age;

write_lag, flush_lag and replay_lag are the time from "the primary flushed some WAL" to "the replica reported it written / flushed / replayed". Each set of numbers has one easy misreading, and we reproduced both:

  1. When replay is stuck, replay_lag can look perfectly normal. We stopped replay on the replica with pg_wal_replay_pause() and then inserted a thousand rows on the primary. Three seconds later replay_bytes was 165368 bytes and the replica was clearly serving old data, yet replay_lag showed about 1 millisecond. The official documentation explains that these columns are "how long the most recently reported position took", not "how far behind it is now"; once fully caught up with no new WAL, they turn NULL after a while. So alert mainly on the byte difference, and treat the time columns as supporting information.
  2. When the primary is idle, now() - pg_last_xact_replay_timestamp() keeps growing. It measures from the primary's commit time of the last replayed transaction to now. The replica was fully caught up, but the primary had been idle for 17 seconds, so it showed 17 seconds. Alerting on it alone causes false alarms at night when traffic is low; combine it with pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn(), which means nothing is outstanding.
MetricWhereAnswersNote
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)PrimaryHow many bytes each replica is behindMost reliable; use it as the main alert
replay_lagPrimaryHow long recent WAL took to be replayedCan stay at an old value while replay is stuck
state, sync_statePrimaryIs the replica streaming, is it synchronousA disconnected replica's row disappears; alert on the row count
pg_last_wal_receive_lsn() vs pg_last_wal_replay_lsn()ReplicaReceived but not yet replayedReceiving fine but replaying slowly often means a query conflict is waiting
now() - pg_last_xact_replay_timestamp()ReplicaHow old the last replayed transaction isGrows while the primary is idle; never alert on it alone

Lag usually comes from: a burst of writes on the primary (large batch UPDATEs, index builds, VACUUM FULL), replica I/O that cannot keep up, network bandwidth, and the query conflicts of step 9 pausing replay. Pausing between batches and sizing batches by lag is the most direct prevention; the archiving job in “Hot and Cold Data, Sharding and Splitting Databases: What to Do When the Data Grows” does exactly that.

Step 5: Reading your own writes

The most common read/write splitting bug is users not seeing what they have just written:

User order service Primary Standby POST /orders INSERT + COMMIT OK 302 → /orders/1001 GET /orders/1001 SELECT … id = 1001 0 rows (not replayed yet) 404 order not found WAL replayed later

Figure: the order is written and committed on the primary and the page immediately redirects to the order details; that read goes to the replica, which has not replayed the order yet, so the answer is "not found". A few hundred milliseconds later the same read works.

In the shop it shows up in several forms:

  • The details page after placing an order: the new order is "not found", or the cart has been emptied but the order list has no new order.
  • The payment result page: payment receives the gateway's notification and marks the payment as successful, the user is sent back to the result page, and the result page reads "awaiting payment" from the replica, so the user presses pay again. This is far more serious than a missing order.
  • Forms after editing: the user changes the delivery address, saves, and the page shows the old address, so they assume it was not saved and change it again.

The problem only happens "just after the write", and it only affects "the person who wrote". So the fix is not to send every read to the primary, but to send only the reads that need it to the primary, or wait for the replica to catch up. The four common approaches:

ApproachHowSuitsWhy it is neededNot for
Stick to the primary for a while after a writeRecord the write time in the session; for N seconds that user's reads go to the primaryOrdinary "edit, then view the result" pages; cheapest to buildNeeds no knowledge of the replica; time alone covers most casesSystems whose lag often exceeds N seconds; users who write constantly stay on the primary
Wait for the replica to replay the write's LSNRecord the primary's LSN after the write; before reading, check the replica's pg_last_wal_replay_lsn() has passed itReading right after placing an order or editing, while still using the replica as much as possiblePrecise: the replica is used as soon as it has caught up, no guessing how longAdds a query to each read; if the replica is persistently behind, every read wastes the wait
Always read critical data from the primaryChosen in code, e.g. payment results, balances, stock decisionsReads where a wrong answer costs money or causes a repeated actionCorrect regardless of how small the lag isHigh-volume reads; marking everything critical means no splitting at all
remote_apply for a few transactionsSET LOCAL synchronous_commit = remote_apply; commit waits for the sync standby's replayA write that is always read back from one fixed replica, at low write volumeNo change needed on the read sideCommits hang when the replica has trouble; with several replicas it cannot guarantee which one you read

In practice they are combined: payment results, stock and balances always come from the primary; ordinary "write then view" reads use a time window plus LSN waiting; everything else goes straight to replicas.

The LSN waiting flow:

Write and commit (primary) Save pg_current_wal_lsn() Store in session (cookie/Redis) next request Next read Within 5 s of the write? Read replica no yes Replica replayed past the write LSN? yes still behind after 200 ms Read primary ask every 10 ms

Figure: after a write commits, the primary's LSN is stored in the session; a later read inside the time window asks the replica how far it has replayed, uses the replica once it has caught up, and after waiting at most 200 milliseconds falls back to the primary.

Two details:

  • The "session" must live somewhere every service instance can see. The user's next request will probably be sent by api-gateway to a different order instance, so the write time and LSN belong in a (signed) cookie or in Redis, not in one process's memory.
  • The time window must be longer than the lag alert threshold. Reads outside the window go straight to the replica, on the assumption that lag is normally far below the window; once lag crosses the threshold, that replica should be taken out of the read rotation (step 11), rather than letting users outside the window read old data.

Step 6: Two pools and LSN waiting in Go

Here are the rules of step 5 as a small package. First, parsing an LSN: PostgreSQL prints pg_lsn as high32/low32, and once converted to uint64 it can be compared directly.

package dbroute

import (
	"fmt"
	"strconv"
	"strings"
)

// LSN is a position in the WAL. PostgreSQL prints it as "16/B374D848":
// the high and low 32 bits of a 64-bit number, in hexadecimal.
type LSN uint64

func ParseLSN(s string) (LSN, error) {
	hi, lo, ok := strings.Cut(s, "/")
	if !ok {
		return 0, fmt.Errorf("lsn %q: missing slash", s)
	}
	h, err := strconv.ParseUint(hi, 16, 32)
	if err != nil {
		return 0, fmt.Errorf("lsn %q: %w", s, err)
	}
	l, err := strconv.ParseUint(lo, 16, 32)
	if err != nil {
		return 0, fmt.Errorf("lsn %q: %w", s, err)
	}
	return LSN(h<<32 | l), nil
}

func (l LSN) String() string {
	return fmt.Sprintf("%X/%X", uint64(l)>>32, uint64(l)&0xFFFFFFFF)
}

The routing itself: Router holds two pgxpool.Pools, and ReadPool uses the session to decide where a read goes.

package dbroute

import (
	"context"
	"errors"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
)

// Router holds two pools: writes and reads that must be current go to the primary, the rest to the replica.
type Router struct {
	Primary *pgxpool.Pool
	Replica *pgxpool.Pool

	StickyFor time.Duration // how long after a write reads must be checked for freshness
	MaxWait   time.Duration // how long to wait for the replica before reading the primary
	PollEvery time.Duration // how often to ask the replica while waiting
}

// Session travels with the user (in a cookie or Redis) and records their last write.
type Session struct {
	LastWriteAt  time.Time
	LastWriteLSN LSN // 0 means the write succeeded but no position was obtained
}

// Fresh reports whether this read is still inside the "just wrote" window.
func (s Session) Fresh(now time.Time, window time.Duration) bool {
	return !s.LastWriteAt.IsZero() && now.Sub(s.LastWriteAt) < window
}

var ErrNotStandby = errors.New("replica pool is not connected to a standby")

// CurrentLSN is called after the writing transaction commits and returns the primary's current WAL position.
func (r *Router) CurrentLSN(ctx context.Context) (LSN, error) {
	var s string
	if err := r.Primary.QueryRow(ctx, "SELECT pg_current_wal_lsn()::text").Scan(&s); err != nil {
		return 0, err
	}
	return ParseLSN(s)
}

// ReplayLSN returns how far the replica has replayed.
func (r *Router) ReplayLSN(ctx context.Context) (LSN, error) {
	var s string
	err := r.Replica.QueryRow(ctx,
		"SELECT coalesce(pg_last_wal_replay_lsn()::text, '')").Scan(&s)
	if err != nil {
		return 0, err
	}
	if s == "" { // on a primary this function returns NULL
		return 0, ErrNotStandby
	}
	return ParseLSN(s)
}

// ReadPool decides where this read goes: outside the window, the replica; inside it, wait
// up to MaxWait for the replica to replay the write's position; with no position, on timeout
// or on a replica error, the primary.
func (r *Router) ReadPool(ctx context.Context, s Session) *pgxpool.Pool {
	if !s.Fresh(time.Now(), r.StickyFor) {
		return r.Replica
	}
	if s.LastWriteLSN != 0 && WaitReplay(ctx, s.LastWriteLSN, r.ReplayLSN, r.MaxWait, r.PollEvery) {
		return r.Replica
	}
	return r.Primary
}

// WaitReplay polls replay until it is >= target (returns true), or until maxWait passes,
// ctx ends or the query fails (returns false).
func WaitReplay(ctx context.Context, target LSN,
	replay func(context.Context) (LSN, error), maxWait, every time.Duration) bool {
	ctx, cancel := context.WithTimeout(ctx, maxWait)
	defer cancel()
	t := time.NewTicker(every)
	defer t.Stop()
	for {
		got, err := replay(ctx)
		if err != nil {
			return false
		}
		if got >= target {
			return true
		}
		select {
		case <-ctx.Done():
			return false
		case <-t.C:
		}
	}
}

CurrentLSN is called after the transaction commits: with the default synchronous_commit = on, the commit only returns once the commit record has been flushed, so the position obtained then is never earlier than this transaction. Once the replica has replayed past it, the order is visible there.

Finally, creating the pools and using them in the order service. The replica pool gets an extra check in AfterConnect: if a connection string is wrong and the primary is used as the replica, reads fail instead of quietly landing on the primary.

package dbroute

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// NewRouter creates both pools; the replica side gets an extra check that it really is a standby.
func NewRouter(ctx context.Context, primaryURL, replicaURL string) (*Router, error) {
	pcfg, err := pgxpool.ParseConfig(primaryURL)
	if err != nil {
		return nil, err
	}
	pcfg.MaxConns = 20

	rcfg, err := pgxpool.ParseConfig(replicaURL)
	if err != nil {
		return nil, err
	}
	rcfg.MaxConns = 40
	rcfg.AfterConnect = func(ctx context.Context, c *pgx.Conn) error {
		var standby bool
		if err := c.QueryRow(ctx, "SELECT pg_is_in_recovery()").Scan(&standby); err != nil {
			return err
		}
		if !standby {
			return ErrNotStandby
		}
		return nil
	}

	primary, err := pgxpool.NewWithConfig(ctx, pcfg)
	if err != nil {
		return nil, err
	}
	replica, err := pgxpool.NewWithConfig(ctx, rcfg)
	if err != nil {
		primary.Close()
		return nil, err
	}
	return &Router{Primary: primary, Replica: replica,
		StickyFor: 5 * time.Second, MaxWait: 200 * time.Millisecond, PollEvery: 10 * time.Millisecond}, nil
}

type Order struct {
	ID     int64
	UserID int64
	Amount int64 // minor currency units
	Status string
}

var ErrNotFound = errors.New("order not found")

// CreateOrder writes on the primary and, after the commit, records the WAL position in the Session.
func (r *Router) CreateOrder(ctx context.Context, s *Session, userID, amount int64) (int64, error) {
	var id int64
	err := pgx.BeginFunc(ctx, r.Primary, func(tx pgx.Tx) error {
		return tx.QueryRow(ctx,
			"INSERT INTO orders (user_id, amount) VALUES ($1, $2) RETURNING id",
			userID, amount).Scan(&id)
	})
	if err != nil {
		return 0, err
	}
	s.LastWriteAt = time.Now()
	// The order is written; failing to get the position is not an error: LSN stays 0 and reads in the window use the primary.
	s.LastWriteLSN, _ = r.CurrentLSN(ctx)
	return id, nil
}

// GetOrder reads one order from the given pool.
func GetOrder(ctx context.Context, db *pgxpool.Pool, id int64) (Order, error) {
	var o Order
	err := db.QueryRow(ctx,
		"SELECT id, user_id, amount, status FROM orders WHERE id = $1", id).
		Scan(&o.ID, &o.UserID, &o.Amount, &o.Status)
	if errors.Is(err, pgx.ErrNoRows) {
		return o, ErrNotFound
	}
	if err != nil {
		return o, fmt.Errorf("get order %d: %w", id, err)
	}
	return o, nil
}

At the call site it is obvious where each read goes: order details use GetOrder(ctx, r.ReadPool(ctx, sess), id); the payment result page ignores the window and uses GetOrder(ctx, r.Primary, id) directly.

The tests come in two layers. The pure logic (LSN parsing including the carry past 0/FFFFFFFF, the edges of the time window, and how WaitReplay behaves when the replica catches up, stays stuck or returns an error) uses ordinary unit tests. The routing behaviour is tested against a real primary and replica: the test pauses replay on the replica with pg_wal_replay_pause() to create lag, places an order, and checks that

  • reading the replica directly returns ErrNotFound (reproducing "the order I just placed is missing");
  • ReadPool waits 200 milliseconds and returns the primary, which has the order;
  • after pg_wal_replay_resume(), ReadPool returns the replica, which now has the order too;
  • an INSERT on the replica fails with cannot execute INSERT in a read-only transaction (SQLSTATE 25006);
  • passing the primary's URL as the replica makes ReplayLSN return ErrNotStandby.

Step 7: If a read leads to a write, read on the primary

Step 5 dealt with "an old read shows the wrong page". More dangerous is making a decision on old data and then writing. The inventory oversell followed exactly this pattern:

// fragment: what not to do
stock := queryStock(ctx, r.Replica, sku) // on the replica this may be the value from 0.5 s ago
if stock >= qty {
	_, err = r.Primary.Exec(ctx, "UPDATE stock SET qty = qty - $1 WHERE sku = $2", qty, sku)
}

The stock seen on the replica may predate someone else's decrement. Even reading both from the primary, "read then write" is itself a race; the right way is to make the check and the write one statement on the primary:

UPDATE stock SET qty = qty - $1
WHERE sku = $2 AND qty >= $1;   -- 0 rows affected means not enough stock

The rules are simple:

  • Inside a transaction that writes, every read goes to the primary. A transaction lives on one connection anyway, so in code this means: choose the primary when you begin the transaction, and do not query other pools inside it.
  • Reads that decide whether to write go to the primary: is the balance enough, is there enough stock, has this payment already been processed (idempotency key checks, see “Idempotency and Distributed Locks”), can the order move to this status.
  • Do not refill a cache from replica data, unless you can accept it being stale for the whole TTL. A common incident: a write deletes the cache entry, the next read gets the old value from a lagging replica and writes it back into the cache, and it is wrong for the entire TTL. Reads that refill a cache should go to the primary or use the LSN waiting of step 5.

Step 8: Where to put the routing

Someone has to decide which query goes where. There are three common places:

In the application order service primary pool + replica pool Primary Replica write read Knows 'just wrote' consistency decisions live here In the connection string order service host=db1,db2,db3 Driver picks target_session_attrs Primary Replica Replica Checked only at connect first matching host wins In a proxy order service write port / read port HAProxy / Pgpool-II health checks or SQL parsing Primary Replica Replica Proxy handles failover does not know who just wrote

Figure: on the left the application holds two pools and chooses; in the middle a connection string lists several hosts and the driver picks by target_session_attrs; on the right a proxy (HAProxy with Patroni, or Pgpool-II) sends connections to the right machine.

In the application (two pools): the approach of step 6. Only the application knows "was this read just after a write" and "is this the payment result page", so the consistency decision always ends up here. The downside is that every service has to do it and the rules are scattered through the code; put them in a shared package as in step 6.

In the connection string (multiple hosts plus target_session_attrs): both libpq and pgx accept several hosts in one connection string, tried in order, with target_session_attrs deciding which kind of server is acceptable:

# writes: only accept a writable server (the primary)
postgres://app@db1:5432,db2:5432,db3:5432/shop?target_session_attrs=read-write
# reads: prefer a standby, accept the primary only if none of them is a standby
postgres://app@db1:5432,db2:5432,db3:5432/shop?target_session_attrs=prefer-standby

The values are any (default), read-write, read-only, primary, standby and prefer-standby. libpq has supported read-write since PostgreSQL 10, and the other four were added in PostgreSQL 14; pgx v5 (v5.13 here) supports all six. We tested with the replica listed first and the primary second: read-write and primary skipped the replica and connected to the primary, while standby, read-only and prefer-standby connected to the replica; listing only the replica and asking for read-write failed with read only connection.

It suits "no config change after failover": when the primary moves, new connections find the new primary on their own. Know its limits, though: the check only happens once, when the connection is made. Existing connections in the pool are not rechecked, so set a maximum connection lifetime (MaxConnLifetime in pgxpool), and drop the connection and retry when a write gets 25006. It also takes "the first matching host" and does not spread reads across replicas; libpq has load_balance_hosts=random since PostgreSQL 16, but the pgx v5.13 connection-string parser does not handle that parameter.

In a proxy:

  • HAProxy plus Patroni: Patroni exposes a REST API on every node; /primary returns 200 only on the primary and /replica only on a replica (/replica?lag=... can also exclude replicas that are too far behind). HAProxy uses these endpoints as health checks and opens two ports: one that only forwards to the primary and one that balances across replicas. The application still has two pools, but their addresses are fixed, and failover and adding or removing replicas are handled by the proxy.
  • Pgpool-II: it parses SQL, spreads read-only SELECTs across replicas and sends writes to the primary, so the application needs a single connection. The price is that it must guess whether each query writes (a SELECT that calls a writing function, for example, needs extra configuration), it does not know "this user just wrote", and it is another component that needs operating and high availability.
  • PgBouncer does not split reads and writes. It is a connection pooler that maps the database name used at connect time to one configured backend; it does not parse SQL. The usual pattern is two aliases (for example shop for the primary and shop_ro for a replica), and the application still chooses.
ApproachWho decides read vs writeKnows "just wrote"?After failoverSuitsNot for
Two pools in the applicationThe codeYesCombine with one of the others to find the primaryServices that need consistency control (nearly all)Legacy systems you cannot change
Multiple hosts + target_session_attrsThe driverNoNew connections find the new primaryNo proxy layer, few hostsSpreading reads evenly across several replicas
HAProxy + PatroniProxy, by health checksNoAutomaticPatroni clusters with several replicasA small one-primary-one-replica setup; the extra layer does not pay off
Pgpool-IIProxy, by parsing SQLNoCan be automaticCode you cannot change that still needs reads spread outFine-grained consistency control; avoiding another complex component
PgBouncerNobodyNoDepends on configurationCutting connection counts, alongside any of the aboveExpecting it to split reads and writes for you

Managed services (such as cloud PostgreSQL) usually give one endpoint for the primary and one for read replicas, which amounts to a ready-made proxy layer; the application's job is the same: two pools plus the consistency decisions.

Step 9: Long queries and query conflicts on replicas

The cancelled report was reproduced like this: open a REPEATABLE READ transaction on the replica that reads the orders table, and meanwhile delete a batch of orders on the primary and run VACUUM:

ERROR:  canceling statement due to conflict with recovery
DETAIL:  User query might have needed to see row versions that must be removed.
hot_standby_feedback: standby reports its oldest snapshot; primary delays cleanup (bloat) Primary DELETE old orders VACUUM removes old versions Standby Replay: remove old versions Report still needs them WAL conflict Wait for the query replay pauses; lag grows for every reader After max_standby_streaming_delay cancel the query (default 30 s)

Figure: VACUUM on the primary removes old row versions, and that removal reaches the standby through the WAL; a query on the standby still needs those versions, so replay must either wait for the query to end or cancel it after the wait limit.

The cause is that the primary and the replica's queries cannot see each other. The primary's VACUUM only knows that no transaction on the primary needs those old row versions, so it removes them; when that cleanup arrives through the WAL, the report on the replica still needs them. The replica has two choices: pause replay until the query finishes (lag keeps growing and everyone reading that replica sees older and older data), or cancel the query. How long it waits is set by max_standby_streaming_delay, 30 seconds by default; our experiment set it to 2 seconds, the query was cancelled after 2 seconds, and confl_snapshot in pg_stat_database_conflicts went up by one.

What you can adjust, and the cost of each:

ApproachEffectCostSuits
Raise max_standby_streaming_delayLong queries are cancelled less oftenReplay stops during a conflict and lag growsReplicas dedicated to reports, not serving online reads
hot_standby_feedback = onThe replica reports its oldest snapshot and the primary keeps those row versionsDead rows on the primary cannot be cleaned; tables and indexes bloatOnline replicas with a few medium-length queries
statement_timeout on online replicasLong queries cannot run there at allReports need a home elsewhereReplicas serving user requests
A dedicated report replicaReports and online reads do not affect each otherAnother machineMany reports, long queries
Retry when a query is cancelledOccasional conflicts do not change the resultThe query runs twiceShort queries; retrying a read-only query is safe

We saw the cost of hot_standby_feedback too: with it on and a long transaction open on the replica, VACUUM (VERBOSE) on the primary printed 10000 are dead but not yet removable, so the ten thousand deleted rows could not be cleaned on the primary. One forgotten transaction on a replica keeps bloating the primary's tables; if you turn it on, the replica also needs idle_in_transaction_session_timeout and statement_timeout, and you should monitor the oldest transaction on the replica.

The shop's arrangement: two replicas for online reads, with a short statement_timeout and the default max_standby_streaming_delay; one dedicated replica for operations reports and exports, with a higher delay limit, accepting that its data may be minutes behind, and kept out of the online read rotation.

Step 10: Failover, split brain and replication slots

Replicas are also the basis of high availability: when the primary dies, a replica is promoted to be the new primary (pg_ctl promote, or pg_promote() in SQL). That step itself is quick; the hard part is everything around it:

etcd / Consul primary lock with a TTL db1 (old primary) lost lock → demote or fence db2 → new primary takes lock, pg_promote() db3 (replica) now follows db2 Patroni WAL HAProxy /primary, /replica health checks write port read port order service must not accept writes again

Figure: Patroni holds a "primary lock" in a consensus store such as etcd; when the primary loses the lock, a replica takes it and is promoted, and the old primary must be demoted or fenced; HAProxy uses the /primary and /replica health checks to send connections to the new location.

  • Who decides, and when. Manual promotion is safest but needs someone awake at night; automatic failover commonly uses Patroni: a Patroni process runs next to every node and competes for a primary lock with a time limit in a consensus store such as etcd, Consul or Kubernetes, and only the holder is primary.
  • Split brain. If the old primary only lost its network rather than dying, once the network returns both machines believe they are primary and both accept writes; the data diverges and is very hard to merge afterwards. Patroni's answer is for a primary that cannot renew its lock to demote itself; stricter environments add fencing to make sure the old primary really stops accepting writes.
  • Asynchronous replication loses the last few transactions. The promoted replica only has the WAL it received, so the last short stretch of transactions the primary reported as committed may be gone. Money-related data should therefore either use synchronous replication (step 3) or rely on the outbox and reconciliation from “Distributed Transactions: Sagas and the Outbox Pattern” to recover them.
  • The application must find the new primary. Use the multi-host connection string or proxy layer of step 8; the application itself must retry on connection failures or on 25006, instead of holding on to connections that point at the old primary.
  • Other replicas must follow the new primary. Promotion starts a new timeline, other replicas must reconnect to the new primary, and the old primary usually needs pg_rewind or a fresh pg_basebackup to rejoin. This is where tools such as Patroni earn their keep; doing it by script makes it easy to miss a step.

A replication slot is what -C -S created in step 2. It makes the primary remember how far the replica has read and keep WAL the replica has not yet received. The benefit is that a replica can catch up after a short disconnection; the risk is that while a replica stays away, the primary keeps all that WAL:

The primary's pg_wal: the slot remembers where the replica is replica restart_lsn pg_current_wal_lsn() cap: max_slot_wal_keep_size can be removed must be kept: grows the longer the replica is away No cap (default -1) pg_wal grows until the disk is full With a cap slot becomes lost: rebuild replica, primary safe

Figure: the slot remembers the replica's restart_lsn, and the primary cannot delete any WAL after that position; the longer the replica is disconnected, the bigger the primary's pg_wal directory gets, until the disk is full; max_slot_wal_keep_size sets a cap beyond which the slot is invalidated.

We stopped the replica, wrote a batch of data on the primary and ran CHECKPOINT: the slot was holding 152 MB of WAL, with wal_status reserved. In production, a replica that is dead for two days without anyone noticing holds two days of writes, which is exactly how "the primary's disk filled up with WAL" at the start happened. What to do:

  • Set max_slot_wal_keep_size (default -1, unlimited). We set it to 32 MB and kept writing, and the slot's wal_status became lost: the primary's disk was safe, at the cost of that replica no longer being able to catch up and having to be rebuilt. That trade-off is almost always right: a replica can be rebuilt, but a full disk on the primary stops the whole service.
  • Monitor how much each slot is holding and whether it is active, and drop unused slots immediately (pg_drop_replication_slot).
SELECT slot_name, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained,
       pg_size_pretty(safe_wal_size) AS safe
FROM pg_replication_slots;

Step 11: Connection pools, monitoring and alerts

Size the pools per role. The primary and each replica have their own max_connections, and each application instance has a primary pool and a replica pool. Estimate capacity like this:

  • The sum of the primary pools = number of instances × primary pool size, plus background jobs, migration tools and monitoring; it must stay below the primary's max_connections with room to spare.
  • The same for replicas, but size it for one replica being down: with three replicas and one gone, the other two must take all the read connections and queries.
  • The fallbacks of steps 5 and 6 send reads back to the primary. If every replica has trouble, all reads may rush to the primary at once; the primary pool's limit is the last gate protecting the primary, so do not enlarge it beyond what the primary can handle just so that "fallback can cope".

When services scale out horizontally on Kubernetes, connection counts grow with the number of instances; with many instances, put PgBouncer in front of the database to keep connection counts down (see “database/sql, Transactions and Connection Pools in Go”).

Monitoring and alerts; adjust the thresholds to your write volume and the lag you can tolerate:

What to monitorSourceSuggested alert
Bytes each replica is behindPrimary pg_stat_replicationAbove the threshold for a while: remove from the read rotation; higher still: page someone
Number of replicas and their statePrimary pg_stat_replication, replica pg_stat_wal_receiverFewer rows than replicas; state or the replica's status not streaming
WAL held by slots, wal_statusPrimary pg_replication_slotsactive = false for more than a few minutes; retained size near the cap; any lost
Primary disk usage (especially pg_wal)Host monitoringEstimate time-to-full from the growth rate
Query conflictsReplica pg_stat_database_conflictsA sudden rise usually means a new long query reached an online replica
Oldest transaction on the replicaReplica pg_stat_activity, xact_startEspecially important with hot_standby_feedback on
Count of SQLSTATE 25006Application logs and metricsAnything above 0 means a write was sent to a replica
Share of reads falling back to the primaryApplication metric (how often ReadPool returns the primary)A rising share means lag is growing and read load is returning to the primary
Pool utilisation and waits per poolpgxpool Stat()Number and duration of connection waits keep rising

The last rows deserve a word: monitoring read/write splitting is not only about the database. The application's fallback share answers most directly "how much is splitting actually taking off the primary right now"; if it quietly climbs from 10% to 80%, the primary's CPU will soon be back where it started.

Common pitfalls

  • Adding replicas before fixing indexes and adding caching. A slow query is just as slow on another machine, and now there is one more machine to run.
  • Assuming the replica is real-time. Replication is asynchronous by default; a successful commit does not mean the replica can see it, and "the order I just placed is missing" will almost certainly happen.
  • Reading payment results, balances or stock from a replica. Wrong answers cause double payments or overselling; critical reads always go to the primary.
  • Reading on the replica, then writing on the primary. Reads that decide whether to write must happen on the primary, ideally merged with the write into one conditional UPDATE.
  • Assuming remote_apply means consistency. Without synchronous_standby_names it behaves like on; with several replicas it only covers the one that was waited for.
  • Having only one synchronous standby. When it stops, every commit hangs, and statement_timeout will not help.
  • Alerting only on replay_lag. While replay is stuck it can sit at a small old value; use the byte difference.
  • Alerting on now() - pg_last_xact_replay_timestamp() alone. It keeps growing while the primary is idle, and fires false alarms at night.
  • Keeping the write time or LSN in one process's memory. It is lost as soon as the next request goes to another instance.
  • Refilling a cache from a replica. The old value is then served to everyone for the whole TTL.
  • Using sequences, temporary tables, LISTEN or FOR UPDATE on a replica. They all fail; check before moving reads.
  • Assuming PgBouncer splits reads and writes. It is a connection pooler and does not parse SQL.
  • Relying on target_session_attrs for failover without a connection lifetime. It only checks at connect time, and old connections stay in the pool.
  • Running reports on online replicas. They get cancelled or they stall replay; with hot_standby_feedback on they also bloat the primary.
  • Automatic failover without fencing the old primary. After a split brain the data diverges, which is harder to clean up than downtime.
  • Replication slots with no cap and no monitoring. One dead replica fills the primary's disk with WAL.
  • Falling back to the primary without a limit. When all replicas fail, every read rushes to the primary and takes it down too.

Key takeaways

  • Read/write splitting only solves "heavy read load that tolerates lag"; write bottlenecks, slow queries, repeated reads and too many connections each have cheaper or more correct fixes.
  • Streaming replication ships the WAL to replicas for replay; a replica is a read-only copy of the whole cluster: no writes, no sequence values, no temporary tables, no LISTEN or FOR UPDATE, and writes sent to it get SQLSTATE 25006.
  • The five synchronous_commit levels wait progressively longer; synchronous replication needs synchronous_standby_names, at least two candidate standbys, and is mainly about not losing data. SET LOCAL makes a single transaction wait.
  • Use the byte difference (pg_wal_lsn_diff) as the main lag metric; replay_lag can sit at an old value while replay is stuck, and the replay timestamp grows while the primary is idle.
  • Reading your own writes: critical reads always go to the primary, ordinary "write then view" reads use a time window plus LSN waiting, everything else goes to replicas; keep session state somewhere shared.
  • If a read leads to a write, read on the primary, ideally by putting the check into a conditional UPDATE; do not refill caches from replicas.
  • Consistency decisions always live in the application; finding the primary can be left to a multi-host connection string (target_session_attrs, checked only at connect) or HAProxy plus Patroni; Pgpool-II parses SQL, and PgBouncer does not split reads and writes.
  • Long queries on replicas conflict with replay: online replicas get a short statement_timeout, reports get a dedicated replica; hot_standby_feedback trades bloat on the primary for fewer cancellations.
  • Failover has to deal with split brain, the last transactions lost by asynchronous replication, and applications reconnecting; replication slots need max_slot_wal_keep_size and monitoring.
  • Size pools per role and for "one replica down", cap the fallback to the primary, and monitor both database lag and the application's fallback share.

References

  • Log-Shipping Standby Servers (official PostgreSQL documentation): streaming replication, replication slots and synchronous replication, used in steps 2, 3 and 10.
  • Hot Standby (official PostgreSQL documentation): query conflicts on standbys, max_standby_streaming_delay and hot_standby_feedback, used in step 9.
  • Write Ahead Log (official PostgreSQL documentation): the synchronous_commit levels and why only on and off differ without synchronous standbys, used in step 3.
  • Replication (official PostgreSQL documentation): max_slot_wal_keep_size defaulting to -1 and the 30-second max_standby_streaming_delay, used in steps 9 and 10.
  • The Cumulative Statistics System (official PostgreSQL documentation): the definitions of write_lag, flush_lag and replay_lag in pg_stat_replication, used in step 4.
  • Database Connection Control Functions (official PostgreSQL documentation): target_session_attrs and load_balance_hosts, used in step 8.
  • pg_basebackup (official PostgreSQL documentation): -R writing standby.signal and connection settings, used to create the replica in step 2.
  • Patroni REST API (official Patroni documentation): the /primary, /replica and /replica?lag= health endpoints, used for the proxy layer in step 8.

Next

Replicas can only take reads. Every write still runs on the primary and is replayed again on every replica; once the bottleneck is writes, or a single primary holds so much data that backups, VACUUM and every new index become a struggle, more replicas will not help. The next article, “Hot and Cold Data, Sharding and Splitting Databases: What to Do When the Data Grows”, takes up that problem: separate hot and cold data and archive the old, then, only when it is really needed, split databases vertically, shard horizontally, and move the data across without downtime.