Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 03 · Partitioning, Replication & CachingChapter 15 of 33
14.
Phase 03Read time ~27 minDifficulty advanced

Database Replication

In this chapter
  • 01Introduction
  • 02Why Do We Need Replication?
  • 03Database failure
  • 04Read scaling
  • 05Primary and Replica
  • 06Leader/Follower Terminology
  • 07How Replication Works
  • 08Synchronous Replication
  • 09Advantage
  • 10Disadvantage
  • 11Asynchronous Replication
  • 12Advantage
  • 13Disadvantage
  • 14Synchronous vs Asynchronous Replication
  • 15Semi-Synchronous Replication
  • 16Replication Lag
  • 17Why Replication Lag Happens
  • 18Network latency
  • 19Replica CPU saturation
  • 20Disk I/O bottlenecks
  • 21Large transactions
  • 22Heavy read workload
  • 23Cross-region replication
  • 24Read Replicas
  • 25Read Scaling Does Not Mean Write Scaling
  • 26Read-After-Write Consistency Problem
  • 27Read-Your-Writes Consistency
  • 28Stale Reads
  • 29Routing Reads to Replicas
  • 30Load Balancing Across Replicas
  • 31Failover
  • 32Manual Failover
  • 33Automatic Failover
  • 34Split-Brain
  • 35Fencing
  • 36Leader Election
  • 37Replica Promotion
  • 38Replication Topologies
  • 39Single Primary
  • 40Cascading Replication
  • 41Multi-Primary Replication
  • 42Leaderless Replication
  • 43Quorum Concepts
  • 44Multi-Region Replication
  • 45Cross-Region Latency
  • 46RPO and Replication
  • 47RTO and Failover
  • 48Replication vs Backup
  • 49Replication
  • 50Backup
  • 51Replication and Disaster Recovery
  • 52Monitoring Replication
  • 53Replication lag
  • 54Replica health
  • 55Replay/apply rate
  • 56Write throughput
  • 57What Happens When a Replica Falls Behind?
  • 58Replica Health vs Replica Freshness
  • 59Read Scaling Architecture
  • 60Primary Bottleneck Still Exists
  • 61Connection Routing
  • 62Failover and Existing Connections
  • 63Replication and Idempotency
  • 64Conflict Handling
  • 65Single-Primary vs Multi-Primary
  • 66Common Replication Failure Modes
  • 67Failure 1: Replica lag
  • 68Failure 2: Network partition
  • 69Failure 3: Replica crash
  • 70Failure 4: Storage failure
  • 71Failure 5: Replication stream failure
  • 72Failure 6: Split-brain
  • 73Failure 7: Incorrect failover
  • 74Failure 8: Application still points to old primary
  • 75Common Mistakes
  • 76Mistake 1: Thinking replicas are backups
  • 77Mistake 2: Assuming replicas are always current
  • 78Mistake 3: Sending every read to replicas
  • 79Mistake 4: Assuming more replicas increase write capacity
  • 80Mistake 5: Ignoring failover routing
  • 81Mistake 6: Ignoring split-brain
  • 82Mistake 7: Ignoring replication lag
  • 83Mistake 8: Blindly retrying writes
  • 84Real-World Architecture Example: E-Commerce
  • 85Practical Exercise
  • 86Mini Project — Build a Read/Write Database Router
  • 87Interview Questions
  • 88Beginner
  • 89Intermediate
  • 90Advanced
  • 91Interview Scenario
  • 92Question
  • 93Production Replication Checklist
  • 94Architecture
  • 95Consistency
  • 96Availability
  • 97Safety
  • 98Performance
  • 99Monitoring
  • 100Recovery
  • 101Master Mental Model
  • 102Chapter Summary
  • 103Key Terms
  • 104Final Interview Checklist
  • 105What's Next?
  • 106Chapter 14 — Database Partitioning & Sharding
