Replication — Explained with Examples
Database replication copies data from one database server to others, ensuring redundancy, high availability, and improved read performance across distributed systems.
Replication is the process of copying data from a primary database to one or more replica databases. It enables fault tolerance (if one server fails, another serves requests), load distribution (replicas handle read traffic), and geographical proximity (replicas closer to users).
Why Replication Matters
If your only database server goes down, your application goes offline. Replication provides redundancy: replica servers take over. It also scales read capacity — instead of one server handling all queries, replicas share the load.
Real-World Analogy
A popular book is held at the main library (primary). The library creates copies at branch libraries (replicas). If the main library burns down, branches still serve readers. Readers can also visit whichever branch is closest, reducing wait times at the main branch.
Example: Master-Slave Replication
import time
from datetime import datetime
class MasterDatabase:
def __init__(self):
self.data = {}
self.replicas = []
self._write_ahead_log = []
def write(self, key, value):
self.data[key] = value
entry = (key, value, datetime.now())
self._write_ahead_log.append(entry)
# Async replication to replicas
for replica in self.replicas:
replica.sync(entry)
print(f"Master: wrote {key}={value}")
def attach_replica(self, replica):
self.replicas.append(replica)
class ReplicaDatabase:
def __init__(self, name):
self.name = name
self.data = {}
def sync(self, entry):
key, value, ts = entry
self.data[key] = value
print(f"{self.name}: synced {key}={value}")
def read(self, key):
return self.data.get(key, "not found")
# Usage
master = MasterDatabase()
replica1 = ReplicaDatabase("Replica-1")
replica2 = ReplicaDatabase("Replica-2")
master.attach_replica(replica1)
master.attach_replica(replica2)
master.write("user:1", "Alice")
# Output:
# Master: wrote user:1=Alice
# Replica-1: synced user:1=Alice
# Replica-2: synced user:1=Alice
print(replica1.read("user:1")) # Output: AliceRelated Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro