Data Consistency Patterns — System Design

When data has several copies, the consistency model decides what may be read. Asynchronous replication leaves replicas behind (replication lag, 1,000 ms in…

A campus has notice boards in three buildings. The academic office pins a new notice in the main building, then a courier carries photocopies to the others. The courier to building A is quick, the one to building B is slow. Students in building B still read the old schedule, though the main board has changed.

The main board is the primary, the other boards are replicas, and the courier is replication. When data has several copies on several servers like this, consistency is a promise about which data you may read. A consistency model answers: who may read which board, and when.

A replica that lags behind

In the Database Scaling lesson, TicketTune added read replicas: copies of the PostgreSQL database that serve SELECTs while every write still goes to the primary. Replication is asynchronous: the primary answers "success" as soon as the write is stored on the primary, and sends the change to the replicas afterwards. The time until a replica has that data too is called replication lag. During the ticket war the replicas are busy, so the lag swells. This lesson's example model: the replica is 1,000 ms behind.

ms Primary Replica Budi reloads
0 UPDATE: email becomes [email protected] still [email protected]
500 [email protected] still [email protected] reads from the replica: [email protected]
1,000 [email protected] applies the change: [email protected]

Budi reloads at 500 ms and sees his own old email. He thinks his change failed, so he changes it again, or contacts support. The data isn't broken; 500 ms later the replica catches up. The problem is the promise the system makes to its readers.

Strong and eventual

The two ends of the promise:

Most of TicketTune's data is fine with eventual: a seat count on the concert page that's 1 second late hurts nobody. But two cases confuse users, and two promises in the middle deal with them.

Read-your-writes

Read-your-writes promises one thing: whoever wrote something always sees their own write. Other people may still see the old data for a moment. That's enough for Budi, and it doesn't force every read onto the primary.

How, in PostgreSQL: after the write, the app stores the log position (the LSN, Log Sequence Number) in Budi's session, from pg_current_wal_lsn(). Before reading from a replica, it checks whether the replica has applied that position:

// read-your-writes: whoever just wrote reads from the primary
// until the replica has applied their write
async function readSource(session) {
  if (!session.lastLsn) return replica; // never wrote anything
  const { rows } = await replica.query(
    "SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn AS applied",
    [session.lastLsn]
  );
  return rows[0].applied ? replica : primary;
}

A simpler way: after a write, read from the primary for a few seconds (Rails uses 2 seconds by default for this).

Causal consistency

The second case needs two writers. The Archipelago Concert page has a discussion. TicketTune's discussion database is sharded by author (the Database Scaling lesson), so:

Siti reads at Budi's question (shard-1, arrives at 1,200 ms) Admin's answer (shard-2, arrives at 700 ms)
800 ms, eventual not there yet "Yes, in basement P2"
800 ms, causal not there yet held back
1,200 ms, causal there there

With eventual, Siti sees an answer to a question that doesn't exist yet. Causal consistency prevents it: if write B was made after its writer saw write A (B depends on A), anyone who sees B must also see A. To do it, the admin's answer carries a note "I'm replying to the question at version so-and-so on shard-1", and the answer is only shown once its question is visible. Read-your-writes doesn't help Siti here, because Siti wrote nothing herself. The other way round, causal already includes read-your-writes: Budi's read depends on his own write.

Promise What it guarantees Price
Strong every read sees the latest write every read on the primary, or writes wait for replicas
Causal a dependent write never appears before what it depends on recording and checking dependencies
Read-your-writes a writer sees their own write a writer's reads sometimes go to the primary
Eventual the same in the end old data can be read for a while

Outbox: the database and the event must tell the same story

Another consistency problem: one action changes two systems. When order #1001 is paid, order changes its status in PostgreSQL and sends an order.paid event to the e-ticket queue (the Message Queue lesson). If the order process crashes between the two:

The outbox pattern solves it: the event is written as a row in an outbox table, in the same database transaction as the data change. Both are stored, or neither is. A separate process (the relay) reads that table and publishes to the queue.

// order: mark #1001 paid AND record its event, in ONE transaction
const client = await pool.connect();
try {
  await client.query("BEGIN");
  await client.query("UPDATE orders SET status = 'paid' WHERE id = $1", [1001]);
  await client.query(
    "INSERT INTO outbox (topic, payload) VALUES ($1, $2)",
    ["order.paid", JSON.stringify({ orderId: 1001 })]
  );
  await client.query("COMMIT");
} catch (err) {
  await client.query("ROLLBACK");
  throw err;
} finally {
  client.release();
}

// relay: a separate process, runs every second
async function sendOutbox() {
  const { rows } = await pool.query(
    "SELECT id, topic, payload FROM outbox WHERE sent_at IS NULL ORDER BY id LIMIT 100"
  );
  for (const row of rows) {
    await queue.publish(row.topic, row.payload);
    await pool.query("UPDATE outbox SET sent_at = now() WHERE id = $1", [row.id]);
  }
}
setInterval(sendOutbox, 1000);

Instead of polling every second, the relay can also read PostgreSQL's log directly (CDC, Change Data Capture, for example with Debezium), so events go out sooner.

Consistency across services: a glimpse of Saga

The outbox keeps one service honest. When one action needs changes in several services (book a seat in ticket, charge the card in payment), a Saga is used: a sequence of local transactions in each service, and if one step fails, the steps already done are undone with a compensating transaction (the seat is released again, say). Why not one big transaction is covered in the Distributed Transactions lesson, and Saga is taken apart in the Saga Pattern lesson.

⚠️ An email that reverts and an e-ticket sent twice

TL;DR: When data has several copies, the consistency model decides what may be read. Asynchronous replication leaves replicas behind (replication lag, 1,000 ms in the Lab's model), so Budi can see his own old email after changing it. Strong consistency: every read returns the latest data, expensive because it needs coordination. Eventual consistency: the data ends up the same, but may be stale for a while, cheap and scalable. Read-your-writes: a writer always sees their own write (check the replica's LSN, or read from the primary for a moment). Causal: a write that depends on another must not appear before it (an answer before its question). Outbox pattern: store the event in an outbox table in the same transaction as the data, then a relay (polling or CDC) publishes it to the message broker; events go out at least once, so consumers must be idempotent. Saga: a sequence of local transactions per service, with a compensating transaction when a step fails.

⚡ A replica that lags behind

Guess first: Budi changes his email, then reloads 500 ms later. The read comes from a replica that is 1,000 ms behind. Which email does he see?

His own old email, [email protected]. The data isn't broken; 500 ms later the replica catches up.

Meaning: Asynchronous replication leaves replicas behind (replication lag). Eventual consistency: the data ends up the same, but may be stale in the meantime.

⚡ Read-your-writes and causal

Meaning: Read-your-writes guarantees a writer always sees their own write: if the replica hasn't applied the LSN of Budi's write yet, Budi's read goes to the primary. Causal guarantees that a write depending on another never shows up first: the admin's answer only shows once Budi's question shows.

⚡ Outbox: one transaction

Write:

await client.query("BEGIN");
await client.query("UPDATE orders SET status = 'paid' WHERE id = $1", [1001]);
await client.query(
  "INSERT INTO outbox (topic, payload) VALUES ($1, $2)",
  ["order.paid", JSON.stringify({ orderId: 1001 })]
);
await client.query("COMMIT");

Meaning: The event is stored as a row in an outbox table, in the same database transaction as the data change. Both are stored, or neither is.

⚡ The relay sends, the consumer is idempotent

Meaning: A separate process (the relay) reads the rows whose sent_at is still empty, publishes them to the queue, then marks them sent. If the relay crashes midway, the event is sent twice, so the consumer must be idempotent.

What you will learn