Database High Availability and Failover
What you will learn
- What availability means and how "nines" translate into downtime
- What a replica is and how failover works
- Why failover can lose recent writes
- The dangers of failing over: split brain
- How to test your setup
1. Availability and the nines
Availability is the share of time a service works. It is usually given in "nines". The conversion is only arithmetic:
for pct in (99, 99.9, 99.99, 99.999):
minutes = (1 - pct / 100) * 365 * 24 * 60
print(f"{pct}% available -> {minutes:,.1f} minutes of downtime per year")
99% available -> 5,256.0 minutes of downtime per year
99.9% available -> 525.6 minutes of downtime per year
99.99% available -> 52.6 minutes of downtime per year
99.999% available -> 5.3 minutes of downtime per year
Each extra nine cuts the allowed downtime by ten, and costs much more: more machines, more automation, more people on call. Nobody gets 100%. The question for each system is: how much downtime can the business tolerate, and what is it willing to pay? A hobby blog can accept hours; a payment system cannot.
2. One machine is a single point of failure
If the database lives on one machine, then that machine's disk, power, network or software failing means the whole application stops. A single point of failure is any one part whose failure brings everything down.
High availability (HA) removes single points of failure by keeping a second copy ready to take over.
application ──► primary ──copies changes──► replica
│ │
X fails └─ promoted: becomes the new primary
- The primary accepts reads and writes.
- A replica receives a copy of every change from the primary and can answer reads (lesson 9.6).
- Failover is switching the application to the replica when the primary dies. The replica is promoted to be the new primary.
Replication details (synchronous or asynchronous, one or many replicas) are the topic of lesson 14.2. For now, what matters is the question: does the replica have every change the primary had?
3. A toy failover
SQLite has no replicas, so we build a toy: a "replica" that is a copy of the primary's file made at one moment. It makes the idea, and its main danger, visible.
import sqlite3, os, tempfile
folder = tempfile.mkdtemp()
primary_path = os.path.join(folder, "primary.db")
replica_path = os.path.join(folder, "replica.db")
p = sqlite3.connect(primary_path)
p.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, item TEXT)")
p.executemany("INSERT INTO orders (item) VALUES (?)", [("shirt",), ("scarf",)])
p.commit()
def copy_to_replica():
src = sqlite3.connect(primary_path)
dst = sqlite3.connect(replica_path)
src.backup(dst) # a toy "replication": a full copy at one moment
src.close(); dst.close()
copy_to_replica()
p.execute("INSERT INTO orders (item) VALUES ('cap')") # written after the last copy
p.commit()
def count(path):
try:
con = sqlite3.connect(f"file:{path}?mode=rw", uri=True)
n = con.execute("SELECT COUNT(*) FROM orders").fetchone()[0]
con.close()
return n
except sqlite3.Error:
return None
print("primary rows:", count(primary_path), "| replica rows:", count(replica_path), "(replica lags by one row)")
primary rows: 3 | replica rows: 2 (replica lags by one row)
Replication lag as a row count, in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). In a SQL cell the toy "replica" is a copy of a real table made at one moment. A row written afterwards shows the lag. Reset data starts again.
CREATE TABLE payments_replica AS SELECT * FROM payments;
INSERT INTO payments (order_id, paid_on, method, amount) VALUES (1, '2026-10-01', 'cash', 25.0);
SELECT (SELECT COUNT(*) FROM payments) AS primary_rows, (SELECT COUNT(*) FROM payments_replica) AS replica_rows;
primary_rows replica_rows
------------ ------------
2296 2295
(1 row)
CREATE TABLE transfers_replica AS SELECT * FROM transfers;
INSERT INTO transfers (from_account, to_account, amount_cents, created_on, status) VALUES (1, 2, 500, '2026-10-01', 'done');
SELECT (SELECT COUNT(*) FROM transfers) AS primary_rows, (SELECT COUNT(*) FROM transfers_replica) AS replica_rows;
primary_rows replica_rows
------------ ------------
601 600
(1 row)
CREATE TABLE enrollments_replica AS SELECT * FROM enrollments;
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (360, 1, '2026-10-01');
SELECT (SELECT COUNT(*) FROM enrollments) AS primary_rows, (SELECT COUNT(*) FROM enrollments_replica) AS replica_rows;
primary_rows replica_rows
------------ ------------
1003 1002
(1 row)
The replica lags by one row. If the primary failed now and the replica were promoted, that row would be lost.
The order for the cap arrived after the last copy, so the replica does not have it. This delay is called replication lag. Now the primary dies and our program notices with a health check, a small test that asks "are you alive?":
def healthy(path):
return count(path) is not None
active = primary_path
p.close()
os.remove(primary_path) # the primary "dies"
print("primary healthy?", healthy(primary_path))
if not healthy(active):
active = replica_path
print("failover: now serving from the replica, which has", count(active), "rows; the lost write ('cap') is gone")
primary healthy? False
failover: now serving from the replica, which has 2 rows; the lost write ('cap') is gone
The service is back, but the customer who ordered the cap was told "order accepted", and the order no longer exists. That is the central trade-off of failover:
- Asynchronous copying (the primary does not wait for the replica) is fast, but a failover can lose the newest writes.
- Synchronous copying (the primary waits until the replica has the change) loses nothing, but every write is slower and a broken replica can block the primary.
Which is right depends on how much data loss the business can accept. That limit has a name, the RPO, and is the subject of lesson 12.6.
4. What real failover must also handle
A real system needs much more than our toy:
| Problem | What it means |
|---|---|
| Detecting failure | A slow network is not a dead machine. Declare death too quickly and you fail over for nothing; too slowly and users wait. |
| Split brain | The old primary was only cut off from the network, not dead, and now two machines both believe they are the primary and accept writes. The data diverges, and merging it is painful. Systems prevent this with agreement rules (lesson 14.7) and by making sure the old primary is stopped. |
| Telling applications | Applications must find the new primary, usually through a name or a proxy that is switched, not by editing every program. |
| The old primary comes back | It must rejoin as a replica, and may contain writes the new primary never received. Those must be reviewed, not silently dropped. |
| Failing back | Moving to the original machine again is another change with its own risk. |
Which tools do this, and how, varies by product; read your product's documentation instead of building failover by hand.
5. Test it
A failover plan that has never been run is a hope. Teams rehearse: switch the primary off on purpose in a safe environment, measure how long the switch takes, and count what was lost. Do this before the real failure, at a time you choose (lesson 12.8 for environments).
Worked example: choosing a level for the tailor shop
The shop's website takes orders at all hours. The owner thinks about three setups.
| Setup | Downtime per year if it reaches the stated level | Cost and effort |
|---|---|---|
| One server, daily backup | days are possible if hardware fails | lowest |
| Primary and one replica, manual failover | about 99.9%, which is 525.6 minutes a year (from the table above) | medium, someone must be available to switch |
| Automatic failover with health checks | a goal of 99.99%, 52.6 minutes a year | highest, needs careful setup and testing |
The shop's real orders come mostly in the daytime, and a few lost orders are acceptable if the customers can be contacted. The owner picks the middle setup: the cost is justified and the risks are understood. The levels are examples, not promises that any setup reaches them; the reached level is measured, not assumed. The shop and numbers are made up.
Common mistakes
- Assuming a replica is a backup. A replica copies mistakes too: a wrong
DELETEis copied within moments. You still need backups (chapter 8). - Forgetting replication lag and promising users data that a failover can lose.
- No plan against split brain.
- Never rehearsing failover.
- Choosing the number of nines without the cost, or without asking what downtime really costs.
Key takeaways
- Availability in nines is simple arithmetic: 99.9% is about 526 minutes of downtime a year; 99.99% about 53.
- A single machine is a single point of failure; HA adds a replica that can be promoted.
- Asynchronous copying can lose the newest writes at failover; synchronous copying avoids that but is slower.
- Real failover must handle detection, split brain, rediscovery and the old primary's return.
- A replica is not a backup, and a failover plan must be rehearsed.
Practice
1. How many minutes of downtime per year does 99.99% allow, according to the lesson?
Show answer
About 52.6 minutes.
2. What is a single point of failure? Give an example from a database setup.
Show answer
A part whose failure stops the whole system, for example the only database server, or the only disk holding the data.
3. Why did the toy failover lose the order for the cap?
Show answer
The replica was copied before that order was written, and nothing copied it afterwards, so the replica lagged and the new primary did not have it.
4. What is split brain, and why is it dangerous?
Show answer
Two machines both act as primary and accept writes, for example after a network cut. Their data diverges and cannot be merged easily.
5. A teammate says: "We have a replica, so we don't need backups." What is wrong?
Show answer
A replica receives every change, including mistakes such as a wrong DELETE or a corrupted write. It does not give you an earlier good copy. Backups do.
6. Give one advantage and one disadvantage of synchronous copying.
Show answer
Advantage: a failover does not lose acknowledged writes. Disadvantage: every write waits for the replica, so it is slower, and a broken replica can stall the primary.