Subscribe

Consistency explained with examples: CAP, PACELC and read-your-writes

CAP and PACELC make more sense once you watch a replica return stale data. I set up a Postgres 18 primary and replica, broke read-your-writes on purpose, fixed it with WAL positions in Go, and timed what eventually means in milliseconds.

Consistency explained with examples: CAP, PACELC and read-your-writes

Most explanations of CAP stay at the level of three letters in a triangle. I find it much easier to understand once you have watched a replica return old data with your own eyes. So in this blog we will set up a Postgres primary with a streaming replica on a laptop, break things on purpose, and fix the most common bug: a user signs up and the next page says "user not found".

This is an intermediate post. You need Docker, Go and a bit of SQL. I used Go 1.27.3, Postgres 18.7 (the postgres:18-alpine image) and pgx v5.13.0. The full code is a small Go module with a setup script for the two databases.

As with the other posts in this series, we go requirements, estimates, a diagram, the deep dive, then trade-offs.

Requirements

The example is a signup flow.

  • A user signs up. The row goes to the primary.
  • The next page shows their profile. Reads should go to a replica where possible, because reads are most of the traffic.
  • The user must see their own signup straight away. Other users seeing it a second later is fine.
  • If the replica dies, signups keep working.

That third line is the interesting one. It's called read-your-writes, and it's weaker than "everyone sees everything instantly" but stronger than "eventually".

Estimates

Say 50 reads per write, which is normal for a profile-type app. If the primary takes 200 writes a second at peak, that's 10,000 reads a second, so moving reads to replicas is worth doing. (The way to get these numbers is in system design basics.)

The other number we need is replica lag: how long after a commit the replica has the row. People say "eventually" and never put a number on it. I measured it further down. On my laptop it was about half a millisecond at the median, and a lot more on the first cold run.

High-level design

                 writes (signup)
   app  ---------------------------------->  primary (Postgres 18)
    |                                           |
    |   reads (profile, lists)                  |  WAL stream (async)
    +------------------------------------> replica (hot standby)

The primary streams its write-ahead log (WAL) to the replica, and the replica replays it. Asynchronous by default: the primary says "committed" without waiting for the replica.

CAP and PACELC in one paragraph each

CAP says that when the network between two copies of your data breaks (a partition), you must pick. Either you refuse requests until the copies can talk again (consistency) or you keep answering and accept that the copies disagree (availability). You don't get to pick "no partitions", networks fail.

PACELC adds the part CAP leaves out. If there is a Partition, choose Availability or Consistency; Else, when everything is healthy, choose Latency or Consistency. That "else" half is what you deal with every day. Waiting for the replica on every commit makes things consistent and slower. Not waiting is fast and gives you stale reads. We will see both below.

Setting up a primary and a replica

The script in the code folder does this. The important bits are an extra pg_hba.conf line so the replica can connect for replication, and pg_basebackup -R, which copies the data and writes the standby settings for you.

docker network create pgdemo
docker run -d --name pg-primary --network pgdemo -e POSTGRES_PASSWORD=dev \
  -p 127.0.0.1:5433:5432 postgres:18-alpine
docker exec pg-primary sh -c 'echo "host replication all all scram-sha-256" >> "$PGDATA/pg_hba.conf"'
docker exec pg-primary psql -U postgres -c "SELECT pg_reload_conf()"

docker run -d --name pg-replica --network pgdemo -e PGPASSWORD=dev \
  -p 127.0.0.1:5434:5432 --user postgres postgres:18-alpine sh -c "
    pg_basebackup -h pg-primary -U postgres -D /var/lib/postgresql/18/docker -R -X stream --checkpoint=fast &&
    exec postgres -D /var/lib/postgresql/18/docker -c recovery_min_apply_delay=2s"

Two things caught me here. The Postgres 18 image keeps its data in /var/lib/postgresql/18/docker, not the old /var/lib/postgresql/data, so older tutorials point at the wrong folder. And when I recreated the replica later without --checkpoint=fast, pg_basebackup just sat there waiting for checkpoint and the replica wasn't reachable. Adding the flag fixed it.

