Stale Reads: Debugging 'I Wrote It but I Can't See It'
Stale reads have many causes beyond the database. Use consistency models to decide whether a read was allowed, and find the layer that served old data.
- stale reads
- consistency models
- eventual consistency
- root cause analysis
- distributed systems
“I wrote it but I can’t see it” is one of the most common bug reports in any system that stores data, and the database is usually the least likely culprit.
Between the code that writes a value and the code that reads it back there are often half a dozen places that keep a copy: a read replica, an application cache, a CDN, a search index, a materialised view, a message consumer’s local state, a browser tab. Each copy has its own rules about how up to date it must be. Most of those rules were never written down, and the person who chose them has often moved on. When a user sees old data, the investigation is really a question about which copy answered and whether it was allowed to answer that way.
That second half is where a little theory pays for itself. Martin Kleppmann’s Designing Data-Intensive Applications spends several chapters on consistency, transactions and the trouble with distributed systems, and the most practical idea in them for an on-call engineer is this: every read path has a consistency model, stated or not, and a stale read is only a bug if the model said it could not happen. If the model allowed it, the bug is in the code that assumed otherwise. This article turns that idea into an investigation method.
Table of Contents
- Where stale data comes from
- Four things people mean by “consistency”
- Consistency models as a list of what is allowed
- When the message arrives before the data
- Isolation anomalies that look like stale reads
- Your incident timeline has a consistency problem too
- Investigating a stale read
- Choosing guarantees on purpose
- Frequently asked questions
- Ask what the read was allowed to return
- Related reading
Where stale data comes from
Start by listing every layer that could have answered the read. In most systems the list is longer than anyone expects.
| Layer | How it serves old data | Typical staleness | Evidence that it answered |
|---|---|---|---|
| Read replica | Has not yet applied the write | Milliseconds, occasionally minutes | Node or role in query logs; replica lag history |
| Application cache | Entry not invalidated, or invalidated before the write committed | Up to the TTL, or indefinitely if invalidation was missed | Cache hit logs; TTL and invalidation code |
| CDN or HTTP cache | Response cached by URL | Up to max-age, plus revalidation behaviour | Cache headers; edge logs; Age header |
| Search index | Asynchronous indexing pipeline behind | Seconds to minutes; longer if indexing failed | Index document version or timestamp; indexer logs |
| Materialised view or warehouse table | Refreshed on a schedule or by a stream | Up to the refresh interval | Refresh job logs; last refresh time |
| Message consumer state | Built from events it has not yet received | Consumer lag | Consumer offsets; processing logs |
| Client or browser | Local state, offline queue, optimistic UI | Until the next fetch | Client logs, if any |
The table is also a hypothesis list. In a stale-read incident, write down which of these layers sits on the path, and for each one, whether it could have produced exactly the symptom reported. Replicas get blamed first because they are the best known, but caches and asynchronous indexes are at least as common, and several of them have no upper bound on staleness when something goes wrong. The article on replication lag and failover covers the replica case in depth; this one is about the wider question.
Four things people mean by “consistency”
Part of what makes stale-read incidents slow is vocabulary. “The database is consistent” can mean four different things, and people in the same incident channel often mean different ones. Kleppmann points out that the word is overloaded, and separating its meanings is one of the more useful habits you can pick up.
| Meaning | Where it comes from | What it actually promises | What it does not promise |
|---|---|---|---|
| Consistency in ACID | Transactions | The application’s invariants hold, given transactions that preserve them | That a reader sees the latest write |
| Eventual consistency | Replicated systems | If writes stop, replicas converge to the same value | How long that takes, or what readers see meanwhile |
| Linearizability | Distributed systems, the C in CAP | The system behaves as if there were one copy, and a read sees the latest completed write | Anything about multi-object transactions |
| Isolation | Transactions | Concurrent transactions do not see each other’s partial effects, to a stated degree | Recency across replicas |
The ACID “C” is, as Kleppmann notes, really a property of the application: the database can enforce constraints you declare, but whether the data makes sense is up to the transactions you write. Eventual consistency is a convergence promise with no deadline. Linearizability is a recency promise. Isolation is about concurrency between transactions. A system can offer strong isolation and weak recency at the same time, which is exactly what a snapshot-isolated replica does.
During an incident, ask which one people mean. “We use a strongly consistent database” often turns out to mean “the primary is ACID”, while the read that went wrong was served from an eventually consistent index.
Consistency models as a list of what is allowed
A consistency model is easiest to understand as a rule about which results a read may return. The Jepsen consistency reference describes a model as a set of histories that a system is allowed to produce, which is the right mental model for an investigation: you have one observed history, and the question is whether it was legal.
The models you meet most often, from strongest to weakest:
- Linearizability. Every read returns the most recent completed write, as if there were a single copy. Once any reader has seen a new value, nobody can see the old one.
- Causal consistency. Operations that are causally related are seen in the same order by everyone. A reply is never visible before the message it replies to. Unrelated operations may be seen in different orders.
- Session guarantees. Weaker promises scoped to one client: read-your-writes (you see your own updates), monotonic reads (you never see older data after newer), and related guarantees. Werner Vogels’ widely cited essay Eventually Consistent lays these variations out for practitioners.
- Eventual consistency. If no new writes arrive, all copies eventually agree. Nothing is promised about what a reader sees before then.
| Model | A user sees their own update disappear | Two users see different values at the same moment | A reply is visible before its message |
|---|---|---|---|
| Linearizable | Not allowed | Not allowed | Not allowed |
| Causal | Not allowed for causally related reads | Allowed for unrelated writes | Not allowed |
| Read-your-writes plus monotonic reads | Not allowed | Allowed | Allowed |
| Eventual | Allowed | Allowed | Allowed |
Was this read allowed?
This question splits stale-read incidents into two very different kinds.
If the path offered a model under which the observed read was not allowed, then something violated a guarantee: a bug in the database, a misconfiguration, a failover that broke the promise, a cache in front of the store that nobody accounted for. That is a platform investigation.
If the path offered a model under which the read was allowed, then the database did exactly what it promised, and the cause is in the application: code that needed a stronger guarantee than the path provided. That is far more common, and it changes the fix. You do not fix it by tuning the replica. You fix it by routing that read differently, adding a version check, or changing the flow so it does not depend on recency.
Write the answer to this question into the investigation early. It stops a team spending a day looking for a database bug that does not exist.
When the message arrives before the data
One of Kleppmann’s most useful examples involves two communication channels. A user uploads an image; the web server writes it to storage and puts a message on a queue asking a worker to resize it. The queue is faster than storage replication, so the worker reads the image from a replica that does not have it yet, and resizes an old version or finds nothing. Linearizable storage would prevent it. Anything weaker allows it.
The pattern is everywhere once you look for it:
- An event announces “order created”, and the consumer looks the order up in a replica or search index that has not caught up.
- A webhook tells a partner that a document is ready; their fetch hits a CDN that still caches the previous version.
- A job is triggered by a “file uploaded” notification and lists a storage prefix before the listing reflects the new file.
- An event is published inside a transaction, before the commit. The consumer reads the old committed value even from the primary, and if the transaction later rolls back, the event announced something that never happened.
The evidence signature is consistent: “not found” or old-value reads in the consumer, clustered within a short time after the triggering event, and a retry a few seconds later succeeding. If the consumer logs both the event ID and what it read, the case is easy. Often it logs neither.
The robust fix is to send the reader the information it needs to know whether it is reading new enough data: the version, sequence number or replication position of the write, so it can wait or fall back to the source of truth when the copy it reads is older.
# Consumer: refuse to act on data older than the event that triggered it.
def handle_customer_updated(event):
record = customers_replica.get(event["customer_id"])
if record is None or record["version"] < event["version"]:
# The copy we read has not caught up yet. Read the source of truth,
# or requeue with a delay; do not act on the stale value.
record = customers_primary.get(event["customer_id"])
render_invoice(record)
For the publish-before-commit case, the standard fix is a transactional outbox: write the event to a table in the same transaction as the data, and publish from that table after commit.
Isolation anomalies that look like stale reads
Some stale-looking reads have nothing to do with replication. They come from two transactions running at the same time on a single database, under an isolation level weaker than the code assumed.
Defaults matter here. PostgreSQL and SQL Server both default to read committed; MySQL’s InnoDB defaults to repeatable read. Read committed prevents dirty reads and dirty writes, but it allows what Kleppmann calls read skew: a transaction that reads two related rows at different moments can see one before and one after a concurrent transfer between them. His example is a customer who looks at two bank accounts during a transfer and sees a total that is temporarily wrong. In a report or a reconciliation job, the same anomaly produces totals that do not add up and cannot be reproduced afterwards.
| Anomaly | What the symptom looks like | Prevented by |
|---|---|---|
| Read skew | A report’s totals disagree with each other; rerunning it gives correct numbers | Snapshot isolation (repeatable read in many databases) |
| Lost update | One of two concurrent edits silently disappears | Atomic updates, explicit locks, compare-and-set, or serializable isolation |
| Write skew | Two transactions each check a rule, both pass, and together they break it | Serializable isolation, or explicitly locking the rows the check depends on |
| Phantom | A check for “no matching rows” passes, then a concurrent insert creates one | Serializable isolation, or materialising the conflict as a lockable row |
Lost updates
A lost update happens when two read-modify-write cycles interleave. Both read the old value, both compute a new one, and the second write overwrites the first. From the user’s side, their change vanished. It looks exactly like a stale read, and an engineer checking the database will find the other user’s value there.
-- Lost update: two sessions run this concurrently; one increment disappears.
SELECT stock FROM inventory WHERE sku = 'A-100'; -- both read 10
UPDATE inventory SET stock = 9 WHERE sku = 'A-100'; -- both write 9
-- Safe: let the database do the read-modify-write atomically.
UPDATE inventory SET stock = stock - 1
WHERE sku = 'A-100' AND stock > 0;
The discriminating test between a lost update and a stale read is the one from the replication article: is the write in the source of truth now? A stale read leaves the new value on the primary. A lost update leaves someone else’s value there.
Write skew
Write skew is subtler. Kleppmann’s example is an on-call rota: two doctors both check that at least one other doctor is on call, both see that the condition holds, and both take themselves off call. Neither transaction wrote the same row, so nothing conflicted, and the invariant was broken anyway. Incident symptoms include double bookings, overdrafts, and limits exceeded by exactly the amount of two concurrent requests. The fix is serializable isolation or an explicit lock on whatever the check reads.
Your incident timeline has a consistency problem too
There is a second consistency question in every incident, and it is about your evidence rather than your data. The timeline is assembled from logs written by different machines, each stamping events with its own clock.
Kleppmann’s chapter on the trouble with distributed systems is blunt about clocks. Time-of-day clocks drift, are corrected by NTP, and can jump backwards. Two machines rarely agree to better than some milliseconds, and a misconfigured one can be off by much more. Ordering events from different machines by timestamp is only reliable when the gap between them is larger than the clock skew, and you rarely know the skew.
For stale-read incidents this matters directly. The whole question is whether a read happened before or after a write became visible, and the two events were usually logged by different services on different hosts. A 40-millisecond gap in the timestamps does not prove the order if the clocks could disagree by 50.
Building a causal timeline
Prefer evidence that carries order in itself over timestamps:
- Request and correlation IDs that link a write, the event it produced and the read that followed.
- Version numbers or sequence numbers on records and events.
- Replication positions such as log sequence numbers or binlog coordinates.
- Message offsets in a queue or log.
- Happened-before relationships in the code: a consumer cannot read an event before it was published.
Causal timeline for customer 88213 (timestamps from different hosts, skew unknown)
api-7 14:21:03.412 UPDATE customers SET address=... version 17 (req a91f)
api-7 14:21:03.415 publish CustomerUpdated version 17 (req a91f)
api-7 14:21:03.430 COMMIT (req a91f)
invoicer-2 14:21:03.418 consume CustomerUpdated version 17, offset 5512
invoicer-2 14:21:03.421 read customer 88213 -> version 16
Order we can trust: publish(17) -> consume(17) -> read(16), by causality.
Order we infer from code: publish happens before COMMIT in the same request.
Timestamps alone would not settle whether the read preceded the commit.
When you must rely on timestamps, say so in the finding, and state the size of the gap you are relying on.
Investigating a stale read
The method is ordinary hypothesis-driven debugging with a checklist adapted to the problem.
- Is the write in the source of truth now? If not, this is a lost or overwritten write, not a stale read. Investigate conflicts, lost updates, rollbacks and failovers instead.
- List every layer between writer and reader, using the table above. Include caches nobody remembers and indexes fed by background jobs.
- For each layer, write down its guarantee and its staleness at the time. Use the configuration and code at the deployed version, not as they are today.
- Ask whether the read was allowed. If it was, find the code that assumed a stronger guarantee.
- Write rival hypotheses and pick the test that discriminates. A replica, a cache and a publish-before-commit bug make different predictions about when the stale window opens and how long it lasts.
| Hypothesis | Predicts | Ruled out if |
|---|---|---|
| Replica lag | Stale only when read from a replica; window tracks lag | Stale reads also occur on the primary, or when lag was near zero |
| Cache not invalidated | Stale for up to the TTL; cache hit logged | Read was a cache miss, or the window exceeds the TTL with no hit |
| Event published before commit | Stale even when reading the primary; window of milliseconds | Consumer reads happen well after the commit and are still stale |
| Index or view behind | Stale until the next index or refresh run | Index version matches the write at the time of the read |
| Lost update | Source of truth holds a different, concurrent value | Source of truth holds the user’s value |
A worked example: the invoice with the old address
This is an illustrative example; the numbers are invented to show the method.
Symptom. Customers who change their billing address and then immediately upgrade their plan sometimes receive an invoice showing the old address. It happens to roughly one in fifty such customers. The customer record always shows the new address when someone checks.
Hypotheses.
- H1: the invoicing service reads the customer from a read replica that lags behind the primary.
- H2: the account service publishes
CustomerUpdatedbefore the transaction commits, so the invoicer reads the old committed value even from the primary. - H3: the invoicer caches customer records and does not invalidate on update.
Discriminating test. The predictions differ on two axes: where the read goes, and how long the stale window lasts. H3 predicts staleness for up to the cache TTL, ten minutes in the invoicer’s configuration, regardless of when the event arrives. H1 predicts staleness only when the read goes to a replica and the replica is behind. H2 predicts a stale window of a few milliseconds even when reading the primary.
The invoicer’s code and connection settings at the deployed version read from the primary and have no cache for customer records, which rules out both H1 and H3 for this path. Its logs show that every stale invoice was generated within 20 milliseconds of the event’s publish time, while invoices generated a second later were correct.
Confirmation. The account service code publishes the event from inside the transaction block, before COMMIT. Under load, the consumer sometimes receives the event and reads the customer before the commit lands. The causal timeline above, built from the request ID, the event version and the record version the invoicer read, shows publish, consume and a read of version 16 for an event announcing version 17.
Finding and fix. “Events were published before the database transaction committed, so consumers could read the previous committed state. One in fifty invoices generated immediately after an address change used the old address.” The fix is a transactional outbox, plus a version check in the invoicer that refuses to render from a record older than the event. The rejected H1 is worth recording too: the invoicer reads from the primary, so replica lag is not a factor in this path.
Choosing guarantees on purpose
Most stale-read incidents are design decisions nobody knew they had made. A few habits turn them into decisions somebody made on purpose:
- List the read paths that need more than eventual consistency. A user’s own data after they change it; a balance before allowing a withdrawal; a uniqueness check before creating an account. Write next to each the guarantee it needs.
- Pick the cheapest guarantee that is correct for each path. Read-your-writes for a profile page is cheaper than linearizability for everything.
- Carry versions across channels. Any event, message or webhook that triggers a read should include the version of the data it announces.
- Make cache invalidation happen after commit, never before, and log it.
- Name the isolation level in code that depends on it, and test the concurrent case.
When derived copies such as indexes, views and warehouse tables are involved, the question widens from “is this read stale?” to “why do these two datasets disagree?”, which is the subject of derived data out of sync.
Frequently asked questions
What is a stale read?
A stale read is a read that returns a value older than the latest completed write. It can come from a replica that has not applied the write, a cache that was not invalidated, an index or view that has not been refreshed, or a consumer that acted on an event before the data it describes became visible. Whether a stale read is a bug depends on the consistency guarantee the read path was supposed to provide.
Is eventual consistency a bug?
No. Eventual consistency is a deliberate trade: it lets a system stay available and fast while copies converge in the background. It becomes a source of incidents when code that needs a stronger guarantee, such as seeing its own writes or reading the latest value before a decision, runs against an eventually consistent path. The fix is usually to route those specific reads differently, not to make the whole system strongly consistent.
What is the difference between linearizability and serializability?
Linearizability is a recency guarantee about single objects: every read sees the latest completed write, as if there were one copy. Serializability is an isolation guarantee about transactions: concurrent transactions produce a result equivalent to running them one at a time, in some order. A system can be serializable without being linearizable, for example when a snapshot-based replica serves consistent but slightly old data. Kleppmann discusses the difference at length, and it explains many incidents where “the database is serializable” did not prevent stale reads.
How do clock differences affect an incident timeline?
Logs from different machines are stamped by different clocks, which drift and can be corrected abruptly. When two events on different hosts are closer together than the possible clock skew, their timestamps do not prove their order. Use evidence that carries order in itself, such as request IDs, version numbers, replication positions and message offsets, and state explicitly in the finding when a conclusion depends on timestamps alone.
How do I stop a consumer from reading data before it is visible?
Publish events only after the transaction commits, typically with a transactional outbox. Include the version or sequence number of the data in the event. In the consumer, compare the version of what it read with the version in the event, and if the copy is older, read from the source of truth or retry after a delay rather than acting on stale data.
Ask what the read was allowed to return
Stale reads are rarely mysterious once you ask the right first question. Not “why is the database wrong?” but “which copy answered, and what was it allowed to return?” The answer separates platform bugs from application assumptions, points to the code that needs a stronger guarantee, and gives the finding a sentence that the next engineer can act on.
Tools can help assemble that answer. Decim, for instance, reads code and commits through GitHub and application logs through Google Cloud Logging, and builds findings in which each claim links to the log line or code behind it, as described on the evidence page. It does not query your stores directly: when the deciding fact is in a database, it writes a read-only check for your team to run. The Sentry Seer comparison explains how that differs from error-centred tools. The root cause analysis guide has the general method, and stream vs batch processing covers what happens when the copies that disagree are entire datasets.
Related reading
- Replication lag and failover: the replica-specific causes of stale and lost data.
- Derived data out of sync: when an index, cache or warehouse disagrees with the source.
- Stream vs batch processing: why the same events can produce two different answers.
- Hypothesis-driven debugging: the discrimination matrix applied to any incident.
- Root cause analysis guide: from symptom statement to confirmed cause.
Decim investigates incidents in your own system and returns a diagnosis where every claim links to its evidence, with the rejected explanations kept so your team learns which guarantees each path really has. It reads code from GitHub, logs from Google Cloud Logging and tickets from Jira, never runs SQL and never merges a fix. Learn more at decim.dev or see pricing.
Related articles
- Stream vs Batch Processing: Why the Same Events Give Two Different Answers Stream vs batch processing results disagree for predictable reasons: event time, late data, duplicates, joins. How to find which number is wrong, and why. Read the article →
- ETL Job Succeeded but No Data Loaded? 9 Causes and How to Find Yours Your ETL job reports success and the target table is empty or short. Nine causes, the check that confirms each, and how to make success mean something. Read the article →
- Replication Lag and Failover: Root Cause Analysis for Replicated Databases Replication lag, failover and write conflicts produce stale reads, lost writes and duplicate IDs. How to investigate replica incidents from evidence. Read the article →
- Hot Partitions and Partial Failures: Investigating Incidents in Sharded Systems A hot partition hides behind healthy averages. How to investigate skewed keys, rebalancing and partial failures in a sharded system, one slice at a time. Read the article →
Decim investigates pipeline incidents
It reads your code, logs and tickets, works through the pipeline step by step, and confirms the cause with evidence you can check: every claim links to the log line, commit or check behind it. Then it proposes the fix and writes the report.
Request a demo