In this chapter (106 sections)
01Introduction02Why Do We Need Replication?03Database failure04Read scaling05Primary and Replica06Leader/Follower Terminology07How Replication Works08Synchronous Replication09Advantage10Disadvantage11Asynchronous Replication12Advantage13Disadvantage14Synchronous vs Asynchronous Replication15Semi-Synchronous Replication16Replication Lag17Why Replication Lag Happens18Network latency19Replica CPU saturation20Disk I/O bottlenecks21Large transactions22Heavy read workload23Cross-region replication24Read Replicas25Read Scaling Does Not Mean Write Scaling26Read-After-Write Consistency Problem27Read-Your-Writes Consistency28Stale Reads29Routing Reads to Replicas30Load Balancing Across Replicas31Failover32Manual Failover33Automatic Failover34Split-Brain35Fencing36Leader Election37Replica Promotion38Replication Topologies39Single Primary40Cascading Replication41Multi-Primary Replication42Leaderless Replication43Quorum Concepts44Multi-Region Replication45Cross-Region Latency46RPO and Replication47RTO and Failover48Replication vs Backup49Replication50Backup51Replication and Disaster Recovery52Monitoring Replication53Replication lag54Replica health55Replay/apply rate56Write throughput57What Happens When a Replica Falls Behind?58Replica Health vs Replica Freshness59Read Scaling Architecture60Primary Bottleneck Still Exists61Connection Routing62Failover and Existing Connections63Replication and Idempotency64Conflict Handling65Single-Primary vs Multi-Primary66Common Replication Failure Modes67Failure 1: Replica lag68Failure 2: Network partition69Failure 3: Replica crash70Failure 4: Storage failure71Failure 5: Replication stream failure72Failure 6: Split-brain73Failure 7: Incorrect failover74Failure 8: Application still points to old primary75Common Mistakes76Mistake 1: Thinking replicas are backups77Mistake 2: Assuming replicas are always current78Mistake 3: Sending every read to replicas79Mistake 4: Assuming more replicas increase write capacity80Mistake 5: Ignoring failover routing81Mistake 6: Ignoring split-brain82Mistake 7: Ignoring replication lag83Mistake 8: Blindly retrying writes84Real-World Architecture Example: E-Commerce85Practical Exercise86Mini Project — Build a Read/Write Database Router87Interview Questions88Beginner89Intermediate90Advanced91Interview Scenario92Question93Production Replication Checklist94Architecture95Consistency96Availability97Safety98Performance99Monitoring100Recovery101Master Mental Model102Chapter Summary103Key Terms104Final Interview Checklist105What's Next?106Chapter 14 — Database Partitioning & Sharding

1. Introduction#

Database replication means maintaining copies of the same database data on multiple database nodes.

Instead of having:

Application
    |
    v
[ One Database ]

we can have:

                 +----------------+
                 |   Application  |
                 +-------+--------+
                         |
                         v
                  +-------------+
                  |   Primary   |
                  +------+------+ 
                         |
              Replication stream
                         |
             +-----------+-----------+
             |                       |
             v                       v
       +-----------+           +-----------+
       |  Replica  |           |  Replica  |
       +-----------+           +-----------+

Replication is primarily used for:

  • high availability
  • read scaling
  • disaster recovery
  • reducing dependence on one database node
  • geographic distribution
  • maintaining additional copies of data

Replication is different from sharding.

Replication copies data.

Sharding splits data.

That distinction is extremely important in system design.


2. Why Do We Need Replication?#

Imagine an application with one database:

Users
  |
  v
Load Balancer
  |
  v
Application Servers
  |
  v
+----------------+
|   PostgreSQL   |
|    Primary     |
+----------------+

This creates several problems.

2.1 Database failure#

If the database crashes:

Application
    |
    X
Database DOWN

The application may become unavailable.

Replication gives us another copy.

             +-------------+
             |   Primary   |
             +------+------+
                    |
                    v
             +-------------+
             |   Replica   |
             +-------------+

If the primary fails, the replica can potentially be promoted.


2.2 Read scaling#

Suppose the application receives:

  • 10,000 reads/second
  • 1,000 writes/second

If every operation goes to one database:

10,000 reads
+
1,000 writes
        |
        v
   One Database

The database can become a bottleneck.

With read replicas:

                    +-------------+
Writes -----------> |   Primary   |
                    +------+------+
                           |
                    Replication
                           |
             +-------------+-------------+
             |                           |
             v                           v
       +-----------+               +-----------+
Reads->| Replica 1 |       Reads-> | Replica 2 |
       +-----------+               +-----------+

Reads can be distributed across replicas.


3. Primary and Replica#

A common replication architecture has:

  • one primary
  • one or more replicas

The primary accepts writes.

Replicas maintain copies of the primary's data.

Example:

                 Writes
                    |
                    v
             +-------------+
             |   Primary   |
             +------+------+
                    |
              Replication
                    |
        +-----------+-----------+
        |                       |
        v                       v
 +-------------+         +-------------+
 |  Replica 1  |         |  Replica 2  |
 +-------------+         +-------------+
        ^                       ^
        |                       |
        +------- Reads ----------+

Different systems use different terminology:

Term Meaning
Primary Node responsible for writes
Replica Copy receiving replicated data
Leader Another common name for primary
Follower Another common name for replica
Read replica Replica primarily used for reads
Standby Replica maintained for availability/failover

The exact terminology varies by database technology.


4. Leader/Follower Terminology#

You may see:

Leader -> Followers

instead of:

Primary -> Replicas

Conceptually they are often similar.

For example:

Leader
  |
  +----> Follower 1
  |
  +----> Follower 2

The important thing is not the terminology.

