Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 158/ 160
08. Transactions, Security & Production SQL Administration

Read Replicas, High Availability & Failover Basics

Scale reads and survive primary failure with replicas and failover plans.

IntermediateRead Replica · Failover3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Copies of the database answer read questions so the main one isn't overloaded. If the main one breaks, a copy takes over.

Think of it like…

A head chef (the primary) takes every order, while assistant chefs copy the head chef's notes so they can answer customers' questions. They're a few seconds behind the latest notes. If the head chef falls ill, one assistant takes over, possibly missing the last few notes.

Where you’ve seen it

An app sends writes to the primary and product-page reads to two replicas. A user updates their profile and immediately reloads it from a replica that's 200 ms behind, and sees the old name. The fix: read from the primary right after a user's own write (read-your-writes).

Words you’ll hear

Primary / replica
The writable server and its read-only copies.
Replication lag
How far behind a replica is; nonzero with asynchronous replication.
Synchronous replication
The primary waits for a replica to confirm before COMMIT returns: no data loss, more latency.
RPO / RTO
How much data you can afford to lose / how long recovery may take.

Visual diagram

Loading interactive diagram

Theory & example queries

Scaling reads, and the lag problem

Replicas let you add read capacity: reporting, search pages and APIs that tolerate slightly old data read from replicas, while writes and freshness-critical reads go to the primary. Many frameworks and proxies support routing reads and writes to different connection pools.

With asynchronous replication, a replica can be milliseconds or, under heavy load, minutes behind. That breaks read-your-own-writes: a user saves something and immediately reads stale data. Common fixes: read from the primary for a short time after a user's write, route session-critical reads to the primary, or check replica lag and fall back when it's too high.

Checking lag on a PostgreSQL replicaQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  now() - pg_last_xact_replay_timestamp() AS replication_lag;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/2
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative replay lag1 sample row
Representative replay lag
replication_lag
00:00:01.8

Note: Lag is illustrative and can change for every measurement. The result is NULL before replay has occurred or when no commit timestamp is available, and the wall-clock calculation is affected by primary/replica clock conditions.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Replicas add read capacity at the cost of slightly stale data.

High availability and failover

If the primary fails, a replica is promoted and applications are pointed at it, via DNS, a virtual IP or a proxy. Tools like Patroni (PostgreSQL), or managed services such as Amazon RDS Multi-AZ and Cloud SQL HA, automate detection and promotion, typically within seconds to a minute or two.

With asynchronous replication, commits the primary acknowledged but hadn't yet sent are lost on failover; synchronous replication to at least one standby avoids that at the cost of write latency. Automation must also prevent split-brain, where two nodes both believe they're primary. Finally, replicas aren't backups: an accidental DELETE replicates within milliseconds, so point-in-time backups are still essential.

Trading latency for zero data loss (PostgreSQL)

synchronous_standby_names = 'FIRST 1 (replica_b)' makes COMMIT wait until replica_b has the WAL, so failing over to it loses nothing.

Key takeaway: Async replicas can lose recent commits on failover; sync replicas cost latency; backups are separate.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Classify your reads

Split reads into those that tolerate a little staleness (listings, reports) and those that must be fresh (just after a user's write, payments).

Focus at this step

stale-OK → replica · fresh → primary

What to watch at this step
Default
primary for critical reads
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A read replica is a copy of the primary database that continuously applies its changes (PostgreSQL streams the WAL; MySQL replays the binlog) and serves read-only queries. Replication is usually asynchronous, so replicas lag slightly behind. Failover promotes a replica to become the new primary when the old one fails; done automatically, it's the basis of high availability (HA).

Why it matters: Replicas spread read traffic and keep a standby ready for outages, but they introduce stale reads, possible data loss on failover and routing complexity. "How do you scale reads?" and "what happens when the primary dies?" are standard system design and backend interview questions.

When to reach for it

  • Offloading reporting and read-heavy endpoints
  • Keeping a hot standby for automatic failover
  • Placing read copies closer to users in other regions

When to avoid or be careful

  • Reading a user's own just-written data from a lagging replica
  • Treating replicas as backups
  • Failover automation without protection against split-brain

Asynchronous vs synchronous replication vs backups

Asynchronous replica
Best for: Scaling reads; standby where losing a few seconds of data is acceptable

Strengths: No impact on write latency.

Watch out: Stale reads; recent commits can be lost on failover.

Synchronous standby
Best for: Failover with zero data loss

Strengths: Committed data is guaranteed to be on the standby.

Watch out: Higher write latency; writes stall if the standby is unavailable (unless configured otherwise).

Backups + WAL archiving (PITR)
Best for: Recovering from mistakes, corruption or disasters

Strengths: Can restore to a point before an accidental DELETE.

Watch out: Slower recovery than failover; must be tested.

Interview signals & numbers to know

When this topic comes up

  • “How do you scale database reads?”
  • “What happens if the primary fails?”
  • “Users don't see their changes right away”
  • Replication lag
  • RPO / RTO

Benchmarks & rules of thumb

~0 s -
data loss (RPO) with a synchronous standby
Seconds–minutes -
typical automated failover time
0 -
protection from accidental DELETE offered by replicas

Common mistakes & follow-ups

Common interview mistakes

  • Sending all reads to replicas and showing users stale data right after they save.
  • Assuming asynchronous failover never loses data.
  • Relying on replicas instead of backups, then losing data to a replicated DELETE.

Likely interviewer follow-ups

  • How would you guarantee users see their own writes when reads go to replicas?
  • What's the difference between RPO and RTO?
  • How does synchronous replication affect write latency?
Interview tip: Cover three things: replicas scale reads but lag, failover promotes a replica (with possible data loss if async), and replicas aren't backups. That structure answers most follow-ups before they're asked.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Read Replicas, High Availability & Failover Basics with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Point-in-Time Recovery (PITR) & Write-Ahead Log (WAL) Archiving
Next topic
Cloud SQL Databases & Analytical Engines (Snowflake, BigQuery, DuckDB)