Single-Leader Replication

Core Concept

intermediate
20-30 minutes
replicationmaster-slaveconsistencyfailoverread-scalingdatabases

Master-slave replication with one writable leader

Single-Leader Replication

Overview

Single-leader replication, also known as master-slave replication, is a database replication strategy where one node (the leader/master) accepts all writes, and these changes are then replicated to one or more follower nodes (slaves/replicas). This is the most common and straightforward replication approach used in many database systems.

This pattern provides read scalability while maintaining strong consistency for writes, making it suitable for applications that require predictable consistency guarantees with the ability to scale read operations.

Architecture

Write Requests → [Leader/Master] → Replication Log
                      ↓
                 [Follower 1] ← Async/Sync Replication
                 [Follower 2] ← Async/Sync Replication  
                 [Follower 3] ← Async/Sync Replication
                      ↑
Read Requests ←──────┘

Key Characteristics

  • Single Write Node: Only the leader accepts write operations
  • Read Scalability: Followers can serve read requests
  • Consistency: Strong consistency for writes, eventual consistency for reads
  • Failover: Automatic or manual promotion of follower to leader
  • Simplicity: Easier to implement than multi-leader systems

Implementation Example

class SingleLeaderReplication:
    def __init__(self, node_id, is_leader=False):
        self.node_id = node_id
        self.is_leader = is_leader
        self.data = {}
        self.followers = []
        self.leader = None
        self.replication_log = []
    
    def write(self, key, value):
        if not self.is_leader:
            raise Exception("Only leader can accept writes")
        
        # Apply write locally
        self.data[key] = value
        
        # Add to replication log
        log_entry = {
            'operation': 'write',
            'key': key,
            'value': value,
            'timestamp': time.time()
        }
        self.replication_log.append(log_entry)
        
        # Replicate to followers
        self.replicate_to_followers(log_entry)
    
    def read(self, key):
        # Can read from any node
        return self.data.get(key)
    
    def replicate_to_followers(self, log_entry):
        for follower in self.followers:
            try:
                follower.apply_replication(log_entry)
            except Exception as e:
                print(f"Replication failed to {follower.node_id}: {e}")

Synchronous vs Asynchronous Replication

Synchronous Replication

  • Pros: Strong consistency, no data loss
  • Cons: Higher latency, availability depends on followers
  • Use Case: Financial systems, critical data

Asynchronous Replication

  • Pros: Low latency, high availability
  • Cons: Risk of data loss, eventual consistency
  • Use Case: Social media, content management

Real-World Usage

MySQL Master-Slave:

-- Configure master
SET GLOBAL binlog_format = 'ROW';
START SLAVE;

-- Configure slave
CHANGE MASTER TO
    MASTER_HOST='master-server',
    MASTER_USER='replication-user',
    MASTER_PASSWORD='password',
    MASTER_LOG_FILE='mysql-bin.000001',
    MASTER_LOG_POS=0;

PostgreSQL Streaming Replication:

-- Configure primary
wal_level = replica
max_wal_senders = 3
wal_keep_segments = 32

-- Configure standby
standby_mode = 'on'
primary_conninfo = 'host=primary-server port=5432'

Trade-offs

Advantages:

  • Simple to understand and implement
  • Strong consistency for writes
  • Good read scalability
  • Well-supported by most databases

Disadvantages:

  • Single point of failure for writes
  • Geographic distribution challenges
  • Failover complexity
  • Potential for replication lag

Best Practices

  1. Monitor Replication Lag: Track delay between leader and followers
  2. Automated Failover: Implement robust leader election
  3. Read Preference: Route reads to followers when consistency allows
  4. Backup Strategy: Use followers for backups without impacting leader

This replication strategy forms the foundation for understanding more complex replication patterns in distributed systems.

Related Concepts

multi-leader-replication
leaderless-replication
consistency
failover

Used By

mysqlpostgresqlmongodbredis