The important questions are:

  1. Who accepts writes?
  2. How is data replicated?
  3. When is a write considered committed?
  4. How much replication lag is allowed?
  5. What happens when the leader fails?
  6. How are reads routed?

These are system-design questions.


5. How Replication Works#

A simplified write flow:

Client
  |
  | WRITE
  v
Primary
  |
  | 1. Persist change
  |
  | 2. Generate replication record
  v
Replication Stream
  |
  +---------> Replica 1
  |
  +---------> Replica 2

The exact mechanism depends on the database.

A database may replicate:

  • physical/log-based changes
  • logical changes
  • operations
  • transactions
  • write-ahead log records

A useful conceptual model is:

Application
     |
     v
Primary
     |
     v
Change Log
     |
     +----------+
     |          |
     v          v
 Replica A   Replica B

The change log allows replicas to replay changes.


6. Synchronous Replication#

In synchronous replication, the primary waits for one or more replicas to acknowledge replication before considering the write sufficiently committed according to the configured policy.

Conceptually:

Client
  |
  v
Primary
  |
  +------> Replica
  |          |
  |       ACK
  |          |
  +<---------+
  |
  v
Client ACK

Advantage#

The replica is much less likely to be behind when the primary acknowledges the write.

Disadvantage#

The write now depends on another node and the network between them.

If the replica is slow:

Primary
   |
   | waiting
   v
Replica
   |
   | slow
   v
Higher write latency

So synchronous replication can improve durability/consistency characteristics at the cost of latency and availability under certain failure conditions.


7. Asynchronous Replication#

With asynchronous replication, the primary can acknowledge the client without waiting for the replica to confirm that it has applied the change.

Client
  |
  v
Primary
  |
  +-----------------> Replica
  |
  v
ACK Client

The replica may receive the change shortly afterward.

Advantage#

Lower write latency and less dependency on replica/network availability.

Disadvantage#

Replication lag can occur.

If the primary fails before a change reaches a replica, that replica may not contain the newest data.


8. Synchronous vs Asynchronous Replication#

Property Synchronous Asynchronous
Primary waits for replica acknowledgment Usually yes No
Write latency Higher Lower
Replica freshness Usually stronger Can lag
Failure sensitivity Higher Lower
Cross-region use Expensive in latency Common
Potential data loss after primary failure Lower depending on configuration Possible

Neither is universally better.

The choice depends on requirements.


9. Semi-Synchronous Replication#

Some systems provide configurations between fully synchronous and fully asynchronous behavior.

A simplified model:

Primary
   |
   +---- Replica A
   |
   +---- Replica B

The primary may wait for acknowledgment from at least one replica while other replicas continue asynchronously.

This can provide a compromise between:

  • durability
  • availability
  • write latency

The exact behavior is database-specific.


10. Replication Lag#

Replication lag is the delay between a change being committed or generated on the primary and becoming available on a replica.

Example:

Primary:
User balance = ₹500
 
Replica:
User balance = ₹400

The primary was updated first.

The replica is temporarily stale.


11. Why Replication Lag Happens#

Possible causes include:

1. Network latency#

Primary ----slow network----> Replica

2. Replica CPU saturation#

The replica receives changes faster than it can apply them.

3. Disk I/O bottlenecks#

The replica cannot persist changes quickly enough.

4. Large transactions#

A large transaction can take significant time to replicate/apply.

5. Heavy read workload#

If the replica is overloaded with reads, replication processing may compete for resources.

6. Cross-region replication#

Geographic distance introduces network latency.


12. Read Replicas#

Read replicas are replicas used to serve read traffic.

Example:

                 +-------------+
                 |   Primary   |
                 +------+------+
                        |
                  Replication
                        |
          +-------------+-------------+
          |                           |
          v                           v
    +-----------+               +-----------+
    | Replica 1 |               | Replica 2 |
    +-----------+               +-----------+
          ^                           ^
          |                           |
        Reads                       Reads

The application can route:

POST /orders
    -> Primary
 
GET /orders/123
    -> Replica

This is useful for read-heavy workloads.


13. Read Scaling Does Not Mean Write Scaling#

A common misconception:

Adding read replicas automatically increases write capacity.

Usually it does not.

If:

Writes = 10,000/sec

and all writes still go to one primary:

                  10k writes
                      |
                      v
                 +---------+
                 | Primary |
                 +---------+

the primary remains the write bottleneck.

Read replicas primarily help with reads.

To scale writes, systems may eventually need techniques such as:

  • partitioning
  • sharding
  • workload redesign
  • batching
  • asynchronous processing
  • multiple writable nodes
  • database-specific distributed architectures

14. Read-After-Write Consistency Problem#

Consider:

Client
  |
  | 1. Create order
  v
Primary
  |
  | success
  v
