← All lessons
How database replication works
One primary, one replica
App
Primary
Replica
app.js
// every write goes to the primaryawait primary.query("INSERT INTO orders VALUES (42, 'pending')");await primary.query("UPDATE orders SET status = 'paid' WHERE id = 42"); // reads can go to a replicaawait replica.query("SELECT status FROM orders WHERE id = 42");replication.js
// on the primary: log first, then commitconst lsn = wal.append(record);wal.flush();commit(tx);walsender.stream(lsn); // on the replica: replay whatever arriveswalreceiver.on("record", (rec) => { wal.write(rec); replay(rec); // readers see it from here on});Read right after a write then drag the lag
profile.js
await primary.query("UPDATE users SET name = $1 WHERE id = 7", [name]); // a moment later, read it backconst db = route === "primary" ? primary : replica;const { rows } = await db.query("SELECT name FROM users WHERE id = 7");read-your-writes.js
// or wait until the replica has replayed that farconst { rows: [w] } = await primary.query("SELECT pg_current_wal_lsn() AS lsn");for (;;) { const { rows: [r] } = await replica.query( "SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn AS ready", [w.lsn]); if (r.ready) break; await sleep(20);}The primary crashes async vs sync replication
App
Primary
Replica
postgresql.conf
# postgresql.conf on the primary # async, the default: commit after the local flushsynchronous_standby_names = '' # sync: also wait for replica1 to flush itsynchronous_standby_names = 'replica1'synchronous_commit = onTopics
Next: How database sharding works
Open lesson