Replication & High Availability — Database

Replication copies every change from the primary to the replicas through the WAL. Writes always go to the primary; reads can be spread over replicas. A…

A Sunset Coffee admin changes the price of Milk Coffee from $4.50 to $5.00. The save succeeds, but the confirmation page shows $4.50. She refreshes half a second later, and the price is $5.00. The database isn't broken. That page just read from a copy that was a little behind.

That copy is part of replication: every change from one main database (the primary) is copied continuously to other databases (replicas), so the replicas can share the reading and stand ready to take over if the primary dies. Picture a football match. The officials record the official score in the match book, and the screens around the stadium update a moment later. A fan who glances at a screen right after a goal still sees the old score. If the official book is lost, the officials use the most up-to-date screen as the official record, and any goal that hadn't reached that screen yet is lost with it.

Primary and replica

So writes always go to the primary, while reads can be shared between the primary and the replicas. Writes go to one place only so there are no conflicts: if two databases both took writes, one could set a row's price to $5.00 and the other to $5.50.

Replication gives you two things: read scaling (the many SELECTs are spread over replicas, and the primary focuses on writes) and high availability, or HA (if the primary dies, a replica takes over in seconds, not hours).

Replication lag: the old price comes back

A replica is always a little behind the primary. That gap in time is called replication lag. It's usually under a second, but it can jump to several seconds when the database is busy. In the Lab, the lag is 500 ms, a commit on the primary takes 2 ms, and replication is async (PostgreSQL's default):

Time Query Sent to Result
0 ms UPDATE products SET price = 500 WHERE id = 1 primary committed at 2 ms
3 ms SELECT price FROM products WHERE id = 1 replica 450
502 ms the WAL for that change arrives, the replica applies it replica now 500

The page shows $4.50. There's no error: the replica answers with the data it has, and that data hasn't changed yet.

This problem is called read-your-writes: you write something, then can't read back what you wrote. A common case: a user creates a post, refreshes the page, and the post isn't there yet. The cause isn't a corrupt database, a frontend bug, or the browser cache, but replication lag.

Reads and writes in Laravel

Laravel can split the queries for you. In config/database.php:

'pgsql' => [
    'driver' => 'pgsql',
    'read' => [
        'host' => ['10.0.0.11'], // replica
    ],
    'write' => [
        'host' => ['10.0.0.10'], // primary
    ],
    'sticky' => true,
    'database' => 'sunset_coffee',
    // username, password, port, ...
],

The exercise models this router with routeQuery(sql, context). Take the SQL's first word after dropping leading spaces (trim()), then compare it ignoring case (toUpperCase()):

SQL context Destination
SELECT ... { justWrote: false } or {} "replica"
SELECT ... { justWrote: true } "primary" (read-your-writes)
INSERT, UPDATE, DELETE anything "primary"
anything else: TRUNCATE, CREATE, MERGE anything "primary" (the safe default)

Sync or async

Async (PostgreSQL's default): a commit is done as soon as the primary has saved the change. The WAL goes to the replica afterwards. Sync makes the commit wait for the replica. You set it in the primary's postgresql.conf:

synchronous_standby_names = 'replica1'
synchronous_commit = remote_apply
Async Sync
The commit waits for the primary only the primary + the replica
Write speed fast (2 ms in the Lab) plus the time to the replica (502 ms in the Lab)
The primary dies changes that hadn't reached the replica are lost nothing is lost
The sync replica dies the primary carries on writes hang until the replica is back

Async suits most web apps. Sync is for data that must never be lost, such as balances and payments.

Failover: when the primary dies

When the primary dies, the HA setup performs a failover:

  1. It detects that the primary has failed several health checks in a row.
  2. It picks the most up-to-date replica, the one that is least behind.
  3. Promote: that replica becomes the new primary, for example with SELECT pg_promote();, and starts taking writes.
  4. The app is pointed at the new primary through DNS, a virtual IP, or a proxy.

Tools such as Patroni and pg_auto_failover run these steps automatically, as do managed services such as AWS RDS Multi-AZ and Google Cloud SQL HA. How long it takes depends on the setup: Patroni with its default settings takes about 30 seconds, and AWS RDS Multi-AZ usually 60 to 120 seconds. After that the app has to open new connections, because the DNS now points to another server. In the Lab, failover is modelled as 15 seconds.

With async, changes that were committed on the primary but hadn't reached the replica are lost:

Time Event
0 ms UPDATE the price to $5.00, committed at 2 ms. The admin sees "saved".
3 ms The primary dies. The WAL for that change hasn't reached the replica (it would have arrived at 502 ms).
15,003 ms The replica is promoted. The price on the new primary: $4.50. The $5.00 change is gone.

With sync, the commit only finishes at 502 ms, after the replica has applied the change. The promoted replica already has $5.00, so nothing is lost.

📌 Split-brain, several replicas, and watching the lag

⚠️ Old data coming back, and a replica mistaken for a backup

TL;DR: Replication copies every change from the primary to the replicas through the WAL. Writes always go to the primary; reads can be spread over replicas. A replica is always a little behind (replication lag), so a SELECT on a replica right after an UPDATE can return old data: in the Lab, $4.50 while the primary already has $5.00. Laravel splits queries with read and write in config/database.php; 'sticky' => true sends reads to the primary after a write, but only within the same request. Async is fast, but on failover the changes that hadn't reached the replica are lost; sync makes the commit wait for the replica, slower but nothing is lost. When the primary dies, failover promotes the most up-to-date replica to be the new primary, usually within 30 to 120 seconds, depending on the setup. A replica is not a backup.

⚡ Primary and replica

Meaning: Replication copies every change from the primary to the replicas through the WAL. Writes always go to the primary, while reads can be shared between the primary and the replicas.

⚡ The old price comes back

Write:

UPDATE products SET price = 500 WHERE id = 1;
SELECT price FROM products WHERE id = 1;
Guess first: the UPDATE goes to the primary, then 3 ms later the SELECT goes to a replica. What price comes back?

Still 450. A replica is always a little behind (replication lag), and in the Lab that change only arrives at 502 ms.

Meaning: A page opened right after a user writes must read from the primary. In Laravel, 'sticky' => true does that, but only within the same request.

In the exercise, tidy the SQL first with trim() and toUpperCase(), and unknown SQL goes to "primary".

⚡ Failover, and a replica isn't a backup

Meaning: When the primary dies, the most up-to-date replica is promoted to be the new primary, usually within 30 to 120 seconds, depending on the setup. With async, changes that hadn't reached the replica are lost. A DELETE without a WHERE is copied too, so backups are still a must.

What you will learn