Client
  |
  | 2. Immediately GET order
  v
Replica

Suppose replication has not caught up.

The replica might return:

404 Not Found

even though the order was successfully created.

This is a classic replica-lag problem.


15. Read-Your-Writes Consistency#

A user often expects:

If I successfully write something, I should immediately be able to see it.

This is called a read-your-writes expectation.

A common solution is to route a user's reads to the primary for a short period after a write.

Write
  |
  v
Primary
  |
  v
User
 
Immediate read
  |
  v
Primary

Later:

Read
  |
  v
Replica

Another approach is to use replication positions/consistency mechanisms provided by the database.

The exact implementation is database-specific.


16. Stale Reads#

A stale read occurs when a replica returns older data than the current primary state.

Example:

Primary:
status = "PAID"
 
Replica:
status = "PENDING"

This may be acceptable for some workloads.

Examples where stale data may be tolerable:

  • analytics dashboards
  • recommendation feeds
  • product view counts
  • historical reports

Examples where stale data can be problematic:

  • payment status
  • account balance
  • inventory availability
  • authorization decisions

The acceptable staleness depends on business requirements.


17. Routing Reads to Replicas#

A service may use a database abstraction:

                    Application
                         |
             +-----------+-----------+
             |                       |
          Writes                    Reads
             |                       |
             v                       v
         Primary              Read Router
                                     |
                         +-----------+-----------+
                         |                       |
                         v                       v
                    Replica 1              Replica 2

The read router can:

  • distribute reads
  • remove unhealthy replicas
  • avoid overloaded replicas
  • account for replication lag

18. Load Balancing Across Replicas#

Suppose there are three replicas:

              Read Traffic
                   |
                   v
             Read Balancer
              /    |    \
             /     |     \
            v      v      v
        Replica1 Replica2 Replica3

Possible algorithms include:

  • round robin
  • weighted routing
  • least connections
  • health-aware routing

But there is an additional database-specific concern:

replication freshness.

A healthy replica may still be too far behind.

Therefore, production systems may consider:

Health
+
Load
+
Replication Lag

when selecting a replica.


19. Failover#

Suppose:

Primary
   |
   +---- Replica 1
   |
   +---- Replica 2

The primary crashes.

A replica may be promoted:

             Replica 1
                 |
                 v
             New Primary

Applications then need to discover the new primary.


20. Manual Failover#

With manual failover:

Primary fails
     |
     v
Operator detects problem
     |
     v
Operator promotes replica
     |
     v
Application reconnects

Advantages:

  • more human control
  • useful for carefully managed environments

Disadvantages:

  • slower recovery
  • human error
  • operational burden

21. Automatic Failover#

With automatic failover:

Primary fails
     |
     v
Failure detection
     |
     v
Leader election / coordination
     |
     v
Replica promoted
     |
     v
Applications redirected

This can reduce recovery time.

However, automatic failover is difficult to implement safely.

A system must avoid promoting two nodes simultaneously.


22. Split-Brain#

Split-brain occurs when multiple nodes incorrectly believe they are the active primary.

Example:

          Network Partition
             /       \
            /         \
           v           v
       Primary A    Primary B
          |            |
       accepts       accepts
       writes        writes

Now two nodes may independently accept conflicting writes.

This can create serious data consistency problems.


23. Fencing#

Fencing is a technique for preventing an old or disconnected primary from continuing to act as the active writer.

Conceptually:

Old Primary
    |
    X
Fenced / prevented from writing
 
New Primary
    |
    v
Accepts writes

The exact fencing mechanism depends on the infrastructure.

The core principle is:

Before promoting a new writer, make sure the old writer cannot continue safely writing.

This is one of the most important ideas in failover design.


24. Leader Election#

In automatic failover, nodes may need to agree on which node becomes leader.

Simplified:

Node A
Node B
Node C
   |
   v
Coordination
   |
   v
Leader = Node B

Distributed coordination systems may use consensus protocols to make such decisions.

We will study distributed coordination in much greater depth later in the course.

For now remember:

Failover is not simply “pick another server.”

It requires coordinated ownership of the write role.


25. Replica Promotion#

A replica can be promoted to primary.

Before promotion, consider:

  • replication lag
  • health
  • data completeness
  • transaction state
  • connectivity
  • whether the old primary is truly unavailable
  • application routing

Example:

Before:
 
Primary A
   |
   +---- Replica B
   +---- Replica C
 
After:
 
Primary B
   |
   +---- Replica C

Replica B becomes the new writer.


26. Replication Topologies#

Replication can be organized in different ways.

26.1 Single Primary#

        Primary
        /     \
       v       v
   Replica   Replica

Most straightforward model.


26.2 Cascading Replication#

Instead of every replica receiving directly from the primary:

