🗄️ Databases

Primary-Replica Replication

Primary-Replica Replication

Writes are handled by the Primary and reads by the Replicas.

Detailed Explanation

Primary-Replica Replication is a database replication method in which a single Primary (master) server handles all write operations, while multiple Replica (slave) servers share the read workload. It is widely used in most web applications with a high ratio of reads to writes.

Changes made on the Primary are propagated to the Replicas through replication logs (binlog, WAL, etc.). Synchronous replication guarantees data consistency but introduces latency, while asynchronous replication is fast but may cause temporary data inconsistency (Replica Lag).

By distributing the read load across multiple Replicas, throughput can be increased, and if the Primary fails, one of the Replicas can be promoted to maintain service continuity. However, read/write routing logic is required at the application level.

Code Example

# Python - SQLAlchemy 읽기/쓰기 분리
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Primary (쓰기용)
primary_engine = create_engine('postgresql://primary-host:5432/mydb')

# Replica (읽기용)
replica_engine = create_engine('postgresql://replica-host:5432/mydb')

PrimarySession = sessionmaker(bind=primary_engine)
ReplicaSession = sessionmaker(bind=replica_engine)

class DatabaseRouter:
    def get_session(self, readonly=False):
        if readonly:
            return ReplicaSession()
        return PrimarySession()

# 사용 예시
router = DatabaseRouter()

# 쓰기 작업 - Primary로
with router.get_session(readonly=False) as session:
    new_user = User(name="홍길동", email="hong@example.com")
    session.add(new_user)
    session.commit()

# 읽기 작업 - Replica로
with router.get_session(readonly=True) as session:
    users = session.query(User).filter(User.active == True).all()

# Django - 데이터베이스 라우터 설정
# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': 'primary-host',
        'NAME': 'mydb',
    },
    'replica': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': 'replica-host',
        'NAME': 'mydb',
    }
}

# routers.py
class PrimaryReplicaRouter:
    def db_for_read(self, model, **hints):
        return 'replica'

    def db_for_write(self, model, **hints):
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return db == 'default'

Practical Conversation Example

DevOps: The DB server CPU is going above 80%. Most of it is read queries.

DBA: We can distribute the reads with a Primary-Replica setup. What is the current read/write ratio?

DevOps: Reads are about 90%.

DBA: If we add 2 Replicas and distribute the read queries, the Primary load should drop significantly. However, we also need to set up Replica Lag monitoring.

Interviewer: What problems occur when Replica Lag arises in a Primary-Replica setup?

Candidate: A post that a user has just written may not appear if it is queried immediately. To resolve this, you can perform reads immediately after writes on the Primary, or track the most recent write time using cookies/sessions and read from the Replica only data older than the Lag.

Interviewer: How do you handle Failover when the Primary fails?

Candidate: You promote one of the Replicas to Primary. Automation tools include MHA for MySQL and Patroni for PostgreSQL.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Senior: Here, the same data is queried right after it is saved. Did you consider Replica Lag?

Junior: Ah, if we read from a Replica, the data we just wrote may not show up.

Senior: Yes, change it so that reads right after writes go to the Primary, or at least change it to query after a delay of about 1 second.

Cautions

Related Terms

Learn More