recovery_min_apply_delay=2s is a cheat. It makes the replica wait two seconds before applying anything, so lag is big enough to see. Real lag is usually much smaller, but under heavy writes or a long running query on the replica it can grow to seconds.

Breaking read-your-writes

The demo inserts a user on the primary, then reads it from the replica straight away.

func stale(ctx context.Context, d *db.DB) {
    email := fmt.Sprintf("asha+%d@example.com", time.Now().UnixNano())
    if _, err := signup(ctx, d, email); err != nil {
        log.Fatal(err)
    }
    start := time.Now()
    name, err := findUser(ctx, d.Replica, email)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("stale: replica right after signup: found=%v\n", name != "")
    for name == "" {
        time.Sleep(50 * time.Millisecond)
        if name, err = findUser(ctx, d.Replica, email); err != nil {
            log.Fatal(err)
        }
    }
    fmt.Printf("stale: replica caught up after %s\n", time.Since(start).Round(10*time.Millisecond))
}

The very first run itself didn't get that far.

ERROR: relation "users" does not exist (SQLSTATE 42P01)

The program creates the table on the primary at startup, and then reads from the replica. The CREATE TABLE was still sitting in the replica's two second delay. Schema changes are replicated exactly like rows, so they lag too. I hadn't thought about that one before, and it's a real thing to keep in mind when a migration runs and the new code reads from a replica a moment later (the expand and contract post is about exactly that ordering).

Second run:

stale: replica right after signup: found=false
stale: replica caught up after 1.96s

That's the bug users report as "I signed up and it says my account doesn't exist".

Fixing it with WAL positions

Every commit has a position in the WAL, called an LSN. The primary can tell you its current position, and a replica can tell you how far it has replayed. If the replica has replayed past your write, it's safe to read from it. If not, read from the primary only.

The write side returns the LSN after commit.

func (d *DB) Write(ctx context.Context, fn func(pgx.Tx) error) (string, error) {
    conn, err := d.Primary.Acquire(ctx)
    if err != nil {
        return "", err
    }
    defer conn.Release()

    if err := pgx.BeginFunc(ctx, conn, fn); err != nil {
        return "", err
    }
    var lsn string
    err = conn.QueryRow(ctx, "SELECT pg_current_wal_lsn()::text").Scan(&lsn)
    return lsn, err
}

In a web app you would put that LSN in the session or a short lived cookie. The read side checks it.

func (d *DB) Reader(ctx context.Context, minLSN string) (*pgxpool.Pool, string, error) {
    if minLSN == "" {
        return d.Replica, "replica", nil
    }
    var caughtUp bool
    err := d.Replica.QueryRow(ctx,
        "SELECT coalesce(pg_last_wal_replay_lsn() >= $1::pg_lsn, false)", minLSN).Scan(&caughtUp)
    if err != nil {
        // Replica unreachable: the primary can always answer.
        return d.Primary, "primary (replica error)", nil
    }
    if caughtUp {
        return d.Replica, "replica", nil
    }
    return d.Primary, "primary", nil
}

pg_current_wal_lsn() runs after the commit, so it's a tiny bit ahead of the commit itself. That only means we go to the primary slightly more often than strictly needed. Safe side.

Running it with the same two second delay:

ryw: signup committed at LSN 0/303CE68
ryw: t+0.0s read from primary  found=true
ryw: t+1.0s read from primary  found=true
ryw: t+2.5s read from replica  found=true

The user sees their row every time. Once the replica catches up, reads move back to it by themselves. Other users without an LSN in their session keep reading from the replica the whole time, and they might not see the new user for two seconds. That is the deal we wrote in the requirements.

The cost is one extra tiny query to the replica per read. If that bothers you, a simpler version is "read from the primary for 5 seconds after any write by this user". Cruder, works fine for most apps.

What eventually means in numbers

Next I removed the delay and measured the real lag: 200 signups, each one followed by reading the replica in a tight loop until the row shows up.