Primary
   |
   v
Replica A
   |
   +----> Replica B
   |
   +----> Replica C

This can reduce direct replication load on the primary in some architectures.

But it introduces additional dependency and potentially more replication lag.


27. Multi-Primary Replication#

Multiple nodes can accept writes.

Primary A <------> Primary B
     ^                 ^
     |                 |
   Writes            Writes

Advantages:

  • writes can be geographically closer to users
  • can reduce dependency on one writer

Challenges:

  • concurrent updates
  • conflict detection
  • conflict resolution
  • ordering
  • consistency
  • failover complexity

Example:

User in India
     |
     v
Primary India
 
User in US
     |
     v
Primary US

If both update the same record at nearly the same time, the system must define what happens.


28. Leaderless Replication#

In some distributed databases there is no single leader responsible for all writes.

Instead:

        +-----------+
        |  Node A   |
        +-----------+
          /       \
         /         \
        v           v
   +---------+   +---------+
   | Node B  |   | Node C  |
   +---------+   +---------+

Clients may write to multiple replicas according to the database's consistency protocol.

Quorums can be used to determine how many nodes need to acknowledge an operation.

Leaderless systems can provide strong availability characteristics but require careful reasoning about consistency and conflict resolution.


29. Quorum Concepts#

A simplified quorum model:

  • N = number of replicas
  • W = acknowledgments required for a write
  • R = replicas consulted for a read

A common rule for overlapping read/write sets is:

R + W > N

This can help ensure that a read and write overlap on at least one replica.

However, this equation alone does not define the complete consistency behavior of a real database.

Database-specific semantics matter.


30. Multi-Region Replication#

Suppose an application operates globally:

                 Global Users
                      |
        +-------------+-------------+
        |             |             |
        v             v             v
      India          US          Europe
        |             |             |
        v             v             v
    DB Region A   DB Region B   DB Region C

Replication can keep data available across regions.

Example:

India DB
   |
   +------> US DB
   |
   +------> Europe DB

Benefits:

  • disaster recovery
  • lower read latency for regional users
  • regional availability
  • geographic redundancy

Challenges:

  • cross-region network latency
  • replication lag
  • conflict handling
  • operational complexity
  • data residency requirements
  • higher cost

31. Cross-Region Latency#

Suppose:

India
  |
  | 150 ms RTT
  v
US

If every write requires a remote synchronous acknowledgment, write latency can increase significantly.

This is one reason many globally distributed systems use asynchronous replication between regions.

The exact architecture depends on the consistency and durability requirements.


32. RPO and Replication#

RPO means:

Recovery Point Objective

It answers:

How much data loss can the business tolerate after a failure?

Example:

RPO = 0

means the target is effectively no data loss.

With asynchronous replication:

Primary
   |
   | replication lag
   v
Replica

If the primary fails before the replica receives the newest data, those writes may be lost during failover.

Therefore:

Replication strategy
        |
        v
Potential data loss
        |
        v
RPO

Replication is closely related to disaster recovery, but replication alone is not a complete disaster-recovery strategy.


33. RTO and Failover#

RTO means:

Recovery Time Objective

It answers:

How quickly must the system recover?

For example:

RTO = 5 minutes

means the recovery target is five minutes.

Automatic failover can reduce RTO, but it requires:

  • health detection
  • promotion
  • routing updates
  • connection recovery
  • application readiness

So:

Replication
+
Failover
+
Routing
+
Recovery automation
=
High-availability design

34. Replication vs Backup#

These are not the same.

Replication#

Primary
   |
   +----> Replica

Designed primarily for:

  • availability
  • read scaling
  • redundancy

Backup#

Database
   |
   v
Backup Storage

Designed primarily for:

  • recovery
  • accidental deletion
  • corruption recovery
  • historical restoration

A dangerous misconception is:

“We have replicas, so we don't need backups.”

That is incorrect.

If a user accidentally deletes data:

Primary
   |
   v
DELETE
   |
   v
Replica

The deletion may also replicate.

A backup can provide a recovery point from before the deletion.


35. Replication and Disaster Recovery#

A disaster-recovery architecture may look like:

                 Primary Region
                 +-----------+
                 | DB Primary|
                 +-----+-----+
                       |
                  Replication
                       |
                       v
                 DR Region
                 +-----------+
                 | DB Replica|
                 +-----------+

If the primary region becomes unavailable:

Primary Region
      X
 
      |
      v
 
DR Region
   becomes
   active

But the DR plan must also account for:

  • application servers
  • networking
  • DNS
  • secrets
  • object storage
  • queues
  • caches
  • monitoring
  • deployment infrastructure

A database replica alone does not make the entire application disaster resilient.


36. Monitoring Replication#

Replication should be monitored continuously.

Important metrics include:

Replication lag#

