All posts
  • #databases
  • #replication
  • #consistency

Read-Your-Writes: Why Your Wallet Says ₹0 Right After You Added ₹100

Replication lag, stale reads and the session guarantee that fixes them. How primaries and replicas drift apart, five production fixes from returning the write to LSN tokens and synchronous replication, and how Facebook, GitHub, Rails and Cosmos DB handle it. With a live simulator.

Akshit Bansal20 min readPart 7

where did my ₹100 go?
on this page

In one minute

  • Your database cluster has one primary that takes every write and replicas that copy it a moment later. That moment is replication lag.
  • Write to the primary, read from a replica before the copy arrives, and you get old data: a stale read. The ₹100 you just added "vanishes".
  • The promise you want is read-your-writes: once your write succeeds, your reads always include it. Other people can be a beat behind.
  • Fixes, from simplest to most precise: return the new value from the write itself, read the user's own data from the primary, stick to the primary for a few seconds, or carry a version token so reads only hit replicas that have caught up. Synchronous replication also works, at a price.

Words you need

  • Primary

    The one database server that accepts writes. Also called the leader (older docs say master).

    Like the bank's head-office ledger

  • Replica

    A read-only copy of the primary on another server. It replays the primary's changes to stay up to date. Also called a follower or read replica.

    Like a branch office holding a photocopy of the ledger

  • Replication

    Shipping every change from the primary to the replicas, in order.

    Like the courier carrying fresh photocopies to the branches

  • Async replication

    The primary says 'done' as soon as it has saved the change, without waiting for any replica. The default in PostgreSQL and MySQL.

    Like dropping a letter in the post box and walking away

  • Sync replication

    The primary says 'done' only after a replica confirms it has the change.

    Like a registered letter: you wait for the signature

  • Replication lag

    How far behind a replica is, in time or in log entries. Usually tiny; under load it can grow to seconds or more.

    Like how old the branch's photocopy is

  • WAL / binlog

    The primary's numbered diary of every change. Replicas replay it. PostgreSQL calls it the write-ahead log (WAL), MySQL the binary log.

    Like the courier's numbered delivery list

  • LSN / GTID

    A position in that diary. PostgreSQL uses a Log Sequence Number (LSN), MySQL a Global Transaction ID (GTID). Later changes have bigger positions.

    Like a page number in the diary

  • Stale read

    A read that returns older data than something you already know has happened.

    Like the branch saying your cheque hasn't cleared when head office cleared it a minute ago

  • Read-your-writes

    A promise: after your write succeeds, your own reads always include it. Also called read-after-write consistency.

    Like after you post a photo, you always see your own photo

  • Session

    One user (or device) talking to your app over time. A session guarantee is a promise to that user, not to everyone.

    Like one customer's visit to the bank

  • Router

    Whatever decides which server a query goes to: your app code, a library such as Rails, or a proxy such as ProxySQL or Pgpool-II.

    Like the receptionist sending you to a counter

The ₹0 shock

Here is the bug from the user's side. Three screens, a fraction of a second apart.

1 · Add money

PayWallet

Amount

₹ 100

Add ₹100

answered by primary

2 · Success

PayWallet

₹100 added

Txn #8812

answered by primary

3 · Refresh

PayWallet

Wallet balance

₹0.00

Where did my ₹100 go?

Recent

No transactions yet

answered by replica 2 (behind)

