- #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 ₹100answered 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)
- 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
Primary
Replicas (read-only copies)
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.
Your app
phone + server
Primary
₹100 · LSN 42
Replica 2
₹0 · LSN 41
- 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 guarantee | Plain meaning | How it breaks in a wallet |
|---|---|---|
| Read your writes | You always see your own changes. | Add ₹100, refresh, see ₹0. |
| Monotonic reads | Time never goes backwards for you. | Refresh shows ₹100, refresh again (different replica) shows ₹0. |
| Monotonic writes | Your writes apply in the order you made them. | 'Add ₹100' then 'pay ₹50' applied in reverse, so the payment is declined. |
| Writes follow reads | A 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:
| Eventual | Read-your-writes | Strong (linearizable) | |
|---|---|---|---|
| Promise | Copies agree… someday | You see your own writes right away | Everyone sees every write right away, in one order |
| Who sees your ₹100 at once? | Nobody is promised | You | Everyone |
| Your friend, 1 s later | Might see ₹0 | Might see ₹0 | Sees ₹100 |
| Cost | Cheapest | Cheap: only your reads need care | Every read or write pays for coordination |
| Good for | Like counts, view counts, feeds | Profiles, settings, your own orders and balance | Balances used to approve a payment, unique usernames, stock levels |
Try it: break it, then fix it
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
- –
- Tap “Add + refresh” to reproduce the bug.
Routing strategies in this simulator:
- Any node: Reads go to any of the three nodes at random. This is the bug from the story.
- Always primary: All of this user's reads go to the primary. Always fresh, but the replicas sit idle and the primary does every read.
- Primary after a write: For a few seconds after you write, your reads go to the primary; after that, any node. Fresh only if the window is longer than the lag.
- Version token: The write hands back its log position (LSN). A read only goes to a replica that has reached it, else to the primary.
- Sync replication: The primary waits until every replica has applied the write before saying OK. Any node is fresh, but each write waits for the slowest replica.
Things to try:
- 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.
- 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.
- Version token. Never stale, and reads go back to replicas as soon as one catches up. Check "reads on primary".
- 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.
-- 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.
The user's own data
Everyone else's / shared data
// 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.
- 01
User writes
commit on primary
- 02
Remember when
wrote:user = now, expires in 2 s
- 03
Next read
flag still there?
- 04
Yes → primary
no → any replica
// 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.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::SessionFix 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.
- 01
Write
commit on the primary
- 02
Read its position
LSN 0/3A0 or a GTID
- 03
Save the token
per user, in Redis
- 04
Pick a replica
replayed ≥ token?
- 05
None ready?
wait a little or use the primary
PostgreSQL, with node-postgres:
// 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:
-- 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:
// 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
operationTimeandclusterTime, and calladvanceOperationTimeandadvanceClusterTimeon 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.
# Wait for both standbys to replay the change before COMMIT returns.synchronous_standby_names = 'FIRST 2 (replica1, replica2)'synchronous_commit = remote_apply| synchronous_commit | COMMIT returns after… | Read-your-writes on the replica? |
|---|---|---|
| off / local | the primary alone has it | No |
| remote_write | the standby received it (not yet on its disk) | No |
| on (with sync standbys) | the standby saved it to disk | No: saved is not yet replayed |
| remote_apply | the standby replayed it, so queries there can see it | Yes |
- 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_consistencysetting (BEFOREorAFTER) 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 write | Own data on primary | Primary after a write | Version token | Sync replication | |
|---|---|---|---|---|---|
| Always fresh for the user? | Only on that screen | Yes | Only while lag stays under the window | Yes | Yes |
| Extra load on the primary | None | High: every own-data read | Medium: reads just after writes | Low: only while replicas are behind | None |
| Write latency | Unchanged | Unchanged | Unchanged | One tiny extra query | Plus the slowest replica's replay |
| Works across devices? | No | Yes | If stored per user on the server | If stored per user on the server | Yes |
| Effort | Tiny | Small | Small (built into Rails) | Medium | A config line, plus ops work |
| Breaks when | the user reloads or opens another screen | the primary is overloaded | lag spikes past the window | the 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 STATUSGraph 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_lagA 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
| Database | Reads by default | Read-your-writes option |
|---|---|---|
| PostgreSQL | Async streaming replicas; your app or proxy picks the server | synchronous_commit = remote_apply, or an LSN token checked with pg_last_wal_replay_lsn() |
| MySQL | Async binlog replicas | GTID token with WAIT_FOR_EXECUTED_GTID_SET; Group Replication group_replication_consistency |
| MongoDB | Reads go to the primary unless you set a readPreference | Causally consistent sessions, with majority read and write concern |
| Amazon DynamoDB | Eventually consistent reads | ConsistentRead: true on the table (not on global secondary indexes) |
| Azure Cosmos DB | Session consistency is the default level | A session token per client, sent with each read |
| Ruby on Rails | Replicas for GET and HEAD with automatic role switching | Primary within the delay window after a write (2 s default) |
In the wild: case files
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.
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.
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.
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.
The 30-second interview answer
If someone asks you this exact wallet question, this order covers it:
- Name it. Replication lag breaks read-your-writes, a per-user guarantee. You don't need global strong consistency.
- Skip the read. Return the new balance from the write and show it straight away.
- Route by owner. The user's own balance and transactions read from the primary; shared data reads from replicas.
- 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.
- Trade-offs. A time window (like Rails) is simpler but fails when lag spikes.
remote_applyworks but slows every write and can block writes. - 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.
- 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.
- R. Nishtala et al., "Scaling Memcache at Facebook" (opens in a new tab), NSDI 2013.
- GitHub, "Mitigating replication lag and reducing read load with freno" (opens in a new tab), 2017.
- Rails Guides, "Multiple Databases with Active Record" (opens in a new tab).
- PostgreSQL docs: synchronous_commit (opens in a new tab), replication settings (opens in a new tab), recovery control functions (opens in a new tab).
- MySQL docs: GTID functions (opens in a new tab), Group Replication variables (opens in a new tab).
- MongoDB docs, "Causal Consistency and Read and Write Concerns" (opens in a new tab).
- AWS docs, "DynamoDB read consistency" (opens in a new tab).
- Microsoft Learn, "Consistency levels in Azure Cosmos DB" (opens in a new tab).