Module 3: Databases
Replication
Primary–replica vs multi-leader replication — read scaling, failover, sync vs async durability, lag, and conflict trade-offs.
Replication copies data to more nodes for durability, read scale, and failover. Topology choice — single leader vs multi-leader vs leaderless — drives the consistency headaches you must name in interviews.
What you will learn
- Explain why systems replicate data
- Compare single-leader (primary–replica) and multi-leader topologies
- Contrast synchronous vs asynchronous replication
- Handle replication lag and read-your-writes correctly
- Pick a topology for a product constraint and call out conflicts/failover
Why replicate?
- A single copy is a single point of failure and a single read bottleneck. Replication is how you buy durability and scale — with new failure modes.
- Durability — survive disk/node loss with extra copies
- Read scaling — spread SELECTs across replicas
- Failover — promote a replica when the primary dies
- Locality — keep a copy closer to users in another region
- Cost — more storage, network, and operational complexity
Single-leader (primary–replica)
- One primary accepts writes. Replicas apply the replication log and serve reads (and stand by for failover).
- Clients write only to the primary (or through a writer endpoint)
- Replicas subscribe to the WAL/binlog/change stream
- Simple conflict model: one writer ⇒ no multi-writer merge for the same row
- Default interview choice for most OLTP designs
- Also called master–slave / leader–follower — same idea
Sync vs async replication
- How eagerly replicas confirm a write decides durability vs latency.
- Async — primary acks fast; replica may lag; risk of data loss on primary crash
- Synchronous — wait for at least one replica ack; stronger durability, higher write latency
- Semi-sync — middle ground used by many production databases
- Cross-AZ sync is common; cross-region sync is expensive in RTT
- Say which durability you are buying when you pick sync
Replication lag & read-your-writes
- Async replicas are eventually consistent. Lag is normal — surprise is what fails interviews.
- Replica lag = delay between primary commit and replica apply
- User writes then immediately reads a replica ⇒ may miss their own update
- Mitigations: read-your-writes from primary, session sticky to primary briefly, or version/timestamp checks
- Monitor lag; shed replica traffic when lag exceeds an SLA
- Never pretend replica reads are always identical to primary reads
Failover
- When the primary dies, a replica must become the new writer — carefully.
- Detect failure (heartbeats/health checks) without flapping on brief blips
- Promote the most up-to-date eligible replica
- Reconfigure clients or VIP/DNS to the new primary
- Fencing: ensure the old primary cannot accept writes after split-brain
- RPO/RTO depend on sync mode and automation quality
Multi-leader (multi-master)
- More than one node accepts writes — useful for multi-region write locality, harder for correctness.
- Users can write to a local region primary
- Same row updated in two regions ⇒ conflicts are inevitable
- Needs conflict resolution: LWW, merge functions, CRDTs, or app rules
- Operationally heavier: monitoring conflicts, not only lag
- Choose only when single-leader write latency/availability is unacceptable
Leaderless replication (brief)
- Some stores let clients write to several replicas and use quorums (think Dynamo-style). Mention it as a third family.
- Writes/reads succeed with W/R quorum among N replicas
- Often paired with hinted handoff and read repair
- Tunable consistency: W+R > N for stronger read overlap
- Great for availability; conflict/version handling is on you
- Bring it up when the interviewer asks about Cassandra-like designs
Topology comparison
- Use this side-by-side when asked which replication style to pick.
- Single-leader — simple writes, easy reasoning; primary is a write hotspot
- Multi-leader — local writes, conflict hell; multi-region apps sometimes need it
- Leaderless — high availability, quorum math, application-visible versions/conflicts
- Reads — all can scale reads; lag/conflict semantics differ
- Interview default — single-leader unless the prompt forces otherwise
Product mapping
- Map topology to product needs, not to buzzwords.
- Bank ledger / inventory reservation → single-leader, often sync or semi-sync to a standby
- Social feed reads → single-leader + many async read replicas
- Global collaborative doc with regional writes → multi-leader or specialized CRDT store
- High-availability shopping cart metadata → sometimes leaderless/quorum stores
- Always state what the user sees under lag or conflict
Common misconceptions
- These lines sound safe but cost points.
- “Replicas replace backups” — bad deletes replicate too; use PITR backups
- “Async replication never loses data” — primary crash can lose unreplicated commits
- “Multi-leader means no conflicts if we shard by user” — only if every row has one home forever
- “Failover is instant and lossless” — depends on sync mode and fencing
- Ignoring read-your-writes after a POST → redirect → GET from a replica
Interview framing
- Use this order when the data tier needs scale or HA.
- State goals: durability, read QPS, multi-region writes, or failover RPO/RTO
- Pick single-leader by default; justify exceptions
- Choose sync vs async and name the latency/durability trade-off
- Explain replica lag + one read-your-writes mitigation
- Sketch failover and fencing in one sentence
Quick revision checklist
- Call out replication lag explicitly.
- Separate sync vs async durability from read freshness.
- Default to single primary + read replicas.
- Name a read-your-writes strategy after user writes.
- Mention fencing on failover to avoid split-brain.
- Remind: replicas are not backups.
FAQs
Does replication replace backups?
No. Replicas can amplify bad deletes or corruption. Point-in-time backups (and tested restores) remain mandatory.
Why can I read stale data from a replica?
Async replicas apply changes after the primary commits. Until catch-up finishes, reads can miss recent writes — including the user’s own.
When do I need multi-leader?
When a single write primary cannot meet latency or availability needs across regions and you accept conflict resolution. Most apps should not start there.
Is synchronous replication always better?
It improves durability (lower RPO) but raises write latency and can reduce availability if replicas are slow or unreachable. Match it to the RPO goal.
How many replicas do I need?
Enough for read QPS and failure domains (e.g. another AZ). More replicas help reads; they do not fix a write-hot primary — that needs vertical scale, caching, or sharding.
What is split-brain?
Two nodes both believe they are primary and accept writes. Prevent it with fencing, locks/leases, or consensus so only one writer is active.
Learner’s Task
- Practice out loud for 8–10 minutes. Pick a topology and defend the lag/durability trade-offs.
- Choose a product (e-commerce orders or a social feed) and state goals: read QPS, RPO, multi-region or not.
- Draw single-leader + 2 replicas; mark where writes go and where reads may go.
- Pick sync or async to a standby and say what happens if the primary dies mid-write.
- Describe one read-your-writes bug after signup/profile update and your mitigation.
- Write a 4-sentence closing: topology, sync mode, lag handling, and why you rejected multi-leader (or when you would use it).