Lag = current primary position - replica position

The exact measurement depends on the database.

Replica health#

Monitor:

  • connection status
  • CPU
  • memory
  • disk
  • I/O
  • replication errors

Replay/apply rate#

How quickly is the replica applying incoming changes?

Write throughput#

A sudden increase in writes may cause replicas to fall behind.


37. What Happens When a Replica Falls Behind?#

Suppose:

Primary writes: 50,000 changes/sec
Replica applies: 30,000 changes/sec

The backlog grows.

Eventually:

Replication Lag
      |
      v
   Increasing

Potential responses:

  • reduce read workload on the replica
  • add replica capacity
  • optimize expensive queries
  • increase resources
  • investigate disk/network bottlenecks
  • temporarily remove the replica from read traffic

A replica should not necessarily serve user traffic just because it is technically alive.


38. Replica Health vs Replica Freshness#

These are different.

A replica can be:

Healthy = YES
Fresh = NO

For example:

Replica:
CPU = 30%
Memory = 50%
Connection = OK
 
Replication lag = 60 seconds

The server is healthy from an infrastructure perspective but may be unsuitable for some consistency-sensitive reads.

This is a common system-design interview point.


39. Read Scaling Architecture#

Consider an e-commerce system.

Traffic:

Reads  = 100,000/sec
Writes = 5,000/sec

A possible architecture:

                    Application
                         |
              +----------+----------+
              |                     |
            Writes                 Reads
              |                     |
              v                     v
          +--------+          +-------------+
          |Primary |          | Read Router |
          +---+----+          +------+------+ 
              |                      |
       Replication             +-----+-----+
              |                |     |     |
       +------+-----+          v     v     v
       |            |       R1    R2    R3
       v            v
      R1           R2

This separates write and read workloads.


40. Primary Bottleneck Still Exists#

Adding replicas does not eliminate every database bottleneck.

Suppose the primary has:

CPU = 95%
Disk = 90%
Writes = 50k/sec

Adding ten read replicas may not help.

Why?

Because the primary still handles:

  • writes
  • transaction coordination
  • replication generation
  • indexes
  • constraints
  • transaction logging

Eventually, you may need:

  • sharding
  • partitioning
  • write batching
  • workload separation
  • queue-based processing
  • schema/query optimization

We will study partitioning and sharding in the next chapter.


41. Connection Routing#

Applications often maintain separate database connection pools.

Conceptually:

Application
    |
    +---- Write Pool ----> Primary
    |
    +---- Read Pool -----> Replicas

This prevents read traffic from consuming all primary connections.

Example pseudocode:

const db = operation === "write"
  ? primaryPool
  : replicaPool;

Real production systems usually use a more sophisticated routing layer.


42. Failover and Existing Connections#

When a primary changes:

Old Primary
    X
 
New Primary
    |
    v
Application

Existing connections to the old primary may fail.

The application must be able to:

  • detect connection failure
  • reconnect
  • rediscover the current primary
  • retry safely when appropriate

Retries must be designed carefully.

For writes, blindly retrying can create duplicate operations if the original request actually succeeded but the response was lost.

This is where idempotency becomes important.


43. Replication and Idempotency#

Suppose:

Client
  |
  | Create Payment
  v
Primary
  |
  | commits
  |
  X response lost

The client retries.

Client
  |
  | Create Payment again
  v
Primary

Without idempotency protection, two payments could potentially be created.

A system may use:

Idempotency-Key: abc123

to ensure repeated requests represent the same logical operation.

Replication does not solve this problem by itself.


44. Conflict Handling#

Conflict is particularly important in:

  • multi-primary systems
  • leaderless systems
  • offline-first systems
  • geographically distributed writes

Example:

Region A:
balance = 100
 
Region B:
balance = 100

Two clients update the same record concurrently.

A -> 150
B -> 120

What should the final value be?

Possible strategies depend on the data:

  • last-write-wins
  • version numbers
  • application-level merge
  • conflict-free data structures
  • reject conflicting updates
  • business-specific reconciliation

There is no universal conflict-resolution strategy.


45. Single-Primary vs Multi-Primary#

Property Single Primary Multi-Primary
Write coordination Simpler More complex
Conflict risk Lower Higher
Write scalability Limited by primary Can distribute writes
Operational complexity Lower Higher
Global writes More challenging Potentially easier
Consistency design Simpler More complicated

The correct choice depends on workload and consistency requirements.


46. Common Replication Failure Modes#

Failure 1: Replica lag#

Primary >>> Replica

Replica cannot keep up.

Failure 2: Network partition#

Nodes cannot communicate.

Failure 3: Replica crash#

One replica becomes unavailable.

Failure 4: Storage failure#

Replica cannot persist incoming changes.

Failure 5: Replication stream failure#

