Backend Case Studies

Topic B13

Replication and eventual consistency

Primaries and replicas, replication lag, and how users keep seeing their own writes.

10 min · advanced

Watch: the new name is saved in the main database, but the copy hasn't caught up. A user reading from the copy sees the old name.

primary · Anareplica 1 · Anareplica 2 · Anauser
  • moving now
  • being checked
  • passed / marked
Step 1 of 5

One primary database takes every write. Two replicas copy changes from the primary and serve reads, so the primary isn't overwhelmed.

Replicas are always slightly behind the primary. The question isn't whether, but who may see that lagging data.

Like branch notice boards

Head office writes a notice, then a courier carries it to the board at each branch. There's a delay: the nearest branch gets it in minutes, the furthest in an hour. During that gap, anyone reading a branch board sees the old version. In the end every board matches, but not instantly.

Problems lag causes

  • Not seeing your own write: a user saves their profile, the page reloads from a replica, and the change isn't there yet (see the figure).
  • Going back in time: one request reads from an up-to-date replica, the next from one further behind. A comment that just appeared suddenly vanishes again.
  • Wrong check-then-write: "is this username taken?" is read from a replica that hasn't heard about a sign-up a moment ago.
Code, for programmersSend sensitive reads to the primary
// after a write, pin this user's reads to the primary for a few seconds
async function updateProfile(userId, data) {
  await primary.user.update({ where: { id: userId }, data });
  await redis.set(`pin:${userId}`, "1", "EX", 5);
}

async function dbFor(userId) {
  return (await redis.get(`pin:${userId}`)) ? primary : replica;
}

// checks that must be exact (unique usernames, balances) always read the primary,
// or better, rely on a UNIQUE constraint on the primary

Synchronous or asynchronous

With asynchronous replication (the default in PostgreSQL and MySQL), the primary answers "done" at once, then sends the change to replicas. Fast, but if the primary dies before the change goes out, the last writes are lost. With synchronous replication, the primary waits for at least one replica to confirm. Nothing is lost, but every write is slower, and if that replica stalls, writes stall too.

Quiz

  1. A user changes their name, reloads, and sees the old name. Most likely cause?

  2. A check for 'is this username taken' should…

  3. What's the risk with asynchronous replication?

0 of 3 answered.