// Data & Databases · 04
Replication
Keep copies of the data on several nodes for reads and failover.
How it fits together
- Web app uses / calls Primary (1 write)
- Web app uses / calls Replica 1 (2 read)
- Web app uses / calls Replica 2 (2 read)
- Primary replicates / copies Replica 1 (3 async log ship)
- Primary replicates / copies Replica 2 (3 async log ship)
- Primary fails / error path Primary down (crash)
Spot it
- The primary is busy serving read queries
- Losing the database host means losing the site
- Reports slow down checkout
It costs
Async replicas can serve stale reads; sync replicas add latency to every write.
In code
public interface IReplicaLag{ TimeSpan Current { get; }}public sealed class DatabaseRouter(string primary, string replica, IReplicaLag lag){ private static readonly TimeSpan MaxLag = TimeSpan.FromSeconds(5); public string ForWrite() => primary; // A user who just wrote reads from the primary (read-your-writes) public string ForRead(bool recentlyWrote) => recentlyWrote || lag.Current > MaxLag ? primary : replica;}Go deeperThe full explanation and what to ask for · 1 min readExpandCollapse
With a single leader, every write goes to the primary, which ships its log to replicas. Asynchronous replication keeps writes fast, but replicas lag and a failover can lose the last few committed transactions. Synchronous replication waits for a replica to confirm: no loss, but slower writes and a dependency on that replica.
The classic mistake is sending every read to a replica, so a user saves and immediately sees the old value. Keep the author on the primary for a short window after a write, or route by query type.
Replication scales reads and adds redundancy, not write capacity: every replica still applies every write. For that you need sharding. Failover also needs fencing, so an old primary cannot keep accepting writes after a new one is promoted.
Ask for it
- primary / replica
- synchronous vs asynchronous
- replication lag
- read replica
- read-your-writes
- failover
Route read-only queries (reports, search, list pages) to a read replica and keep writes and read-after-write paths on the primary. Use a connection string per role, expose replication lag as a metric, and fall back to the primary when lag passes 5 seconds.