The write landed on the primary. The refresh was answered by a replica that hasn't heard about it yet.
  • Nothing was lost. The primary has ₹100. Replica 2 will have it in a moment.
  • It still looks broken. For that moment, money vanished. In a payments app that means a support ticket, a second top-up (now they've paid twice), or an uninstall.
  • It's the same bug everywhere: an edited profile that reverts on refresh, a comment that disappears after you post it, a "your order" page that says you have no orders.

Why it happens

Your appsends writes and reads
Router / load balancerwrites → primary, reads → any of the three

Primary

accepts writesbalance ₹100 · LSN 42

Replicas (read-only copies)

Replica 1LSN 42 · ₹100, caught up
Replica 2LSN 41 · ₹0, still behind
Writes go to the primary. Reads are spread over all three nodes. Copies reach the replicas a little later, and not all at the same time.

Why bother with replicas at all? Because most apps read far more than they write, and one server only goes so far.

  • Scale reads

    Spread reads over many servers instead of one. Add a replica, get more read capacity.

  • Survive a crash

    If the primary dies, a replica can be promoted to take over (failover).

  • Keep heavy work away

    Reports, exports and analytics run on a replica so they don't slow down payments.

  • Be near the user

    A replica in another region answers reads without a round trip across the world.

Step through the race

The bug is a race between two things: the change travelling to the replica, and your read travelling to the replica. The read is a single hop. The change has to be shipped and replayed. The read often wins.

press play, or step through

Your app

phone + server

Primary

₹100 · LSN 42

Replica 2

₹0 · LSN 41

  1. 0 ms

    UPDATE balance + 100

Step 1/6: Writes always go to the primary. It commits the change and writes it to its log as entry 42.

Why replicas fall behind

Lag is not a fixed number. It is small most of the time and jumps when something is busy.

  • Nobody waits

    With async replication the primary answers before any replica has the change. Some lag is built in by design.

  • Distance

    A replica in another zone or region is further away, so every change takes longer to arrive.

  • Busy replica

    Replaying changes competes with the replica's own read queries for CPU and disk.

  • Big writes

    A migration or an UPDATE that touches millions of rows has to be replayed in full on every replica.

  • Long queries

    PostgreSQL can pause replay rather than cancel a long query on the replica (max_standby_streaming_delay). Lag grows while it waits.

  • Catching up

    A replica that restarted or was just added has a backlog to replay before it is current.

Quick check: Replication lag on your dashboard is usually around 20 ms. Is adding a 50 ms sleep after each write a good fix?

Name it: read-your-writes

This guarantee has a name, and it comes from a 1994 paper by Doug Terry and colleagues at Xerox PARC on the Bayou system: "Session Guarantees for Weakly Consistent Replicated Data". They noticed that users don't need every copy to be perfect. They need the system to never contradict what they already did or saw. They wrote down four such promises.

Session guaranteePlain meaningHow it breaks in a wallet
Read your writesYou always see your own changes.Add ₹100, refresh, see ₹0.
Monotonic readsTime never goes backwards for you.Refresh shows ₹100, refresh again (different replica) shows ₹0.
Monotonic writesYour writes apply in the order you made them.'Add ₹100' then 'pay ₹50' applied in reverse, so the payment is declined.
Writes follow readsA write you make because of something you read is ordered after it.You pay a friend's request; someone else sees your payment before the request exists.

Where it sits among the usual consistency levels:

EventualRead-your-writesStrong (linearizable)
PromiseCopies agree… somedayYou see your own writes right awayEveryone sees every write right away, in one order
Who sees your ₹100 at once?Nobody is promisedYouEveryone
Your friend, 1 s laterMight see ₹0Might see ₹0Sees ₹100
CostCheapestCheap: only your reads need careEvery read or write pays for coordination
Good forLike counts, view counts, feedsProfiles, settings, your own orders and balanceBalances used to approve a payment, unique usernames, stock levels

Try it: break it, then fix it

InteractiveWallet on a replicated database
tap “Add + refresh”

Reads go to any of the three nodes at random. This is the bug from the story.

PayWallet

Wallet balance

₹0

Balance loaded

not refreshed yet

Router: Waiting for your first request.

Primary

LSN 41

₹0

Replica 1

LSN 41in sync

₹0

Replica 2

LSN 41in sync

₹0

stale reads
0 / 0
reads on primary
–
last write took
–
  1. Tap “Add + refresh” to reproduce the bug.
Writes commit on the primary and ship to each replica after the lag you set (Replica 2 is 1.6× slower). Refresh goes through the router using the strategy you pick. Times are slowed down so you can watch them.

Things to try:

  1. Any node, lag 1.5 s, press "Add + refresh" a few times. Roughly two refreshes in three hit a replica that hasn't caught up yet.
  2. Primary after a write, set the window to 1 s and the lag to 2.5 s. The window expires before the replicas catch up, and the bug comes back.
  3. Version token. Never stale, and reads go back to replicas as soon as one catches up. Check "reads on primary".
  4. Sync replication. Never stale, but look at "last write took": every write now waits for the slowest replica.

The fixes

Fix 1: don't read at all

The cheapest read is the one you skip. The write already knows the new balance, so send it back.

add_money.sqlsql
-- One round trip: change the balance and return the new value from the primary.UPDATE walletsSET balance = balance + $2WHERE user_id = $1RETURNING balance;
  • The success screen shows the balance from this response, not from a fresh query.
  • Pair it with optimistic UI: show "₹100 added" as soon as the server says OK, and keep that value on the device for the next screen.
  • Limit: it only covers the screen that made the write. Reload, another tab, the transaction history, another device: all of those still read. You need one of the fixes below as well.

Fix 2: read your own data from the primary

Split reads by whose data they are.

Incoming readwho owns this data?

The user's own data

balance, transactions, profile→ primary, always fresh

Everyone else's / shared data

offers, merchant list, feed→ replicas, a little late is fine
The user's own money data reads from the primary. Everything else reads from replicas.
db.tsts
// The few queries that must see the user's latest writes are marked; the rest use replicas.export function dbFor(read: { ownData: boolean }) {  return read.ownData ? primary : pickReplica();}const wallet = await dbFor({ ownData: true }).query(  "SELECT balance FROM wallets WHERE user_id = $1",  [userId],);
  • Cost: the primary serves every "my data" read. For a wallet that is usually fine: a balance is one indexed row.
  • Breaks when "my data" is most of your traffic. Then the replicas sit idle and the primary is the bottleneck again.

Fix 3: stick to the primary for a while after a write

After a user writes, send their reads to the primary for a few seconds. After that, the replicas have almost certainly caught up.

  1. 01

    User writes

    commit on primary

  2. 02

    Remember when

    wrote:user = now, expires in 2 s

  3. 03

    Next read

    flag still there?

  4. 04

    Yes → primary

    no → any replica

sticky.tsts
// The window must be longer than your worst realistic lag, not your average lag.const WINDOW_MS = 2_000;export async function afterWrite(userId: string) {  // Kept per user in Redis (not a cookie), so it also covers the user's other devices.  await redis.set(`wrote:${userId}`, "1", { PX: WINDOW_MS });}export async function dbForRead(userId: string) {  return (await redis.exists(`wrote:${userId}`)) ? primary : pickReplica();}

Rails has this built in (Rails 6 and later), with a 2-second default:

config/environments/production.rbruby
config.active_record.database_selector = { delay: 2.seconds }config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolverconfig.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session

Fix 4: version tokens (the precise one)

Instead of guessing how long to wait, remember how far the primary had got when your write committed, and only read from a replica that has got at least that far.

  1. 01

    Write

    commit on the primary

  2. 02

    Read its position

    LSN 0/3A0 or a GTID

  3. 03

    Save the token

    per user, in Redis

  4. 04

    Pick a replica

    replayed ≥ token?

  5. 05

    None ready?

    wait a little or use the primary

PostgreSQL, with node-postgres:

wallet.tsts
// 1. Write on the primary. With autocommit, the UPDATE has committed when it returns.const { rows } = await primary.query(  "UPDATE wallets SET balance = balance + $2 WHERE user_id = $1 RETURNING balance",  [userId, 100],);// 2. Ask how far the primary's log has got. It is at or past our commit.const { rows: pos } = await primary.query("SELECT pg_current_wal_insert_lsn() AS lsn");await redis.set(`ryw:${userId}`, pos[0].lsn, { EX: 60 });// 3. Later, for a read: use a replica that has replayed at least that far.export async function dbForRead(userId: string) {  const token = await redis.get(`ryw:${userId}`);  if (!token) return pickReplica();  for (const replica of shuffle(replicas)) {    const { rows } = await replica.query(      "SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn AS fresh",      [token],    );    if (rows[0].fresh) return replica;  }  return primary; // nobody has caught up yet}

MySQL, with GTIDs. The replica can even wait for the change instead of refusing:

mysql_token.sqlsql
-- On the primary, right after the write: which transactions have committed?SELECT @@GLOBAL.gtid_executed;-- On the replica, before the read: wait up to 1 second for that set.-- Returns 0 when caught up (run the read here), 1 on timeout (use the primary).SELECT WAIT_FOR_EXECUTED_GTID_SET('3E11FA47-71CA-11E1-9E33-C80AA9429562:1-77', 1);

MongoDB has the token built in, called a causally consistent session:

mongo.jsjs
// Inside one session, reads see the session's earlier writes, even on a secondary.const session = client.startSession({ causalConsistency: true });const wallets = client.db("pay").collection("wallets");await wallets.updateOne(  { userId },  { $inc: { balance: 100 } },  { session, writeConcern: { w: "majority" } },);const wallet = await wallets.findOne(  { userId },  { session, readPreference: "secondary", readConcern: { level: "majority" } },);
  • Across HTTP requests, save the session's operationTime and clusterTime, and call advanceOperationTime and advanceClusterTime on the next request's session.
  • Cost: one extra tiny query per read in the simple version. Routers avoid it by checking each replica's position a few times a second and keeping it in memory.
  • Breaks when the token store is down. Then treat every read as "no token" or send it to the primary; never fail the request.

Fix 5: synchronous replication

Make the primary wait until replicas have applied the change before it says OK. Then any replica you read from is fresh.

postgresql.confini
# Wait for both standbys to replay the change before COMMIT returns.synchronous_standby_names = 'FIRST 2 (replica1, replica2)'synchronous_commit = remote_apply
synchronous_commitCOMMIT returns after…Read-your-writes on the replica?
off / localthe primary alone has itNo
remote_writethe standby received it (not yet on its disk)No
on (with sync standbys)the standby saved it to diskNo: saved is not yet replayed
remote_applythe standby replayed it, so queries there can see itYes
  • MySQL: semi-synchronous replication is not enough. It waits for a replica to receive the change, not to apply it. Group Replication's group_replication_consistency setting (BEFORE or AFTER) is the one that gives fresh reads.
  • Cost: every write now takes as long as the slowest synchronous replica. Cross-region, that is very noticeable.

Don't forget the cache

If you cache balances in Redis or Memcached, the cache is one more copy that can lag.

  • On a write, update or delete the cached value in the same code path.
  • Never fill the cache from a replica that is behind, or you'll freeze the stale value in place for the whole TTL. Facebook hit exactly this (case file #1).

Quick check: You use 'primary after a write' with a 2-second window. A big migration pushes replica lag to 10 seconds. What does a user see if they add money and refresh after 3 seconds?

Which fix should you ship?

Return from writeOwn data on primaryPrimary after a writeVersion tokenSync replication
Always fresh for the user?Only on that screenYesOnly while lag stays under the windowYesYes
Extra load on the primaryNoneHigh: every own-data readMedium: reads just after writesLow: only while replicas are behindNone
Write latencyUnchangedUnchangedUnchangedOne tiny extra queryPlus the slowest replica's replay
Works across devices?NoYesIf stored per user on the serverIf stored per user on the serverYes
EffortTinySmallSmall (built into Rails)MediumA config line, plus ops work
Breaks whenthe user reloads or opens another screenthe primary is overloadedlag spikes past the windowthe token store is down (fall back to the primary)a sync replica is slow or dead

Production checklist

  • Measure lag

    pg_stat_replication · SHOW REPLICA STATUS

    Graph and alert on it. PostgreSQL shows replay_lag per standby on the primary; MySQL shows Seconds_Behind_Source on each replica.

  • Eject lagging replicas

    ProxySQL max_replication_lag

    A replica that is too far behind should stop getting reads until it catches up. Proxies like ProxySQL can do this per server.

  • Pin users to a replica

    Hash the user ID to pick a replica, so a user's balance doesn't flicker between two replicas at different positions (monotonic reads).

  • Test with a slow replica

    recovery_min_apply_delay = '5s'

    In staging, delay a replica on purpose (MySQL: SOURCE_DELAY). If the app still looks right with 5-second-old data, your fix works.

  • Background jobs too

    A job queued right after a write may read from a replica and not find the new row. Pass the token to the job, or read from the primary.

  • Know your failover

    With async replication, promoting a lagging replica loses the writes it never got. That's durability, a separate problem from read-your-writes.

What your database already gives you

DatabaseReads by defaultRead-your-writes option
PostgreSQLAsync streaming replicas; your app or proxy picks the serversynchronous_commit = remote_apply, or an LSN token checked with pg_last_wal_replay_lsn()
MySQLAsync binlog replicasGTID token with WAIT_FOR_EXECUTED_GTID_SET; Group Replication group_replication_consistency
MongoDBReads go to the primary unless you set a readPreferenceCausally consistent sessions, with majority read and write concern
Amazon DynamoDBEventually consistent readsConsistentRead: true on the table (not on global secondary indexes)
Azure Cosmos DBSession consistency is the default levelA session token per client, sent with each read
Ruby on RailsReplicas for GET and HEAD with automatic role switchingPrimary within the delay window after a write (2 s default)

In the wild: case files

Case file #01

Facebook

Big tech · 2013

a marker that says 'I just changed this'

The problem
Facebook ran MySQL replicas in several regions, with one master region taking writes, and a huge memcache layer in front. A user who changed something from a non-master region could read it back from the local replica before replication caught up, and the stale value could end up cached.
The fix
Their NSDI 2013 paper describes 'remote markers'. Before the write, the web server sets a marker for that key in the local region. Reads that find the marker go to the master region instead of the local replica, until replication catches up and the marker is gone. Cache refills from a replica are also held back until the replication stream has caught up.
The lesson
A tiny per-key 'just changed' flag routes only the affected reads to the primary. And caches need the same care as replicas, or they freeze stale data in place.
Source: Nishtala et al., Scaling Memcache at Facebook (NSDI 2013)(opens in a new tab)
Case file #02

GitHub

Big tech · 2017

measure lag, don't guess it

The problem
GitHub's Rails app writes to MySQL primaries and wants to read from replicas. Right after a write, it can't know whether the replicas have the change, so those reads defaulted to the primary. Big write jobs (migrations, archiving) also pushed replicas behind.
The fix
GitHub built freno, a highly available service that constantly checks replication lag across its MySQL replicas. Apps ask it whether replicas are caught up enough before reading from them, and heavy write jobs ask it whether to slow down. That moved reads off the primaries safely.
The lesson
Once you can see lag, you can route reads after writes to replicas when it's safe, and make writers back off before they cause the lag.
Source: GitHub blog: Mitigating replication lag and reducing read load with freno(opens in a new tab)
Case file #03

Ruby on Rails

Open-source framework · 2019 (Rails 6.0)

the 2-second window

The problem
Apps adding read replicas kept hitting the same bug: a form submit (POST, primary) redirects to a page (GET) that reads from a replica that hasn't caught up.
The fix
Rails 6 added automatic role switching: GET and HEAD requests use replicas, unless the session wrote recently. Inside the delay window (2 seconds by default) they use the primary. The guides say plainly that it doesn't promise anything to other users, and that the delay should be tuned to your setup.
The lesson
A time window is easy and catches the common case. It is still a guess, so tune it to your real lag and watch for spikes.
Source: Rails Guides: Multiple Databases with Active Record(opens in a new tab)
Case file #04

Microsoft Azure Cosmos DB

Cloud database · ongoing

tokens, built into the protocol

The problem
Cosmos DB keeps several replicas of every database, often across regions. Strong consistency everywhere costs latency and throughput; plain eventual consistency confuses the user who just wrote.
The fix
Cosmos DB offers five consistency levels, and Session is the default. After a write, the client gets a session token; reads that send it are served by a replica at least that up to date. Clients outside the session may see older data.
The lesson
Read-your-writes is useful enough that a major cloud database made it the default. It's the version-token fix, done by the database for you.
Source: Microsoft Learn: Consistency levels in Azure Cosmos DB(opens in a new tab)

The 30-second interview answer

If someone asks you this exact wallet question, this order covers it:

  1. Name it. Replication lag breaks read-your-writes, a per-user guarantee. You don't need global strong consistency.
  2. Skip the read. Return the new balance from the write and show it straight away.
  3. Route by owner. The user's own balance and transactions read from the primary; shared data reads from replicas.
  4. Scale with tokens. Store the commit's LSN or GTID per user; read only from replicas that have replayed past it; otherwise wait briefly or use the primary.
  5. Trade-offs. A time window (like Rails) is simpler but fails when lag spikes. remote_apply works but slows every write and can block writes.
  6. Operate it. Monitor lag, eject lagging replicas, keep users on one replica, test with a delayed replica, and never approve a debit from a replica.

Learn next and sources

  • Next ideas: monotonic reads and causal consistency; linearizability vs serializability; quorum reads in Dynamo-style databases (R + W greater than N); what async failover can lose.
  • The best long read on this: chapter 5, "Replication", of Designing Data-Intensive Applications by Martin Kleppmann, which has a section on reading your own writes.
  1. D. B. Terry, A. J. Demers, K. Petersen, M. J. Spreitzer, M. M. Theimer and B. B. Welch, "Session Guarantees for Weakly Consistent Replicated Data", PDIS 1994.
  2. R. Nishtala et al., "Scaling Memcache at Facebook" (opens in a new tab), NSDI 2013.
  3. GitHub, "Mitigating replication lag and reducing read load with freno" (opens in a new tab), 2017.
  4. Rails Guides, "Multiple Databases with Active Record" (opens in a new tab).
  5. PostgreSQL docs: synchronous_commit (opens in a new tab), replication settings (opens in a new tab), recovery control functions (opens in a new tab).
  6. MySQL docs: GTID functions (opens in a new tab), Group Replication variables (opens in a new tab).
  7. MongoDB docs, "Causal Consistency and Read and Write Concerns" (opens in a new tab).
  8. AWS docs, "DynamoDB read consistency" (opens in a new tab).
  9. Microsoft Learn, "Consistency levels in Azure Cosmos DB" (opens in a new tab).