Move read traffic off a single primary onto streaming replicas. Route each read to a replica that is provably fresh enough for that request, fall back to the primary when none is, and configure replication so that promoting a replica never discards a transaction the application already reported as committed.
Read replicas are the first tool most teams reach for when a database primary runs hot and most of its traffic is SELECTs. Replicas copy the primary's write-ahead log and serve reads. That part is easy. The hard part is that every replica is somewhat behind. A naive setup shows users data that is missing their own last action, double-processes things that look unfinished, and can lose committed transactions when a replica gets promoted. This guide follows one invented service through all three problems: replication lag, read-your-writes, and failover. It ends with a routing layer you can describe in an interview in under a minute and defend when the follow-up questions get specific.
The problem
A situation where the obvious design starts to hurt.
Ledgerline is an expense-reporting SaaS used by about 40,000 companies. Everything lives in one Postgres 16 primary, pg-main, on a 32 vCPU machine. On Monday mornings, roughly 09:00 to 11:00 UTC, managers clear approval queues. Load hits about 21,000 queries per second, and 95% of those are reads: approval dashboards, policy lookups, receipt lists. Only around 900 per second are writes.
One Monday the primary sat at 94% CPU, the 200-connection pool was exhausted, and p99 for the approval page went from 120 ms to 2.4 s.
The team added two async streaming replicas, pg-r1 and pg-r2, and pointed every SELECT at them. Primary CPU dropped to 30%. Within a day, support had dozens of tickets reading "I submitted my expense and it disappeared." The submit handler wrote to the primary and redirected to the list page, which read from a replica 200 ms to 3 s behind. During the nightly corporate-card import it was 6 s behind.
Worse, a manager's double-click hit the approve endpoint twice. Its precondition check read status = 'pending' from a lagging replica both times, so two approval emails and two ledger entries went out.
In March the primary's host died. The failover script promoted pg-r2, which was 1.4 s behind. About 1,100 committed transactions vanished, including approvals whose notification emails had already been sent. Reads had scaled. Correctness had not.
The solution
What the pattern proposes.
Keep the replicas, but stop treating all reads alike. Put a small replica router in the data-access layer and give it four rules.
First, writes and read-before-write checks go to the primary. Anything that reads a value in order to decide on a write, like the approve precondition, runs on the primary, inside the same transaction, ideally with SELECT ... FOR UPDATE. Replicas are for display, never for guarding a write.
Second, read-your-writes through LSN tokens. After a write commits, the router reads pg_current_wal_lsn() from the primary and stores it in the user's session as minLsn, with a 30 s expiry. On each later read, the router picks only replicas whose replayed position (pg_last_wal_replay_lsn()) is at or past minLsn. If none qualifies, the read goes to the primary. Most users never wrote anything recently, so they carry no token and can use any healthy replica.
Third, lag eviction. A poller queries every replica every 200 ms for its replay LSN and its replay delay. A replica more than 5 s behind, or one that has not answered a poll in 2 s, leaves the rotation. The primary writes a heartbeat row every second so the delay figure stays meaningful when traffic is quiet.
Fourth, failover that cannot lose commits. Run Patroni with etcd and synchronous_mode: true, which sets synchronous_standby_names = 'ANY 1 (pg-r1, pg-r2)'. Every commit waits until at least one replica has flushed it, and Patroni only promotes a standby that was synchronous. Clients reach the primary through HAProxy, which health-checks Patroni's /primary endpoint. A demoted node stops receiving writes and rejoins through pg_rewind.
An everyday analogy
The same idea, outside software.
Picture a warehouse where the head clerk keeps the master stock ledger and two branch clerks get carbon copies of each page by courier. Customers can ask any clerk how much stock is left. A customer who has just returned goods holds a receipt with a page number. A branch clerk answers that customer only after filing that page, and otherwise sends them to the head clerk.
Anyone about to sell the last unit asks the head clerk, because a carbon copy might be a page behind.
The head clerk also refuses to tell a customer "done" until at least one branch confirms it has the page in hand. If the head clerk collapses, that branch takes over the master ledger without missing a single entry.
Structure
The pieces and how they relate.
Participants
- Primary (pg-main)
- The only node that accepts writes. It also serves reads that guard a write, reads pinned by a recent LSN that no replica has reached, and all reads when every replica is evicted. Each commit waits for one synchronous standby to flush it.
- Streaming replicas (pg-r1, pg-r2)
- Replay the primary's WAL and serve read-only queries. Each is somewhat behind, usually tens of milliseconds and seconds during bulk imports. Either can be the synchronous standby that Patroni is allowed to promote.
- Replica router
- A library inside the API process. For each query it decides between primary and replica using cached replica state and the request's minLsn. It never blocks waiting for a replica to catch up.
- Lag poller
- A background loop that asks each replica for
pg_last_wal_replay_lsn()and its replay delay every 200 ms. It marks unreachable or stale replicas so the router drops them. A slightly stale snapshot only under-reports progress, so it is always safe. - Session LSN token
- The primary's WAL position right after the user's last write, stored in the session or a signed cookie and expired after 30 s. It is the promise the router keeps: this user sees nothing older than their own last write.
- Patroni, etcd and HAProxy
- Patroni holds a leader lock in etcd and promotes only a synchronous standby. HAProxy sends primary traffic to whichever node answers 200 on
/primary, which fences a demoted node out of the write path.
Pseudocode
The solution to the scenario, language-neutral.
// Background, every 200 ms
for each replica r:
try:
r.replayLsn, r.lagSeconds = r.query("pg_last_wal_replay_lsn(), now() - pg_last_xact_replay_timestamp()")
r.polledAt = now
on error:
r.polledAt = -infinity // out of rotation until a good poll
// Write path
write(session, fn):
result = fn(primary) // transaction commits; sync standby has flushed it
lsn = primary.query("pg_current_wal_lsn()")
session.minLsn = max(session.minLsn, lsn)
session.minLsnExpires = now + 30 s
return result
// Guarded read: the value decides a write
approve(session, reportId):
write(session, tx ->
row = tx.query("SELECT status FROM reports WHERE id = ? FOR UPDATE", reportId)
if row.status != 'pending': return AlreadyDecided
tx.exec("UPDATE reports SET status = 'approved' ..."))
// Display read
read(session, sql):
minLsn = session.minLsn if now < session.minLsnExpires else none
candidates = replicas where
now - polledAt <= 2 s
and lagSeconds <= 5
and (minLsn is none or replayLsn >= minLsn)
if candidates is empty:
return primary.query(sql) // bounded by a primary fallback pool of 40 connections
return random(candidates).query(sql)
// Failover (Patroni, not application code)
if leader lock in etcd expires (TTL 30 s):
candidate = the standby listed as synchronous
candidate.promote()
HAProxy health check flips /primary to candidate
old primary, when it returns, runs pg_rewind and rejoins as a replicaThe code
The same solution in TypeScript, Python and PHP.
// Replica router: picks primary or a replica per read using cached replica state.
// Reads may carry a minimum LSN; a replica serves them only if it has replayed that far.
export type Lsn = string; // e.g. "1A/3F00C2B8", as returned by pg_current_wal_lsn()::text
export interface Conn {
query<T>(sql: string, params?: unknown[]): Promise<T[]>;
}
interface ReplicaState {
name: string;
conn: Conn;
replayLsn: Lsn | null;
lagSeconds: number;
polledAt: number;
}
export function compareLsn(a: Lsn, b: Lsn): number {
const [ah, al] = a.split("/").map((p) => parseInt(p, 16));
const [bh, bl] = b.split("/").map((p) => parseInt(p, 16));
if (ah !== bh) return ah < bh ? -1 : 1;
if (al !== bl) return al < bl ? -1 : 1;
return 0;
}
// The primary writes a heartbeat row every second, so replay delay stays meaningful when idle.
const POLL_SQL = `
SELECT pg_last_wal_replay_lsn()::text AS lsn,
COALESCE(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()), 0)::float8 AS lag`;
export class ReplicaRouter {
private readonly replicas: ReplicaState[];
constructor(
private readonly primary: Conn,
replicas: { name: string; conn: Conn }[],
private readonly maxLagSeconds = 5,
private readonly maxPollAgeMs = 2000,
) {
this.replicas = replicas.map((r) => ({ ...r, replayLsn: null, lagSeconds: Infinity, polledAt: 0 }));
}
// Call every 200 ms. A stale snapshot only under-reports progress, so it is safe.
async poll(now = Date.now()): Promise<void> {
await Promise.all(
this.replicas.map(async (r) => {
try {
const [row] = await r.conn.query<{ lsn: string | null; lag: number }>(POLL_SQL);
r.replayLsn = row.lsn;
r.lagSeconds = row.lag;
r.polledAt = now;
} catch {
r.polledAt = 0; // unreachable: out of rotation until the next good poll
}
}),
);
}
// Runs fn on the primary, then returns the WAL position to store as the session's minLsn.
async write<T>(fn: (c: Conn) => Promise<T>): Promise<{ result: T; lsn: Lsn }> {
const result = await fn(this.primary);
const [row] = await this.primary.query<{ lsn: string }>("SELECT pg_current_wal_lsn()::text AS lsn");
return { result, lsn: row.lsn };
}
pickReader(minLsn?: Lsn, now = Date.now()): { name: string; conn: Conn } {
const ready = this.replicas.filter(
(r) =>
r.replayLsn !== null &&
now - r.polledAt <= this.maxPollAgeMs &&
r.lagSeconds <= this.maxLagSeconds &&
(minLsn === undefined || compareLsn(r.replayLsn, minLsn) >= 0),
);
if (ready.length === 0) return { name: "primary", conn: this.primary };
return ready[Math.floor(Math.random() * ready.length)];
}
async read<T>(sql: string, params: unknown[] = [], minLsn?: Lsn): Promise<T[]> {
return this.pickReader(minLsn).conn.query<T>(sql, params);
}
}
// --- Demo with fake connections ---
class FakeConn implements Conn {
constructor(private readonly respond: (sql: string) => unknown[]) {}
async query<T>(sql: string): Promise<T[]> {
return this.respond(sql) as T[];
}
}
async function main(): Promise<void> {
const primary = new FakeConn((sql) =>
sql.includes("pg_current_wal_lsn") ? [{ lsn: "1A/3F00C2B8" }] : [{ source: "primary" }],
);
const r1 = new FakeConn((sql) =>
sql.includes("replay") ? [{ lsn: "1A/3F00C2B8", lag: 0.2 }] : [{ source: "pg-r1" }],
);
const r2 = new FakeConn((sql) =>
sql.includes("replay") ? [{ lsn: "1A/3E000000", lag: 1.1 }] : [{ source: "pg-r2" }],
);
const router = new ReplicaRouter(primary, [
{ name: "pg-r1", conn: r1 },
{ name: "pg-r2", conn: r2 },
]);
await router.poll();
const { lsn } = await router.write((c) => c.query("INSERT INTO expenses (amount) VALUES (42)"));
console.log(router.pickReader(lsn).name); // pg-r1: pg-r2 has not replayed this LSN yet
console.log(router.pickReader().name); // pg-r1 or pg-r2
console.log(router.pickReader("1B/00000000").name); // primary: no replica is that far
}
void main();"""Replica router: picks primary or a replica per read using cached replica state.
Reads may carry a minimum LSN; a replica serves them only if it has replayed that far.
"""
import random
import time
from dataclasses import dataclass
from typing import Any, Callable, Optional, Protocol, TypeVar
T = TypeVar("T")
class Conn(Protocol):
def query(self, sql: str, params: tuple = ()) -> list[dict[str, Any]]: ...
def _parse_lsn(lsn: str) -> tuple[int, int]:
hi, lo = lsn.split("/")
return int(hi, 16), int(lo, 16)
def compare_lsn(a: str, b: str) -> int:
pa, pb = _parse_lsn(a), _parse_lsn(b)
return (pa > pb) - (pa < pb)
# The primary writes a heartbeat row every second, so replay delay stays meaningful when idle.
POLL_SQL = """
SELECT pg_last_wal_replay_lsn()::text AS lsn,
COALESCE(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()), 0)::float8 AS lag"""
def _now_ms() -> float:
return time.monotonic() * 1000
@dataclass
class ReplicaState:
name: str
conn: Conn
replay_lsn: Optional[str] = None
lag_seconds: float = float("inf")
polled_at: float = float("-inf")
class ReplicaRouter:
def __init__(
self,
primary: Conn,
replicas: list[tuple[str, Conn]],
max_lag_seconds: float = 5.0,
max_poll_age_ms: float = 2000.0,
) -> None:
self.primary = primary
self.replicas = [ReplicaState(name, conn) for name, conn in replicas]
self.max_lag_seconds = max_lag_seconds
self.max_poll_age_ms = max_poll_age_ms
def poll(self, now: Optional[float] = None) -> None:
"""Call every 200 ms. A stale snapshot only under-reports progress, so it is safe."""
now = _now_ms() if now is None else now
for r in self.replicas:
try:
row = r.conn.query(POLL_SQL)[0]
r.replay_lsn = row["lsn"]
r.lag_seconds = float(row["lag"])
r.polled_at = now
except Exception:
r.polled_at = float("-inf") # out of rotation until the next good poll
def write(self, fn: Callable[[Conn], T]) -> tuple[T, str]:
"""Run fn on the primary, then return the WAL position to store as minLsn."""
result = fn(self.primary)
lsn = self.primary.query("SELECT pg_current_wal_lsn()::text AS lsn")[0]["lsn"]
return result, lsn
def pick_reader(self, min_lsn: Optional[str] = None, now: Optional[float] = None) -> tuple[str, Conn]:
now = _now_ms() if now is None else now
ready = [
r
for r in self.replicas
if r.replay_lsn is not None
and now - r.polled_at <= self.max_poll_age_ms
and r.lag_seconds <= self.max_lag_seconds
and (min_lsn is None or compare_lsn(r.replay_lsn, min_lsn) >= 0)
]
if not ready:
return "primary", self.primary
chosen = random.choice(ready)
return chosen.name, chosen.conn
def read(self, sql: str, params: tuple = (), min_lsn: Optional[str] = None) -> list[dict[str, Any]]:
_, conn = self.pick_reader(min_lsn)
return conn.query(sql, params)
# --- Demo with fake connections ---
class FakeConn:
def __init__(self, respond: Callable[[str], list[dict[str, Any]]]) -> None:
self.respond = respond
def query(self, sql: str, params: tuple = ()) -> list[dict[str, Any]]:
return self.respond(sql)
if __name__ == "__main__":
primary = FakeConn(
lambda sql: [{"lsn": "1A/3F00C2B8"}] if "pg_current_wal_lsn" in sql else [{"source": "primary"}]
)
r1 = FakeConn(
lambda sql: [{"lsn": "1A/3F00C2B8", "lag": 0.2}] if "replay" in sql else [{"source": "pg-r1"}]
)
r2 = FakeConn(
lambda sql: [{"lsn": "1A/3E000000", "lag": 1.1}] if "replay" in sql else [{"source": "pg-r2"}]
)
router = ReplicaRouter(primary, [("pg-r1", r1), ("pg-r2", r2)])
router.poll()
_, lsn = router.write(lambda c: c.query("INSERT INTO expenses (amount) VALUES (42)"))
print(router.pick_reader(lsn)[0]) # pg-r1: pg-r2 has not replayed this LSN yet
print(router.pick_reader()[0]) # pg-r1 or pg-r2
print(router.pick_reader("1B/00000000")[0]) # primary: no replica is that far<?php
declare(strict_types=1);
// Replica router: picks primary or a replica per read using cached replica state.
// Reads may carry a minimum LSN; a replica serves them only if it has replayed that far.
interface Conn
{
/** @return list<array<string, mixed>> */
public function query(string $sql, array $params = []): array;
}
final class ReplicaState
{
public ?string $replayLsn = null;
public float $lagSeconds = INF;
public float $polledAt = -INF;
public function __construct(
public readonly string $name,
public readonly Conn $conn,
) {}
}
function compareLsn(string $a, string $b): int
{
[$ah, $al] = array_map('hexdec', explode('/', $a));
[$bh, $bl] = array_map('hexdec', explode('/', $b));
return [$ah, $al] <=> [$bh, $bl];
}
final class ReplicaRouter
{
// The primary writes a heartbeat row every second, so replay delay stays meaningful when idle.
private const POLL_SQL = "SELECT pg_last_wal_replay_lsn()::text AS lsn,
COALESCE(EXTRACT(EPOCH FROM now() - pg_last_xact_replay_timestamp()), 0)::float8 AS lag";
/** @var list<ReplicaState> */
private array $replicas = [];
/** @param array<string, Conn> $replicas name => connection */
public function __construct(
private readonly Conn $primary,
array $replicas,
private readonly float $maxLagSeconds = 5.0,
private readonly float $maxPollAgeMs = 2000.0,
) {
foreach ($replicas as $name => $conn) {
$this->replicas[] = new ReplicaState($name, $conn);
}
}
// Call every 200 ms. A stale snapshot only under-reports progress, so it is safe.
public function poll(?float $now = null): void
{
$now ??= microtime(true) * 1000;
foreach ($this->replicas as $r) {
try {
$row = $r->conn->query(self::POLL_SQL)[0];
$r->replayLsn = $row['lsn'];
$r->lagSeconds = (float) $row['lag'];
$r->polledAt = $now;
} catch (Throwable) {
$r->polledAt = -INF; // out of rotation until the next good poll
}
}
}
/** Runs $fn on the primary, then returns the WAL position to store as minLsn. */
public function write(callable $fn): array
{
$result = $fn($this->primary);
$lsn = $this->primary->query('SELECT pg_current_wal_lsn()::text AS lsn')[0]['lsn'];
return ['result' => $result, 'lsn' => $lsn];
}
/** @return array{0: string, 1: Conn} */
public function pickReader(?string $minLsn = null, ?float $now = null): array
{
$now ??= microtime(true) * 1000;
$ready = array_values(array_filter(
$this->replicas,
fn (ReplicaState $r): bool => $r->replayLsn !== null
&& $now - $r->polledAt <= $this->maxPollAgeMs
&& $r->lagSeconds <= $this->maxLagSeconds
&& ($minLsn === null || compareLsn($r->replayLsn, $minLsn) >= 0),
));
if ($ready === []) {
return ['primary', $this->primary];
}
$chosen = $ready[array_rand($ready)];
return [$chosen->name, $chosen->conn];
}
public function read(string $sql, array $params = [], ?string $minLsn = null): array
{
[, $conn] = $this->pickReader($minLsn);
return $conn->query($sql, $params);
}
}
// --- Demo with fake connections ---
final class FakeConn implements Conn
{
public function __construct(private readonly Closure $respond) {}
public function query(string $sql, array $params = []): array
{
return ($this->respond)($sql);
}
}
$primary = new FakeConn(fn (string $sql): array => str_contains($sql, 'pg_current_wal_lsn')
? [['lsn' => '1A/3F00C2B8']] : [['source' => 'primary']]);
$r1 = new FakeConn(fn (string $sql): array => str_contains($sql, 'replay')
? [['lsn' => '1A/3F00C2B8', 'lag' => 0.2]] : [['source' => 'pg-r1']]);
$r2 = new FakeConn(fn (string $sql): array => str_contains($sql, 'replay')
? [['lsn' => '1A/3E000000', 'lag' => 1.1]] : [['source' => 'pg-r2']]);
$router = new ReplicaRouter($primary, ['pg-r1' => $r1, 'pg-r2' => $r2]);
$router->poll();
$lsn = $router->write(fn (Conn $c) => $c->query('INSERT INTO expenses (amount) VALUES (42)'))['lsn'];
echo $router->pickReader($lsn)[0], PHP_EOL; // pg-r1: pg-r2 has not replayed this LSN yet
echo $router->pickReader()[0], PHP_EOL; // pg-r1 or pg-r2
echo $router->pickReader('1B/00000000')[0], PHP_EOL; // primary: no replica is that farWhen to use it
Situations where it pays off.
Reads outnumber writes by roughly 5:1 or more and the primary is bound by CPU, connections or buffer cache rather than by write I/O.
Each replica adds a full copy of read capacity. Writes still all land on one node, so replicas do nothing for a write-bound primary. Ledgerline's 95% read mix is the ideal case.
Most read paths can tolerate data a few seconds old, like dashboards, lists and search, and you can identify the few that cannot.
The router only pays off if most traffic is allowed on a replica. If nearly every read needs the latest state, everything falls back to the primary and you have bought hardware for nothing.
You need a hot standby for failover anyway.
The synchronous standby that protects against data loss can serve reads in normal operation, so the failover capacity is not idle.
Reporting or export queries scan large ranges and compete with OLTP traffic.
Giving them a dedicated replica with different settings, such as a long
max_standby_streaming_delay, isolates their cost from the approval page without touching the primary.
How to implement it
Steps to introduce it in existing code.
Classify every query path as write, guarded read, or display read. Guarded reads move into the write transaction on the primary and use
FOR UPDATEor a conditional UPDATE. Only display reads are allowed on replicas.Add streaming replicas and turn on
hot_standby. Run Patroni withsynchronous_mode: trueso one replica always acknowledges commits and only that replica is eligible for promotion.Write a heartbeat row on the primary every second. Run a poller that records each replica's replay LSN and replay delay every 200 ms, and evict any replica above 5 s of lag or without a successful poll for 2 s.
After each committed write, read
pg_current_wal_lsn()and store it in the session as minLsn with a 30 s expiry. Keep the maximum if the user writes several times.In the router, send display reads to a random replica whose replay LSN is at or past minLsn. Fall back to the primary through a separate, capped connection pool.
Put HAProxy in front of the primary, checking Patroni's
/primaryendpoint. Test failover monthly by killing the primary under load and confirming that no committed write is missing on the new leader.
Pros and cons
What you gain and what you pay.
Pros
- Read capacity scales roughly linearly per replica. Ledgerline's primary CPU fell from 94% to around 35% with two replicas, even counting pinned reads.
- Users always see their own writes, while users without a recent write never touch the primary.
- The router makes decisions from in-memory state, so it adds no extra round trip to the read path.
- With a synchronous standby, failover loses zero acknowledged commits, and the standby earns its keep by serving reads.
Cons
- Users still see other people's changes up to 5 s late. A manager's dashboard can miss an expense a colleague submitted 2 s ago.
- Synchronous commit adds one network round trip to every write, about 0.5 to 2 ms across availability zones in one region.
- Carrying a token across services and devices takes plumbing. A user who submits on mobile and checks on desktop has no token on the second device unless it lives server-side.
- Replicas fight replay conflicts. Long queries can be cancelled, or the primary's vacuum can be held back, depending on the settings you pick.
Trade-offs
Decisions you'll have to make, each with its price.
LSN token per session versus a fixed 10 s primary pin after any write
You gainLSN routing sends writers back to replicas as soon as one catches up, and it stays correct even when lag exceeds 10 s.
You payYou must plumb a token through the session and across internal service calls. Each service that writes must return its LSN.
Sync quorum ANY 1 of 2 with synchronous_mode_strict off
You gainZero lost commits on normal failover. If both replicas die, the primary keeps accepting writes asynchronously instead of blocking.
You payEach write takes roughly 1 ms longer. In the both-replicas-down window, a primary crash can still lose recent commits.
Evict replicas above 5 s of lag
You gainBounds how stale any display read can be, which product teams can reason about and document.
You payDuring the nightly import both replicas can cross 5 s together and all reads land on the primary. That is why the fallback pool is capped and imports are throttled.
hot_standby_feedback on versus max_standby_streaming_delay of 30 s
You gainFeedback on stops replica queries being cancelled by vacuum conflicts. A streaming delay lets replay wait up to 30 s for queries to finish.
You payFeedback holds back vacuum on the primary, so tables bloat while long replica queries run. A streaming delay adds up to 30 s of lag, which then triggers eviction.
Router in the application library versus a SQL proxy such as Pgpool-II
You gainThe application knows which reads guard writes and which user wrote what, so it can route by LSN and intent.
You payEvery service language needs the router logic, and a proxy can never be fully replaced for clients you do not control, such as BI tools.
How it fails
What goes wrong in production and how to prevent it.
All replicas exceed the lag limit during the nightly card import and 20,000 reads per second hit the primary.
What to doRoute fallback reads through a separate primary pool capped at 40 connections. Display reads that cannot get a connection within 50 ms receive a degraded response with a "data may be a few seconds old" banner, served from any replica regardless of lag. Throttle the import to keep WAL generation under about 40 MB per second.
An idle primary makes replicas look minutes behind, because pg_last_xact_replay_timestamp stops advancing when there are no commits.
What to doHave the primary update a single-row heartbeat table every second. Replay delay then reflects true lag. Alert when the heartbeat itself stops arriving.
Long export queries on a replica are cancelled with "canceling statement due to conflict with recovery".
What to doSend exports to a dedicated reporting replica with
max_standby_streaming_delay = 300s. Exclude it from the OLTP rotation, because its lag will regularly exceed 5 s.The old primary comes back after a network partition and accepts writes alongside the new leader (split brain).
What to doPatroni demotes any node that loses its etcd leader lock (TTL 30 s, loop_wait 10 s). HAProxy only routes to the node returning 200 on
/primary. The returning node is rewound withpg_rewindbefore rejoining as a replica.An approve endpoint checks status on a replica and acts twice on a double-click.
What to doMove every read that decides a write into the primary transaction with
SELECT ... FOR UPDATEorUPDATE ... WHERE status = 'pending'and check the row count. Add a lint rule that rejects replica reads inside write handlers.
In a system design interview
When to bring it up and how to explain it.
Bring this up when the design has a read-heavy relational store and the interviewer pushes on scale: a dashboard, feed, catalogue or any 10:1 read-to-write workload. Raise lag and read-your-writes yourself before they ask. That is the part that separates a strong answer from "just add replicas."
What you could say
Reads are about 95% of the traffic, so I'd add two streaming replicas behind a router in the data layer. Writes go to the primary, and so does any read that decides a write, like checking that a report is still pending before approving it. I'd do that check inside the write transaction with a row lock.
For read-your-writes, after each commit I'd grab the primary's WAL position and store it in the session for about 30 seconds. A poller tracks each replica's replayed position every 200 milliseconds. The router sends a read to any replica that has replayed past the user's position, and to the primary otherwise. Most users haven't written anything recently, so they hit any replica. I'd also evict replicas more than 5 seconds behind, and cap the primary fallback pool so a replica outage can't overload the primary.
For failover I'd run Patroni with synchronous mode, so every commit is flushed on at least one replica and only that replica can be promoted. That costs about a millisecond per write and means we never lose an acknowledged commit. HAProxy follows the leader, which also fences off the old primary.
Likely follow-ups
A user submits on their phone and immediately opens the desktop app. Do they see the expense?
Only if the token is server-side. I'd key the last-write LSN by user ID in Redis with a 30 s TTL instead of a per-device cookie, so any device or service handling that user's request reads the same minimum position. That costs one small lookup per request, which can be skipped for anonymous or read-only sessions.
What happens to read-your-writes during a failover?
The promoted node was the synchronous standby, so it has every commit the user was told about. Replicas reattach to the new timeline and keep replaying from there. If a token points past where the new leader currently is, no replica qualifies and reads go to the primary until new writes move its position forward. That is safe, just briefly more primary load.
When do replicas stop being enough?
When the primary is write-bound. Replicas replay every write, so they don't reduce write I/O, and each one adds WAL send overhead. If writes grow past what one node's disk and CPU can handle, or replay can't keep up and lag stays above the 5 s cap, the next step is sharding by company ID, with each shard keeping its own replicas.
Why not cache instead of adding replicas?
I'd do both for different reads. Policy lookups are hot and rarely change, so they belong in a cache. Approval queues are per manager and change constantly, so hit rates would be poor and invalidation hard. Replicas serve arbitrary queries with bounded staleness and no invalidation logic.
Relations with other guides
Patterns it's often confused or combined with.
- Cache-Aside: Invalidation, Stampedes, TTLs and Stale Reads
A cache in front of replicas compounds staleness: replica lag plus cache TTL. Populate the cache from the primary, or only from replicas past the writer's LSN, or the cache can freeze a pre-write value for its full TTL.
- CQRS: Separate Write and Read Models with Projections
Read replicas are the simplest form of separating reads from writes: same schema, same engine. CQRS goes further with read models shaped for queries, at the cost of building and maintaining the projection.
- Sharding: Splitting Data Across Nodes by Key
Replicas scale reads but not writes. When the primary's write load or storage outgrows one machine, sharding splits the data and each shard gets its own primary and replicas.
- Bulkhead: Isolate Resources So One Failure Stays Contained
The primary fallback pool is a bulkhead. Capping it at 40 connections stops a replica outage from letting display reads starve the write path.
- Change Data Capture: Stream Database Changes from the Log
CDC reads the same WAL that replicas replay, but feeds other systems such as search or analytics instead of an identical Postgres copy. LSNs give both a shared notion of position.
- Circuit breaker: fail fast when a dependency is down
The router's eviction rule acts like a circuit breaker per replica. A replica that fails polls is opened out of rotation and closed again on the first healthy poll.
Common questions
Short answers to the usual doubts.
Why compare LSNs instead of just pinning a user to the primary for a few seconds after a write?
A time window has to be longer than the worst lag you ever see. At Ledgerline that is 6 s during imports, so every writer would hit the primary for 6 s even when replicas are 50 ms behind. An LSN check releases the user to a replica as soon as one has caught up, usually within milliseconds. It also stays correct when lag exceeds the window, which a timer cannot.
Does the poller's 200 ms delay ever cause a stale read?
No. The poller can only under-report how far a replica has replayed, because replay moves forward. A replica that looks caught up in the cache really is caught up. The cost is occasionally sending a read to the primary that a replica could have served.
Why not set synchronous_commit to remote_apply so every replica is always current?
remote_apply makes each commit wait until the standby has replayed the change, not just flushed it. Any replay stall, such as a long query holding a conflicting lock, then stalls every write on the primary. You would trade an occasional primary-pinned read for write latency tied to your slowest replica. Use on with a sync quorum for durability, and LSN routing for freshness.
How many replicas should I run?
Size for losing one. If the read load needs two replicas' worth of capacity, run three, so a replica outage or rebuild does not push everything back to the primary. Keep at least two in the sync quorum so one replica failing does not leave commits unprotected.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Relational databases (SQL) in productionTake the test