Changes stop flowing.

Failure 6: Split-brain#

Multiple nodes become writers.

Failure 7: Incorrect failover#

A stale replica is promoted without considering lost changes.

Failure 8: Application still points to old primary#

Failover occurs but clients do not discover it.


47. Common Mistakes#

Mistake 1: Thinking replicas are backups#

They are not a substitute for backups.

Mistake 2: Assuming replicas are always current#

Asynchronous replicas can lag.

Mistake 3: Sending every read to replicas#

Some reads require stronger consistency.

Mistake 4: Assuming more replicas increase write capacity#

They generally increase read capacity, not primary write capacity.

Mistake 5: Ignoring failover routing#

Promoting a replica is useless if applications cannot find it.

Mistake 6: Ignoring split-brain#

Automatic failover must protect against multiple writers.

Mistake 7: Ignoring replication lag#

A technically healthy replica can still be stale.

Mistake 8: Blindly retrying writes#

Retries can duplicate non-idempotent operations.


48. Real-World Architecture Example: E-Commerce#

Requirements:

  • 1 million users
  • read-heavy catalog
  • order creation
  • payment processing
  • high availability

Possible architecture:

                    Users
                      |
                      v
                 Load Balancer
                      |
                      v
               Application Layer
                 /           \
                /             \
             Reads           Writes
               |                |
               v                v
         Read Router          Primary
          /      \               |
         v        v              |
      Replica   Replica          |
         ^        ^              |
         +--------+--------------+
              Replication

But payment/order reads may need stronger consistency.

Therefore:

Catalog reads
    -> Replica
 
Payment status
    -> Primary / consistency-aware read
 
Order immediately after creation
    -> Primary or consistency-aware replica

System design is about matching architecture to requirements.


49. Practical Exercise#

Design replication for a news website.

Requirements:

  • 200,000 reads/sec
  • 1,000 writes/sec
  • users distributed globally
  • articles can tolerate a few seconds of staleness
  • high availability required

Think about:

  1. How many primary nodes?
  2. How many read replicas?
  3. Where should replicas be located?
  4. Should replication be synchronous or asynchronous?
  5. What happens if the primary fails?
  6. How should reads be routed?
  7. What happens if a replica falls behind?
  8. Do you still need backups?

A reasonable conceptual design might be:

                  Global Users
                       |
                 Global Routing
                       |
              +--------+--------+
              |                 |
           Region A          Region B
              |                 |
              v                 v
           Replica            Replica
              ^                 ^
              |                 |
              +------+----------+
                     |
                  Primary

The exact topology depends on the database and availability requirements.


50. Mini Project — Build a Read/Write Database Router#

Create a small service with two conceptual database connections:

primary
replica

Expose:

POST /users
GET /users/:id

Routing:

POST -> primary
GET  -> replica

Then simulate replication lag.

For example:

POST /users

writes to primary.

The replica intentionally waits two seconds before receiving the change.

Then:

GET /users/123

immediately after creation may return:

404

After replication catches up:

GET /users/123

returns:

{
  "id": 123,
  "name": "Anubhav"
}

This exercise demonstrates why read-after-write consistency matters.


51. Interview Questions#

Beginner#

  1. What is database replication?
  2. Why do we need replication?
  3. What is a primary database?
  4. What is a read replica?
  5. What is replication lag?
  6. What is synchronous replication?
  7. What is asynchronous replication?

Intermediate#

  1. How do read replicas improve scalability?
  2. Why don't read replicas increase write capacity?
  3. What is read-after-write consistency?
  4. What is stale data?
  5. How does database failover work?
  6. What is split-brain?
  7. Why are backups still required if replicas exist?
  8. How do you route reads across replicas?

Advanced#

  1. How would you design automatic database failover?
  2. How do you prevent split-brain?
  3. What is fencing?
  4. What are the trade-offs of multi-primary replication?
  5. How does cross-region replication affect latency?
  6. How does replication affect RPO?
  7. How would you handle a replica that is 60 seconds behind?
  8. How do you handle read-after-write requirements?
  9. What happens if the old primary comes back after failover?
  10. How would you design replication for a globally distributed application?

52. Interview Scenario#

Question#

You have one PostgreSQL primary and three read replicas. Suddenly one replica falls 30 seconds behind. What do you do?

A strong reasoning process:

1. Confirm the lag.
2. Determine whether the replica is healthy.
3. Check CPU, memory, disk I/O and network.
4. Check replication/apply throughput.
5. Remove the stale replica from latency/consistency-sensitive read traffic.
6. Investigate why it fell behind.
7. Restore replication health.
8. Reintroduce it only when freshness is acceptable.

Do not immediately assume the database itself is broken.

Find the bottleneck first.


53. Production Replication Checklist#

