Playground: replication lagPlayground: replication lag
Writes land on the primary instantly, replicas catch up after a lag you control. Read from a replica during the lag and you get stale data. That is eventual consistency.Writes primary pe turant aate hain, replicas tumhare control wale lag ke baad catch up karte hain. Lag ke dauran replica se read karo to stale data milta hai. Yahi eventual consistency hai.
Replication: why your database has clones
Replication keeps copies of the same data on multiple servers. It buys three things: read scaling (replicas answer reads, the primary only writes), availability (primary dies, a replica is promoted), and proximity (replicas in other regions serve local users faster). The shape is almost always single-leader: one primary accepts writes; followers apply the same changes in the same order from the primary's log (WAL/binlog/oplog).
Sync vs async: the fundamental choice
- Synchronous: a write is confirmed only after a replica has it too. Survives primary death with zero loss, but every write is as slow as the slowest replica, and a dead replica blocks writes.
- Asynchronous: primary confirms immediately; replicas catch up behind. Fast and resilient, but a primary crash can lose the last few seconds of writes.
- Semi-sync (common compromise): one sync replica, the rest async: bounded staleness, bounded risk.
Replication lag and read-your-writes
Async replicas lag: milliseconds normally, seconds or worse under load. The user who just updated their profile and reads from a lagging replica sees the old value. Fixes: read-your-writes (route the writer's own reads to the primary for a window, or wait for the replica to pass the write's log position), pin critical reads (balances) to the primary always, and monitor lag as a first-class metric.
Failover: the dangerous 60 seconds
- Detect: health checks and heartbeats decide the primary is dead (too eager = flapping; too slow = long outage).
- Elect: remaining nodes choose a new primary. This needs consensus (a majority must agree), or a network partition can produce split-brain: two primaries accepting writes, diverging data, reconciliation nightmare.
- Repoint: clients and the old primary (when it returns, demoted) switch to the new leader. DNS, a proxy (ProxySQL) or a discovery service (etcd/ZooKeeper) handles this.
Multi-leader and leaderless (know they exist)
Multi-leader: primaries in multiple regions accept local writes and sync to each other: great regional latency, but write conflicts need resolution (last-write-wins, CRDTs, app logic). Leaderless (Dynamo-style): no primary; clients write to W of N replicas and read from R of N (W + R > N for consistency). Cassandra/DynamoDB. Maximum availability, eventual consistency, conflict handling pushed to reads.
Worked example: Postgres for a growing SaaS
Primary in the main region; 2 async read replicas for dashboards and search indexing; 1 semi-sync replica as the failover candidate (managed RDS promotes it in ~60-120s); pgbouncer pooling; lag alerting at 5s; writes always to the primary; "my own recent writes" reads pinned to the primary for 10s after a write.
Common interview traps
- "Add replicas" without saying sync or async and what that implies.
- Failover described in one line with no detection, election or split-brain story.
- Sending all reads to replicas including ones that must be fresh.
Interview Q&A
Q: After a failover, a user says their last order vanished. Explain.
A: Classic async loss window: the order was written to the old primary after its last replication to the promoted replica. Mitigations: semi-sync on one replica, or on failover check the new primary's log position vs clients' last confirmed writes and reconcile (order systems usually re-verify with the payment gateway anyway).
Q: How do replicas stay in sync, concretely?
A: The primary appends every change to a write-ahead log; replicas stream and replay it in order, tracking their replay position (LSN/GTID). Lag = primary position minus replica position.
Replication: tumhare database ke clones kyun hain
Replication same data ki copies multiple servers par rakhta hai. Teen cheezein milti hain: read scaling (replicas reads ke jawab dein, primary sirf writes), availability (primary mara, ek replica promote ho gaya), aur proximity (doosre regions ke replicas local users ko fast serve karein). Shape almost hamesha single-leader hoti hai: ek primary writes accept karta hai; followers primary ke log (WAL/binlog/oplog) se same changes same order mein apply karte hain.
Sync vs async: fundamental choice
- Synchronous: write tabhi confirm hoti hai jab replica ke paas bhi ho. Primary death par zero loss, par har write utni slow jitna slowest replica, aur mara replica writes block kar deta hai.
- Asynchronous: primary turant confirm; replicas peeche peeche catch up. Fast aur resilient, par primary crash aakhri kuch seconds ki writes le sakta hai.
- Semi-sync (common compromise): ek sync replica, baaki async: bounded staleness, bounded risk.
Replication lag aur read-your-writes
Async replicas lag karte hain: normally milliseconds, load par seconds ya worse. Jis user ne abhi profile update ki, agar wo lagging replica se pade to purana value dikhega. Fixes: read-your-writes (writer ki apni reads kuch window tak primary par route karo, ya replica ke write ke log position cross karne ka wait karo), critical reads (balances) hamesha primary par pin karo, aur lag ko first-class metric bana kar monitor karo.
Failover: wo khatarnak 60 seconds
- Detect: health checks aur heartbeats decide karte hain primary mara (zyada eager = flapping; zyada slow = lambi outage).
- Elect: bache nodes naya primary chunte hain. Iske liye consensus chahiye (majority agree kare), warna network partition split-brain bana sakta hai: do primaries writes accept karte hue, data diverge, reconciliation ka khaufnaak sapna.
- Repoint: clients aur purana primary (wapas aane par, demoted) naye leader par switch karein. DNS, proxy (ProxySQL) ya discovery service (etcd/ZooKeeper) ye handle karta hai.
Multi-leader aur leaderless (pata hona chahiye)
Multi-leader: multiple regions ke primaries local writes accept karte hain aur ek doosre se sync: regional latency badhiya, par write conflicts ka resolution chahiye (last-write-wins, CRDTs, app logic). Leaderless (Dynamo-style): koi primary nahi; clients N mein se W replicas ko likhte hain aur R se padhte hain (consistency ke liye W + R > N). Cassandra/DynamoDB. Maximum availability, eventual consistency, conflict handling reads par.
Worked example: badhte SaaS ke liye Postgres
Primary main region mein; 2 async read replicas dashboards aur search indexing ke liye; 1 semi-sync replica failover candidate (managed RDS ~60-120s mein promote karta hai); pgbouncer pooling; 5s par lag alerting; writes hamesha primary; "mere apne recent writes" reads write ke baad 10s tak primary par pin.
Common interview traps
- "Replicas laga do" bina bataye sync ya async, aur uska matlab kya.
- Failover ek line mein, bina detection, election ya split-brain story ke.
- Saari reads replicas par bhejna, unhe bhi jo fresh honi zaroori hain.
Interview Q&A
Q: Failover ke baad user kehta hai uska last order gayab. Explain karo.
A: Classic async loss window: order purane primary par tab likha gaya jab wo promoted replica tak replicate nahi hua tha. Mitigations: ek replica par semi-sync, ya failover par naye primary ka log position clients ke last confirmed writes se compare karke reconcile (order systems waise bhi payment gateway se re-verify karte hain).
Q: Replicas sync kaise rehte hain, concretely?
A: Primary har change write-ahead log mein append karta hai; replicas use order mein stream karke replay karte hain, apni replay position (LSN/GTID) track karte hue. Lag = primary position minus replica position.