lag: 200 writes, p50=1.592ms p99=19.613ms max=28.324ms
lag: 200 writes, p50=531µs p99=2.873ms max=3.646ms
lag: 200 writes, p50=513µs p99=1.976ms max=3.98ms

The first of the three runs were cold and slower. After that, half a millisecond. With no delay my "stale" test found the row on the replica straight away, both times I ran it. That is exactly why this bug passes every test on a laptop and shows up in production under load, when lag goes from microseconds to seconds.

Paying for consistency: synchronous replication

Postgres can wait for the replica before saying "committed". With synchronous_commit = remote_apply the commit returns only after the replica has applied it, so a read on the replica right after a write always sees it.

docker exec pg-primary psql -U postgres \
  -c "ALTER SYSTEM SET synchronous_standby_names = '*'" \
  -c "ALTER SYSTEM SET synchronous_commit = 'remote_apply'" \
  -c "SELECT pg_reload_conf()"

This is the "else" half of PACELC: latency for consistency. I measured signup latency both ways.

writes (synchronous_commit=on): p50=1.345ms p99=3.621ms
writes (synchronous_commit=remote_apply): p50=1.431ms p99=2.602ms

Almost no difference, and honestly that surprised me for a second. Then it made sense, both containers run in the same VM on my laptop, so the "network" is a memory copy. Between two availability zones you would add a round trip of around a millisecond to every commit, between regions tens of milliseconds.

Now the "P" half. I stopped the replica and tried a signup.

docker stop pg-replica
docker exec pg-primary timeout 5 psql -U postgres \
  -c "INSERT INTO users (email, name) VALUES ('cap@example.com', 'Ravi')"

It hung until timeout killed the client. On the primary the backend was still there, waiting:

 pid | wait_event_type | wait_event | state  |                    q
-----+-----------------+------------+--------+------------------------------------------
 169 | IPC             | SyncRep    | active | INSERT INTO users (email, name) VALUES (

Setting statement_timeout = '2s' in the session did not stop the wait either, it sat there until I cancelled it with pg_cancel_backend. Then psql printed this:

WARNING:  canceling wait for synchronous replication due to user request
DETAIL:  The transaction has already committed locally, but might not have been replicated to the standby.
INSERT 0 1

That's CAP in one screen. With one sync replica down, the system chose consistency and stopped accepting signups. But see, the escape hatch has its own surprise: the row is committed on the primary anyway. Before the cancel a count from another session returned 0, after it returned 1. So the client saw an error or a hang, but the user exists. Retrying signups must be safe because of that (an idempotency key or a unique email does it).

In production people use synchronous_standby_names = 'ANY 1 (r1, r2)' with two replicas, so one can die without blocking writes.

Stale caches are the same problem

A cache is a replica you maintain by hand. With cache-aside and a 60 second TTL, a profile update can be invisible for up to 60 seconds, which is eventual consistency with a bound of 60 seconds. Deleting the key after the write narrows it but there is still a race: a reader can fill the cache with the old row just after you delete. The caching strategies post goes through those cases. The same read-your-writes trick works there too, skip the cache for a user's own data for a few seconds after they change it.

Trade-offs

Here is how I think about the levels, from cheapest to most expensive.

  • Eventual: read any replica. Fine for counts, feeds and search results.
  • Read-your-writes: the LSN check above. Good for anything a user just edited.
  • Monotonic reads: with two or more replicas, a user can see a new row on one and then lose it on a slower one. Pin each session to one replica.
  • Strong: sync replication or read from the primary. Use it for money and stock levels, where a stale read leads to a wrong action. The transactions and isolation levels post covers what happens inside that one database.

Managed databases make the same trade visible. DynamoDB reads are eventually consistent by default, and a strongly consistent read costs twice the read capacity. Same PACELC, with a price tag.

Clean up with docker rm -f pg-primary pg-replica && docker network rm pgdemo. If you only take one thing to your own code, make it the LSN check for a user's own data.