Before deploying a replicated database architecture, ask:

Architecture#

  • Is there a primary?
  • How many replicas?
  • Are replicas distributed across failure domains?
  • Is cross-region replication required?

Consistency#

  • Can reads be stale?
  • What is the maximum acceptable lag?
  • Which operations require read-after-write behavior?

Availability#

  • How is failover triggered?
  • Is failover automatic or manual?
  • How is the new primary discovered?

Safety#

  • How is split-brain prevented?
  • Is fencing available?
  • Can the old primary continue writing?

Performance#

  • What is the write latency?
  • What is replication throughput?
  • How much read traffic can replicas handle?

Monitoring#

  • Replication lag
  • Replica health
  • Replication errors
  • CPU
  • Memory
  • Disk
  • Network
  • Connection count

Recovery#

  • What is the RPO?
  • What is the RTO?
  • Are backups available?
  • Has restoration been tested?

54. Master Mental Model#

Remember database replication using this model:

                    APPLICATION
                         |
                +--------+--------+
                |                 |
              WRITE              READ
                |                 |
                v                 v
            +-------+        +----------+
            |PRIMARY|        |  ROUTER  |
            +---+---+        +----+-----+
                |                  |
          Replication          +---+---+
                |              |       |
          +-----+-----+        v       v
          |           |      R1       R2
          v           v
        R1           R2

Then ask five questions:

1. How is data copied?
2. How fresh are replicas?
3. How are reads routed?
4. What happens if primary fails?
5. How do we prevent multiple writers?

If you can answer these five questions, you understand the core of database replication.


55. Chapter Summary#

In this chapter, we learned:

  • what database replication is
  • why replication is needed
  • primary/replica architecture
  • leader/follower terminology
  • synchronous replication
  • asynchronous replication
  • semi-synchronous concepts
  • replication lag
  • read replicas
  • read scaling
  • read-after-write consistency
  • stale reads
  • replica routing
  • failover
  • automatic vs manual failover
  • leader election
  • split-brain
  • fencing
  • replica promotion
  • cascading replication
  • multi-primary replication
  • leaderless replication
  • quorum concepts
  • multi-region replication
  • RPO/RTO implications
  • replication monitoring
  • replica freshness
  • backups vs replication
  • disaster recovery
  • conflict handling
  • production failure modes
  • practical replication architecture

The central idea is:

Replication creates additional copies of data so a system can improve availability, read scalability, and geographic resilience—but it introduces consistency, lag, failover, and operational challenges.


56. Key Terms#

Term Meaning
Replication Maintaining copies of database data
Primary Main write node
Replica Copy of primary data
Leader Alternative term for primary
Follower Alternative term for replica
Read Replica Replica serving reads
Replication Lag Delay between source and replica state
Synchronous Primary waits for required replica acknowledgment
Asynchronous Primary does not wait for replica application
Failover Moving active responsibility to another node
Promotion Turning a replica into a primary
Split-Brain Multiple nodes incorrectly acting as writers
Fencing Preventing an old writer from continuing
Multi-Primary Multiple nodes accept writes
Leaderless No single designated write leader
Quorum Required subset of nodes for an operation
RPO Acceptable recovery data loss
RTO Target recovery time
Stale Read Read returning older data
Read-After-Write A write should be visible to subsequent reads

57. Final Interview Checklist#

Before moving on, make sure you can explain:

  • Why replication is needed
  • Primary vs replica
  • Leader vs follower
  • Synchronous vs asynchronous replication
  • Replication lag
  • Read replicas
  • Read-after-write consistency
  • Stale reads
  • Failover
  • Automatic failover
  • Leader election
  • Split-brain
  • Fencing
  • Replica promotion
  • Cascading replication
  • Multi-primary replication
  • Leaderless replication
  • Quorum concepts
  • Multi-region replication
  • RPO/RTO
  • Replication monitoring
  • Replication vs backup
  • Replica overload
  • Conflict resolution
  • Read/write routing
  • Production failure scenarios

58. What's Next?#

Chapter 14 — Database Partitioning & Sharding#

Next we move from copying data to splitting data.

We will learn:

  • What database partitioning means
  • What sharding means
  • Why replication cannot solve every scaling problem
  • Horizontal vs vertical partitioning
  • Shard keys
  • Hash-based sharding
  • Range-based sharding
  • Directory-based sharding
  • Consistent hashing
  • Hot partitions
  • Rebalancing
  • Cross-shard queries
  • Cross-shard transactions
  • Shard failure
  • Resharding
  • Global sharding
  • Sharding in SQL and NoSQL systems
  • Real-world sharded architectures
  • Sharding interview questions
  • A practical sharded URL-shortener design

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 12 — Database IndexingNext ChapterChapter 14 — Database Partitioning & Sharding
PrevNext