Database Engineering··2 min read

PostgreSQL Read Replicas Without Stale-Read Bugs: Causal Consistency with LSN Tracking

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

PostgreSQL Read Replicas Without Stale-Read Bugs: Causal Consistency with LSN Tracking

The Classic Read-After-Write Bug on Asynchronous Replicas

When you split database traffic so INSERT / UPDATE / DELETE queries hit the PostgreSQL primary and SELECT queries hit asynchronous streaming read replicas, you immediately run into replication lag.

Even a healthy 80-millisecond WAL replay delay is enough to break user flows: a user submits a form (POST /api/orders), your frontend immediately redirects to GET /api/orders/123 on a read replica, and the replica returns 404 Not Found because that WAL segment has not replayed yet.


1. Tracking Write Causal Position with pg_current_wal_lsn()

PostgreSQL tracks every state mutation using a monotonically increasing Log Sequence Number (LSN).

Whenever a user performs a write on the primary node, we query SELECT pg_current_wal_lsn() inside the commit response and attach that LSN value (0/16B3748) to a short-lived HTTP-only session header or Redis key for that user (user:min_lsn:<user_id>, TTL 5 seconds).


2. LSN-Aware Read Replica Routing Middleware

When a subsequent GET request arrives for that user, our database router compares the user's required minimum LSN against the replica's last replayed WAL position (pg_last_wal_replay_lsn()):

func (r *DBRouter) PickReadPool(ctx context.Context, userMinLSN string) *pgxpool.Pool {
	if userMinLSN == "" {
		return r.replicaPool
	}

	if r.replicaHasCaughtUp(userMinLSN) {
		return r.replicaPool
	}

	// Replica is still behind this user's last write; route safely to Primary
	return r.primaryPool
}

By polling SELECT pg_last_wal_replay_lsn() on each replica once every 100ms in a background ticker, individual read queries never pay an extra SQL round-trip. Over 98.4% of read traffic stays on the read replicas, while recent writers enjoy 100% causal read-your-own-write consistency.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles