Node.js › Databases

What is database replication, and how does a Node.js application typically route reads to replicas while sending writes to a primary?

Advanced

Answer

Replication maintains one or more read-only copies (replicas) of a primary database, continuously synchronized with the primary's writes -- read-heavy applications route SELECT queries to replicas (distributing read load across multiple database servers) while all writes go exclusively to the primary, since replicas typically can't accept writes and there's a brief replication lag before a replica reflects the primary's most recent writes.
const primaryPool = new Pool({ connectionString: PRIMARY_DB_URL });
const replicaPool = new Pool({ connectionString: REPLICA_DB_URL });

async function getUser(id) { return replicaPool.query('SELECT * FROM users WHERE id = $1', [id]); }
async function updateUser(id, data) { return primaryPool.query('UPDATE users SET ... WHERE id = $1', [id]); }
Real-world example A high-traffic content platform routes all its read-heavy product-listing queries to a pool of three read replicas while sending all cart and checkout writes to the single primary database, significantly reducing load on the primary and allowing read capacity to scale independently of write capacity.

Common follow-ups: What problems can arise from replication lag if an application immediately reads data right after writing it?;How do you handle read-your-own-writes consistency when a user needs to see their own recent write immediately?