Blog
What is stale data, and how to control it
Stale data no longer matches its source when it’s read. See where it comes from in replicas, caches, and change data capture, and how to measure and control it.
Blog
Stale data no longer matches its source when it’s read. See where it comes from in replicas, caches, and change data capture, and how to measure and control it.
Stale data is data that no longer reflects the current state of the original data source when it is read. It was correct when it was written, but a user, a model, or a fraud check reads it after the source has changed.
The most typical case is a read that follows a successful write.
A customer saves a change, refreshes, and sees the old value.
A risk model scores a transaction against a balance that is several seconds behind.
A recommendation engine personalizes a page from behavior the customer has already moved past.
In each case, the decision ran against a copy of the data that hadn't caught up with the source.
Production systems can keep many such copies. One write fans out to read replicas, caches, CDN edges, feature stores, and search indexes, and each copy catches up on its own schedule.
Stale reads come from caches that kept an old value, replicas that haven't applied a recent write, and consistency settings that allow an older version to be returned. Controlling staleness means deciding how old each kind of read is allowed to be, then choosing the invalidation, replication, and read consistency that keep reads inside that limit. Balances, inventory, and permissions usually need strongly consistent reads; feeds, counters, and analytics can usually tolerate eventual ones.
Staleness is the time between the copy someone read and the current value upstream. The record itself is intact, and that's the difference between stale data and bad data. Bad data was wrong from the start: a mistyped address, a duplicate record, or a malformed field. Stale data passed every check when it entered the system and became wrong because the world changed. A bad address needs a correction, while a stale inventory count needs a faster path from the warehouse to the read.
Data freshness is how current a copy is relative to its source, and the acceptable level depends on who reads it and why. A marketing team can run a weekly dashboard from data that is a day old. A fraud model that scores card transactions needs the account's recent activity within seconds. A ten-year-old signed contract is still the authoritative record of the agreement, while a product availability feed that is ten minutes old may already be stale if customers are buying against live stock. Each read needs the tolerance its decision allows.
Two other properties affect whether a read leads to the right outcome.
Durability asks whether an acknowledged write survives a failure, which matters during failover.
Atomicity asks whether related changes succeed or fail together, which matters when a read leads to a write, as in a seat reservation. A fresh read still leads to a wrong outcome if either of those fails.
This is different from over-retained. Security and governance teams also use "stale data" for files, exports, and accounts that nobody uses anymore but that remain stored, which adds security vulnerabilities and retention risk.
A write lands on the primary database and may then flow to read replicas, an application cache, CDN edges, a feature store, and a search or vector index. Each copy catches up on its own schedule and falls behind for different reasons. One case involves no copy at all: during a network partition, a node that has been replaced as primary can continue to serve reads until the cluster removes it, so even a primary can return an outdated value.
Layer | How it falls behind | What bounds the staleness | Metric to watch |
|---|---|---|---|
Read replica | Applies the write after the primary has already committed it | Replication lag |
|
Application cache | Keeps the value it was given until a TTL expires or an invalidation arrives | TTL, invalidation delay | Key age, invalidation lag |
CDN edge | Serves cached responses until a purge propagates | Purge propagation time | Cache age headers |
CDC pipeline or stream processor | Connector and consumer lag between the commit and the downstream write | End-to-end pipeline lag | Consumer lag, connector lag |
Feature store | Recomputes features on a batch or stream cadence | Refresh interval plus event and processing delay | Feature age at serving time |
Search or vector index | Re-indexes or re-embeds documents on a schedule | Re-indexing cadence | Index age, pending updates |
The same record can be current on the primary, two seconds behind on a replica, ten minutes behind in a cache, and a week behind in a vector index.
Reads that combine several layers add a second problem. A service that joins a customer record from a replica with a balance from a cache and a risk score from a feature store is combining data of three different ages. Each copy can be within its own tolerance, while the combined result describes a situation that never existed at any one time. Jobs that join queues updating on different schedules, and services that share real-time state through their own local copies, also mismatch. When values have to agree with each other, read them from one source inside one transaction.
A user usually sees old data after a successful write because the write went to the primary and the next read went to a replica that hadn't applied it yet. The primary committed, returned success, and shipped the change to its replicas asynchronously. The application then routed the follow-up read to a replica, which answered from its state before the write. A cache that still holds the pre-write value produces the same symptom.
Replicas receive changes as a log stream, such as the write-ahead log in PostgreSQL or the binary log in MySQL, and apply them after the primary has acknowledged the commit. Google Cloud's replication lag guide for Cloud SQL splits the delay into three parts[1]:
The primary can be slow to send
The replica can be slow to receive
The replica can be slow to apply
Amazon RDS reports the delay as the CloudWatch ReplicaLag metric, which for MySQL and MariaDB comes from Seconds_Behind_Source[2] (Seconds_Behind_Master before MySQL 8.0.22). A read that lands on the replica inside that window returns the older record: a create followed by a find returns nothing, and a save followed by a refresh returns the previous value.
Three fixes and what each one costs:
Fix | How it works | Cost |
|---|---|---|
Primary consistency window | Route a user's reads to the primary for a few seconds after any write | Simple to build; moves read load to the primary for every recent write |
Log sequence number (LSN) or version token | Give the client the write's position in the write-ahead log, or the record's version; a replica serves the read only after it has applied that position | Precise, and only the reads that need it wait; the token travels with the client |
Synchronous replication | The primary waits for the replica to apply the change before acknowledging the commit | Removes the window for every read; adds a replica round trip to every write |
PostgreSQL implements the third option as synchronous_commit = remote_apply. The commit waits until the standby has applied the transaction and made it visible to queries, which causes larger commit delays[3] than the other settings.
Visibility is the factor that affects stale reads. Durability on the standby is a separate setting: synchronous_commit = on waits for the standby to flush the commit to disk but not to apply it. Because remote_apply adds latency to every write to protect a subset of reads, it’s best for data where a stale read costs more than a slower commit.
In PostgreSQL, the token approach looks like this in pseudocode. The token is a minimum replay position captured after the commit, not the transaction's exact commit position. LSNs aren't plain integers, and a replica that hasn't replayed anything returns NULL, so the code compares positions with pg_wal_lsn_diff() treats NULL as behind, and falls back to the primary after a short wait.
# pseudocode: serve a read from a replica only once it has replayed past this user's write
# after the write commits
primary.execute(update_sql)
session['min_lsn'] = primary.query_one("SELECT pg_current_wal_lsn()") # at or after the commit
def caught_up(replica, min_lsn):
replayed = replica.query_one("SELECT pg_last_wal_replay_lsn()")
if replayed is None: # nothing replayed yet: treat as behind
return False
return replica.query_one("SELECT pg_wal_lsn_diff(%s, %s) <= 0",
[min_lsn, replayed])
# on the next read
replica = pick_replica()
deadline = now() + 0.05 # wait up to 50 ms for the replica
while not caught_up(replica, session['min_lsn']):
if now() > deadline:
replica = primary # stop waiting; read from the primary
break
sleep(0.005)
row = replica.execute(select_sql)During a sustained lag spike, every read that follows a recent write moves to the primary at once, so the primary takes on extra read traffic while it is already behind on shipping changes. Proxies that remove lagging replicas from rotation make this worse: As each replica crosses the lag threshold, it leaves the pool, until the primary carries every read. With client timeouts and retries in the mix, the overload persists after the original spike has passed.
That is called a metastable failure: a degraded state the system stays in, even after the trigger is gone. Version tokens degrade more gracefully, because only reads that depend on a write newer than the replica's position fall back to the primary.
Session-scoped fixes stop users from missing their own writes. They don't help a user who reads someone else's write. If one person comments on a post and another person refreshes it, the second person's session has no token for the first person's write, so the comment can be missing for the length of the lag. For many products, that delay is acceptable. Where it isn't, the options are strongly consistent reads for that data or synchronous replication.
The same race happens between services. A service writes a row and publishes an event; another service receives the event within milliseconds and queries a replica, and the replica hasn't applied the row yet, so the consumer reports "not found" for a record that exists. Retrying with back-off turns the problem into added latency and occasional failures. Carrying the write's version in the event, and having the consumer read from the primary or wait until a replica reaches that version, fixes it the same way the token does for users.
A cache serves stale data because it keeps the value it was last given, and that value doesn’t get updated when the source changes. In cache-aside, or lazy loading, the most common type of caching staleness problem, the application checks the cache, misses, reads the database, and writes the result into the cache. From then on, the cached copy and the database are two independent records of the same fact, and the application is responsible for keeping them aligned.
Reader A misses the cache and reads the old value from the database. Before Reader A writes that value into the cache, Writer B updates the database and deletes the cache key. Reader A then completes its write to the cache, so the cache holds the old value, causing the invalidation. The outdated value stays in the cache until the key is written again or expires.
A cache miss carries a second risk. If the miss falls through to a lagging replica instead of the primary, the application caches the replica's older value, and the cache ends up staler than the replica it read from.
The usual answer is to delete the key after the database commit.
Updating the cache on every write lets two writers race and leave the cache holding whichever value finished last, which may not be the one that committed last.
Deleting before the commit opens a time period where another reader repopulates the key with the old value.
Deleting after the commit narrows the window to the time between the commit and the delete, but the race above can still occur. A lease or a version check closes it.
def update_customer(cid, fields):
db.update('customers', cid, fields) # commit first
cache.delete(f'customer:{cid}') # then invalidateThe difference between cache-aside, write-through, and write-behind
Strategy | How the cache is filled | Staleness risk | Cost |
|---|---|---|---|
Cache-aside (lazy loading) | On a read miss, from the database | Cache holds old values until invalidated or expired | Cheapest writes; invalidation logic is the application's responsibility |
Write-through | On every write, alongside the database | Short window after each write, but a failure between the two writes leaves them inconsistent unless both are coordinated | Every write updates two stores; the cache fills with data that may never be read |
Write-behind | On every write, with the database updated later | The database can be behind the cache; data is at risk if the cache fails before flushing | Fastest writes; possible data loss |
AWS's ElastiCache caching strategies[4] describe the tradeoff: lazy loading allows stale data, and write-through shortens the window in which cached data is out of date. But write-through still writes to two systems, so it has the same exposure as any dual write.
Write-through also leaves a new or replaced cache node empty until each key is written again.
A TTL limits how long a cache entry exists, but it doesn't prevent the entry from being stale. If a key has a ten-minute TTL and the race above puts an old value into the cache, users read that value for up to ten minutes with no alert. Choose the TTL from the staleness the data can tolerate, and rely on invalidation to keep entries current.
The fix for the cache-aside race is to make the cache reject a write based on an outdated read. Facebook's memcache uses leases: a miss gives the reader a lease token, a delete invalidates outstanding leases for that key, and a write carrying an invalidated lease is rejected. Because a lease for a given key is issued at most once every ten seconds, leases also prevent a “thundering herd,” where every reader misses at once and queries the database.
Facebook’s 2013 memcache paper[5] reported that cache misses on a set of keys prone to thundering herds produced a peak database query rate of 17K queries per second without leases and 1.3K with them. The figures come from one deployment more than a decade ago, but the mechanism applies to any look-aside cache. Versioned writes, which update the cache only if its version is older than the one the reader saw, provide the same protection without a central lease service. The same race appears in other forms: out-of-order invalidation messages, near caches (small caches inside each application server), and derived aggregates that invalidation doesn’t reach.
The most reliable way to keep a second store current is to drive it from the database's change log rather than from a second write in the application. The second store might be a cache, a key-value store that serves low-latency reads, or a search index. In each case, two stores need to see the same change.
When an application writes to the database and then to a second store, the two writes aren't atomic. The second write can fail, time out, or land after a newer write from another thread, which leaves the second store stale with no error. Retries handle failures but not ordering, and application-level transactions can't span two systems that don't share a transaction log.
Change data capture (CDC) reads committed changes from the database's log, such as the write-ahead log in PostgreSQL or the binary log in MySQL, and streams them as row-level events. Because it works from committed changes, it avoids the dual-write problem, and it preserves source order within the scope the connector supports, usually per table, key, or partition. Delivery is at least once by default: because the same event can be delivered more than once[6] after a failure or restart, consumer services need to be idempotent unless exactly-once delivery is configured through Kafka Connect. Deleting a cache key twice is harmless; applying the same balance change twice isn't. Ordering and recovery behavior, including the handoff from an initial snapshot to streaming, depend on the database and connector configuration.
A CDC consumer can delete or refresh cache keys as rows change, replicate a managed relational database into a key-value store, or update a search index:
# CDC consumer that invalidates cache keys as rows change
for change in cdc_stream('public.customers'):
cache.delete(f"customer:{change.key}") # idempotent: safe to repeatWhen the application needs to publish a business event rather than a raw row change, a transactional outbox closes the dual-write gap from the other side. The application writes the data change and an event row into an outbox table in the same database transaction, so either both commit, or neither does. A separate relay reads the outbox, often through CDC, and publishes the events, and the second store is updated from them. Because the event and the data change share a transaction, the change can't commit without its event. The outbox doesn't make delivery exactly once: a relay can publish an event twice after a restart, so consumer services still need to be idempotent.
BEGIN;
UPDATE accounts SET balance = balance - 40 WHERE id = 7;
INSERT INTO outbox (aggregate, event, payload)
VALUES ('account', 'BalanceChanged', '{"id":7,"delta":-40}');
COMMIT;
-- a relay reads outbox rows (or their CDC events) and publishes themBetween the commit and the downstream write, there is connector latency, consumer backlog, and the time the downstream store takes to apply the change. Under a burst of writes, the consumer service falls behind and the second store drifts like a replica, so a CDC pipeline needs its own lag metric and alert. If the connector falls behind past the database's WAL or binlog retention, the log it needs is gone, and the downstream store has to be rebuilt from a fresh snapshot. Set log retention to cover the longest connector outage you plan to survive, and alert on connector lag well before it reaches that limit.
A distributed database's read consistency setting decides whether a read waits for the latest committed value or answers from whichever replica responds first. Every database ships with a default, and several widely used defaults, including Aerospike's, favor availability and cost over freshness. That default works for data that tolerates staleness.
"Strong consistency" can refer to more than one thing, so check which guarantee a database's documentation describes.
A linearizable read returns a value that reflects every write completed before the read began.
A session-consistent read is narrower: A client always reads its own writes and never sees a record's versions go backward within its session, but it isn't promised the latest write from another client.
An eventually consistent read may return a value that doesn't yet include recent writes; replicas converge if writes stop.
Stronger guarantees cost more when the database has to coordinate to provide them. A linearizable read has to confirm that the answering node is still the current primary for the record, which typically takes a round trip to other replicas. A Cassandra QUORUM read waits for more replicas to respond, and a strongly consistent DynamoDB read uses twice the read capacity of an eventually consistent one.
Database | Default read consistency | How to get a stronger read | Cost of a stronger read |
|---|---|---|---|
AP mode by default; session-consistent reads in namespaces configured for strong consistency (SC) | Request linearizable reads per command in an SC namespace | Session reads cost about the same as AP reads; linearizable reads add a confirmation round with the replicas | |
Writer reads are current; reader replicas are eventually consistent, with lag usually under 100 ms | Read from the writer endpoint | No separate pricing; the cost is load on the writer | |
Cassandra[8] | Set per operation by the client; ONE reads one replica | QUORUM or LOCAL_QUORUM, which make reads and writes each wait for a majority of replicas, so reads usually reach the latest successful write, but that falls short of linearizability; lightweight transactions (SERIAL) for operations that need stronger coordination | More replicas must respond, so latency rises |
Cosmos DB[9] | Session consistency | Bounded staleness, which caps lag at a configured number of versions or time interval, or Strong | Session and weaker reads use one replica; strong and bounded-staleness reads contact more replicas |
DynamoDB[10] | Eventually consistent | Set ConsistentRead = true on tables and local secondary indexes | Strongly consistent reads cost twice as much; global secondary indexes and streams are always eventually consistent |
MongoDB[11] | Read concern local; read preference primary | Read concern majority or linearizable, with write concern majority. Read preference chooses which member answers; read concern sets what the answer guarantees | Linearizable reads wait for a majority round trip |
Spanner[12] | Strong | Strong is the default; bounded or exact staleness reads are opt-in | Any up-to-date replica can serve a strong read, though it may need a round trip to the leader. Rows within one strong read are mutually consistent; two separate strong reads differ if writes land between them |
Three entries stand out.
DynamoDB's eventually consistent reads are the default and cost half as much, so an application that never sets ConsistentRead uses them.
Cassandra leaves the consistency level to each request, and a read at ONE can come from a replica that never received the write.
Spanner defaults to strong reads and makes staleness opt-in.
Eventual consistency has no fixed bound. Under light write load, replication lag on a well-provisioned replica can be tens of milliseconds. During a batch job, a large transaction, or a schema change that holds locks, the same replica can fall seconds or minutes behind. Aurora replica lag is usually much less than 100 ms and varies with the rate of change[7], and increases during heavy writes.
Google Cloud's MySQL guide lists long-running transactions, missing primary keys, and DDL locks among the causes of replica lag[13].
Design for the 99th-percentile lag during the heaviest write period.
Bounded-staleness reads are between eventual and strong.
Spanner's bounded-staleness reads let the database choose the newest timestamp within the bound that the nearest replica can serve, trading a known amount of age for lower latency.
Cosmos DB's bounded staleness level caps lag by a number of versions or a time interval.
MongoDB's maxStalenessSeconds read preference excludes secondaries that are too far behind, and some proxies remove a replica from rotation when its lag passes a threshold.
These controls turn an unknown staleness into a declared one.
Reading from a nearby region trades staleness for latency, and failover causes both lost writes and stale reads. Both tradeoffs need to be decided per data type.
A replica in the user's region answers in a few milliseconds instead of the hundred or more it takes to cross an ocean. Keeping that replica current means shipping every write from the region that accepted it. Most cross-region replication is asynchronous, because waiting for an inter-region round trip on every commit adds the same latency the local replica was meant to avoid. An application reading in a destination region sees the shipping delay as staleness.
Synchronous replication across sites removes that staleness and adds the inter-site round trip to every write. Letting several regions accept writes for the same record asynchronously adds conflict resolution, because two regions can change the same record before either receives the other's change. Synchronous replication avoids those conflicts instead of resolving them afterward. A product catalog can be read locally, but a balance check belongs in the writing region, behind a strongly consistent read, or in a cluster that replicates synchronously across sites. Even with synchronous replication, read routing and read mode still determine whether a given read can be stale.
Failover causes two problems. With asynchronous replication, a write that the old primary acknowledged but hadn't yet shipped is missing from the new primary. That's a durability failure, and it looks like staleness because the older value becomes authoritative again, so clients that already saw the newer value now read an earlier one. Separately, replicas that were behind keep serving pre-failover state until they resync, and caches populated from the old primary hold values the new primary never had. Those are stale reads of data that did survive.
Synchronous replication within the cluster addresses the first problem, because a write isn't acknowledged until the replicas have it. It doesn't address the second by itself. When you evaluate a database for high availability, ask two questions:
Are acknowledged writes replicated before the acknowledgment?
What can a client read while the cluster recovers?
A cache node that restarts either comes back empty, which moves load onto the database, or comes back with its previous contents, which are now as old as the outage. A cache without durable storage doesn’t keep a record of which entries changed during the outage. Shortening TTLs after such an incident trades more database load for a tighter bound on how long a recovered cache serves old data. Deciding in advance what the cache does on restart, and treating it as a performance layer rather than a system of record, avoids that scramble. A system that needs both low-latency reads and durable storage needs the durability to come from a store that survives a restart with its data intact.
Stale reads don't produce errors, so start from the system. A stale read is the system working as configured, so the question is which configured delay the read fell into.
Symptom | Most likely cause | How to confirm it |
|---|---|---|
A user saves a change, refreshes, and sees the old value | Replica lag | Compare the replica's last-applied log position with the position of the user's write; check |
A value comes back after it was deleted or changed, and stays wrong until the TTL runs out | Cache-aside race (stale set) | Check whether a read miss and a write overlapped on that key; look for cache writes landing after the invalidation |
Some users see the new version and others see the old one at the same time | Reads load-balanced across replicas with different lag; less often, a CDN edge or a near cache | Compare lag per replica at the time of the reads; check cache age headers; check whether the invalidation reached every application server |
Reads are fine most of the day and stale during batch jobs or deploys | Apply-side replica lag | Watch replica lag and network lag separately; if network lag is low and replica lag is high, the replica can't apply changes fast enough |
A record exists on the primary, but a consumer service reports it as not found | Event delivered before replication caught up | Compare the event timestamp with the replica's applied position when the consumer service read it |
A dashboard shows outdated numbers with no alert | A pipeline stopped, or a table went stale | Check the table's freshness: the time since the last row was inserted or updated |
A model's predictions degrade with no change to the model | Stale features at serving time | Compare feature timestamps at inference with the source event timestamps |
The metrics in the table isolate causes because they measure different delays. Cloud SQL reports network_lag, the time for a change to reach the replica, separately from replica_lag, the time until the replica applies it, and the time period between the two shows whether the network or the replica is the bottleneck[1]. For dataset-level staleness, the simplest check is each table's freshness, with an alert when the time since its most recent insert or update crosses a threshold.
Staleness becomes manageable when it's measured per layer and budgeted across the whole read path, the same way latency is. Dataset freshness, or the time since a table last updated, and replication lag, or how far a replica is behind, each measure one layer. Neither describes what a user received, because one read can pass through several layers.
Staleness age is the time between the commit of the first later version that superseded the returned version and the read. A read that returns the latest committed version has a staleness age of zero, regardless of how long ago that version was written. Measuring staleness age requires recording version and commit-time history, which an ordinary read doesn't return.
Stale-read rate is the share of reads that returned a version older than the latest committed one at read time.
Convergence time is how long after a write every copy in the path reflects it.
Staleness age needs a high-percentile target, because one request rarely makes one read. If reads are independent, the chance that at least one of a request’s 50 reads lands beyond the 99th percentile is 1 − 0.99^50, about 39.5%. For the 99.9th percentile, it is 1 − 0.999^50, about 4.9%. Dean and Barroso make the same point in “The Tail at Scale”[14]: when a request waits on 100 servers that each exceed one second 1% of the time, 63% of requests take longer than one second. Reads that share nodes, network paths, or hot partitions are correlated, which can make the real numbers worse. A target such as “99.9% of reads have a staleness age under 500 ms” holds up under that fan-out.
A staleness budget assigns an acceptable age to each source a read depends on.
Sources in series add: a cache filled from a replica is as stale as the replica plus its own delay.
Sources fed in parallel from the same log don't add, because the read is only as stale as its stalest source.
The example table shows a budget for a product-availability read that must be under two seconds old, where a replica and a CDC-fed cache both follow the primary's log.
Source or constraint | Budget at p99.9 | How it combines | What enforces it |
|---|---|---|---|
Replica (primary log to replica apply) | 500 ms | In parallel with the cache, so the larger of the two sets the age | Replica lag alert; version-token fallback to the primary |
Cache fed by CDC (primary log to cache update) | 1 s | In parallel with the replica | CDC consumer lag alert |
Cache TTL | Worst-case bound only | Not counted toward the normal budget | TTL set to the tolerance, with invalidation doing the work |
Spread between values assembled into one response | 1 s or less | A separate limit on age differences, not added to the age | A version or timestamp carried with each value, or the values read inside one transaction |
Read age | 1 s or less, inside the 2 s tolerance | Largest of the source ages | Measured end to end as staleness age |
Measure each source's age against the commit time at the primary rather than adding up the lag figures each layer reports; that way no delay is counted twice or missed. The spread row handles the mismatch problem: Values can each be within budget and still describe a state that never existed, so their spread needs its own limit.
Dataset monitors track how long it has been since each table last updated, often against data SLAs agreed with the teams that consume the data. RDS replica lag metrics[2] and Cloud SQL replication lag metrics[1] cover the replication hop. The budget connects these by setting what each number is allowed to be. Networking research has a related metric[15], Age of Information, defined as the time since the most recently received update was generated. That definition suits sources such as sensors, where every new reading replaces the last. Database records change irregularly, so staleness age measures from when the returned version was superseded instead.
Data can tolerate a stale read when acting on the old value costs less than a fresh read would. That depends on the data and the decision made from it, so classify each type of data the application reads and assign it a tolerance and a read strategy.
Data type | Acceptable staleness | Read strategy |
|---|---|---|
Account balances, payments, ledger entries | None at decision time | Strongly consistent read, plus a transaction or conditional write for any update that depends on it |
Inventory, seat, and ticket availability | Seconds for browsing; none at reservation | Eventual reads for catalog pages; an atomic conditional write or transaction at reservation |
Permissions and access control | None once revoked | Strong read or immediate invalidation; never served from a TTL-only cache |
Prices and promotions | Short, with a hard bound | Cache with invalidation on change plus a short TTL as the bound |
User profile the user is editing | None for their own writes | Read-your-own-writes via version token, primary consistency, or session consistency |
Feeds, likes, counters, comments by others | Seconds | Eventual reads from replicas or cache |
Analytics and reporting | Minutes to a day, by report | Scheduled refresh with a freshness check |
In inventory, fresh reads aren't enough on their own. A ticketing platform selling seats across several venues during an on-sale handles a surge of concurrent requests for the same small set of records. A stale availability read can send several buyers after a seat that's already sold, but fresh reads don't prevent double-booking, either: Two buyers can read the same available seat before either reservation commits. The reservation has to enforce exclusivity itself, through an atomic conditional write or a transaction, rather than a read followed by an unprotected write.
Balances work the same way: A strongly consistent balance read doesn't stop two concurrent withdrawals from spending the same funds unless the read and the update are protected together. An on-sale is also a hot-key problem, because the requests concentrate on a few records and the few nodes that own them, which is when a system is most likely to shed load onto stale copies. If a network partition forces a choice between answering with possibly stale data and refusing to answer, reservation and payment operations should refuse.
Stale permissions are a security problem rather than a convenience problem. Revoked permissions shouldn’t stay in a cache. Permission changes need an invalidation path as reliable as the grant path.
For each row, also decide what happens when fresh data isn't available:
Serve the stale value (fail open)
Refuse (fail closed)
A recommendation widget can fail open, because slightly old recommendations are better than a blank page. A fraud check needs a conservative fallback, such as rules that don't depend on the missing features, because a score computed from stale data looks like a good score. Declining outright is the other extreme and has its own cost, because false declines turn away legitimate customers.
Pay for a fresh read wherever a stale read would cost more. Applying that rule means pricing both sides, and the cost of strong consistency is usually the easier one to measure.
In fraud detection, the model is only as good as the features it scores. If an account's recent transaction count is 30 seconds behind, a burst of attempts looks like one attempt, and a correctly trained model returns the wrong answer because its inputs describe an earlier state. A fraud score also draws on many lookups, such as account history, device, merchant, and recent velocity counts, and each added lookup is another chance to read a stale value or wait on a slow one.
In advertising, a bid placed against a budget or frequency cap that has already been used up spends money on an impression the campaign didn't want.
In pricing, a product shown at last hour's price sells at last hour's price.
In inventory, stale availability lets customers buy items that are out of stock, and the failed fulfillment that follows can cost the customer relationship as well as the sale. A recommendation model fed stale stock data continues to promote items that can't ship.
Customer experience and personalization staleness issues are less obvious. A user who saves a setting and sees it revert loses trust in the product, even though the setting was saved. Recommendations built from behavior that's two sessions old personalize for preferences the customer has moved past. These losses don't trigger alerts, which makes them easy to miss.
Fresh reads cost latency, capacity, or money.
DynamoDB charges twice as much[10] for a strongly consistent read as for an eventually consistent one.
Cosmos DB's strong and bounded-staleness reads contact more replicas than session reads.
Synchronous replication adds a replica round trip to every write, which is why PostgreSQL documents remote_apply as the setting with the largest commit delays[3].
Write-through caching makes every write update two stores.
Pinning reads to the primary after a write uses primary capacity. Where a database separates session reads from linearizable ones, only the linearizable reads pay for coordination.
For a balance check before a payment, a fresh read costs a few milliseconds, while a stale read risks an overdraft or a fraud loss. For a view count on a blog post, a fresh read costs capacity and a stale one costs nothing.
ML and AI systems add more copies to the data path, and each one can give a model information that has since changed. Features are computed from source data on a schedule, documents are embedded into an index on a schedule, and an agent reads from a tool once and keeps the result in its context window. In each case, the model handles the information correctly, but the information is out of date.
A feature store addresses one part of training-serving skew: The feature computed for training has the same definition as the one served at inference. But it doesn't guarantee that the served value is current. If the pipeline that computes "transactions in the last hour" runs every fifteen minutes, a real-time fraud model scores against a count that can be fourteen minutes old, and drift monitoring doesn't flag it, because stale counts are distributed just like fresh ones.
Feature freshness is a per-feature decision, and the refresh interval is only part of it. Event arrival delay, late-arriving events, processing time, and the time the serving store takes to apply an update all add to a feature's age. The read at serving time matters, too: a real-time predictor has to fetch the current value quickly enough to fit inside the request, which favors a store built for low-latency point reads that refreshes from streams rather than batches.
Slow-moving features, such as a customer's tenure or home region, can be hours old without harm. Fast-moving ones, such as recent activity counts, need to be seconds old. Measure feature freshness when the model reads the value, because that's the value the prediction used.
Retrieval-augmented generation adds an index of embedded documents between the source and the model, and the index can go stale in two ways.
A document can change or be superseded while its old embedding stays in the index, so retrieval returns a two-year-old policy as the current one.
An index can also mix documents embedded with different model versions. Vectors from different models may occupy different embedding spaces, so mixing them makes similarity comparisons unreliable unless the models are known to be compatible.
In both cases, the model faithfully repeats an expired source, and relevance ranking scores a superseded document as highly as its replacement. The fixes match the rest of the data path: Delete and re-embed on change, store a version with each document, and treat re-indexing cadence as a freshness budget with a cost.
An agent calls a tool, gets a result such as a file's contents, a database row, or a ticket's status, and the runtime adds that result to the agent's context. If the source then changes, the agent keeps using the old data as current fact. A 2026 preprint on arXiv[16], not yet peer-reviewed, demonstrates this with an agent that reads a free-shipping threshold of 100, misses an edit that lowers it to 50, and answers from the old value. Its proposed fix links each observation to its source, detects changes, and refreshes or flags the stale context before the next model call, which is cache invalidation applied to a context window.
Agents need fresh data because they act on what they read. A data store that agents rely on should return each value with its version and timestamp, so the agent or its runtime detects that an observation is stale and reads it again.
Refreshing context isn't enough for consequential actions, because the state can still change between the agent's last check and its action. An agent that reads that an account has enough funds and then issues a payment can still overdraw it. The payment itself has to enforce the balance condition when it commits, through a conditional write or a transaction, the same protection a seat reservation needs.
An agent answering even a simple question can make many database reads: the customer record, the order history, the open tickets, the current price. Each read is another chance to get a stale copy or wait in the latency tail, so the same tail-latency arithmetic that applies to a web request applies to every answer.
Agent workloads mix reusable context, such as policies, product catalogs, and documentation, with frequently changing operational state, such as balances, order status, and inventory. Reusable context benefits from caching. Frequently changing facts used for consequential decisions need explicit freshness guarantees, and a cache that can't provide them adds more consistency work than the latency it saves. For those reads, a database that serves low-latency point reads with a documented consistency mode removes both the stale copy and the extra hop.
When stale data and latency are both problems, consider whether the architecture needs the extra copies at all. Each copy comes with infrastructure to keep it close to current: invalidation, leases, version tokens, CDC pipelines, lag alerts, and budgets. A database that serves the hot reads itself, at the latency the cache was added to provide, removes the separate copies the application has to synchronize. The database still keeps replicas for durability. What matters is whether it updates them synchronously before acknowledging a write, so that failover doesn’t promote a replica that's missing acknowledged writes.
The cache-plus-replica stack exists because the primary database couldn't serve the read load at acceptable latency. Each copy it adds needs its own invalidation path, failover behavior, monitoring, and place in the staleness budget, and each new write path in the application needs its own invalidation logic.
Three architectures provide fast access to changing data.
A cache in front of the database gives fast reads, along with the consistency problems described earlier.
A stream processor computes derived state as events arrive, which suits aggregates and time windows, but it's another copy with its own consumer lag, and it serves a derived view rather than the record.
A database built for low-latency operational reads serves the record itself, so there's no separate copy to invalidate.
Use a stream processor when the read is a computation over many events, a cache when the source database can't meet the read latency and the data tolerates the cache's staleness, and the database itself when the data can't tolerate staleness and the database meets the latency.
A cache remains the right answer for session data and other short-lived state that doesn't need durability, for data where staleness is harmless and read volume is extreme, and for shielding a system of record that can't be changed. A cache-only tier shouldn't be the system of record for anything the business can't afford to lose on a restart.
Aerospike is designed for data that can't tolerate staleness but still needs fast reads. Its default is the availability-first AP mode. In strong consistency mode, Aerospike replicates each write synchronously within the cluster before acknowledging it, and acknowledged writes aren't lost to cluster partitioning events. Session-consistent reads, the default in that mode, cost about the same as AP reads; linearizable reads add a confirmation round with the replicas.
These guarantees apply to namespaces configured for strong consistency, and they hold within stated limits: with default settings, the cluster stops accepting writes when clock skew between nodes reaches 20 seconds, and data loss becomes possible beyond 27 seconds of clock skew or of process or virtual machine pauses. The commit-to-device setting writes each record to storage before acknowledging it, for durability across node crashes.
Multi-record transactions, added in Aerospike 8, provide strict serializability for records in strong consistency namespaces. An application can read a customer record, a balance, and a risk score at one point in time, or reserve a seat and update an order as one unit.
Across regions, Aerospike offers two models. Cross Datacenter Replication (XDR) ships writes asynchronously between independent clusters, so a read in a destination cluster carries the shipping delay as staleness. Multi-site clustering runs one strongly consistent cluster across sites with synchronous replication, and write latency then depends on the network distance between sites. For ML workloads, Aerospike is available as an online store for the Feast feature store.
Aerospike is a record store for operational workloads, not an analytical engine for large scans, and it doesn't currently offer vector search, so stale embeddings need a different tool. The case for removing a cache tier is fewer copies and fewer hops to keep consistent. Whether a database read beats a cache hit on latency depends on the deployment, network, data model, and workload.
FAQs
The write committed on the primary, and the next read was served by a replica or cache that hadn't applied it yet. Route the user's reads to the primary briefly after a write, pass the write's log position so a replica only serves reads it has caught up to, or use synchronous replication for that data.
Delete the cache key after the database commit, and use leases or versioned writes so an outdated read can't repopulate it. For a second store that needs every change, feed it from change data capture or a transactional outbox, with idempotent consumer services.
Aerospike in its default AP mode, Aurora reader replicas, Cassandra at consistency level ONE, Cosmos DB at consistent-prefix or eventual consistency, DynamoDB by default, MongoDB with a secondary read preference, and Spanner with opt-in bounded or exact staleness all serve reads that can omit a recent write, usually at lower cost or latency. They suit feeds, counters, and analytics; balances, inventory, and permissions need stronger reads.
Replication lag is the delay between a write committing on the primary and a replica applying it. Use ReplicaLag on Amazon RDS, replica_lag and network_lag on Cloud SQL, Seconds_Behind_Source from SHOW REPLICA STATUS on MySQL, or the replay_lag column of pg_stat_replication on a PostgreSQL primary. Track the 99th percentile during peak writes rather than the average. On PostgreSQL, avoid computing lag as now() - pg_last_xact_replay_timestamp() on the replica, because it reports growing lag whenever the primary is idle.
Not for data that can't tolerate staleness. A cache is another copy that needs invalidation and monitoring. If the database serves hot reads within the required latency, reading from it removes that copy. Caches still make sense for short-lived session state, for data where staleness is harmless at very high read volume, and for shielding a system of record you can't change.
Google Cloud Documentation. “Replication lag.” Cloud SQL for PostgreSQL. Google Cloud.
https://docs.cloud.google.com/sql/docs/postgres/replication/replication-lag
Amazon Web Services. “Monitoring read replication.” Amazon Relational Database Service User Guide.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReadRepl.Monitoring.html
PostgreSQL Global Development Group. “19.5. Write Ahead Log.” PostgreSQL 19 Documentation.
https://www.postgresql.org/docs/current/runtime-config-wal.html
Amazon Web Services. “Caching strategies for Memcached.” Amazon ElastiCache User Guide.
https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/Strategies.html
Nishtala, Rajesh, Hans Fugal, Steven Grimm, Marc Kwiatkowski, Herman Lee, Harry C. Li, Ryan McElroy, Mike Paleczny, Daniel Peek, Paul Saab, David Stafford, Tony Tung, and Venkateshwaran Venkataramani. “Scaling Memcache at Facebook.” In 10th USENIX Symposium on Networked Systems Design and Implementation (NSDI 13), 385–398. Lombard, IL: USENIX Association, April 2013.
https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala
Juránek, Vojtěch. “Towards Debezium exactly-once delivery.” Debezium blog. June 22, 2023.
https://debezium.io/blog/2023/06/22/towards-exactly-once-delivery/
Amazon Web Services. “Replication with Amazon Aurora.” Amazon Aurora User Guide.
https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Replication.html
Apache Software Foundation. “Dynamo.” Apache Cassandra Documentation, version 4.0, Architecture.
https://svn.apache.org/repos/asf/cassandra/site/src/doc/4.0/architecture/dynamo.html
Microsoft. “Manage consistency levels in Azure Cosmos DB.” Microsoft Learn. The page metadata lists the author handle markjbrown.
https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-manage-consistency
Amazon Web Services. “DynamoDB read consistency.” Amazon DynamoDB Developer Guide.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html
Kingsbury, Kyle. “MongoDB 4.2.6.” Jepsen, LLC. May 15, 2020.
Google Cloud Documentation. “Replication.” Spanner. Google Cloud.
Google Cloud Documentation. “Replication lag.” Cloud SQL for MySQL. Google Cloud.
https://docs.cloud.google.com/sql/docs/mysql/replication/replication-lag
Dean, Jeffrey, and Luiz André Barroso. “The Tail at Scale.” Communications of the ACM 56, no. 2 (2013): 74–80. Google Research.
Kaul, Sanjit K., Roy D. Yates, and Marco Gruteser. “Status Updates Through Queues.” IEEE, 2012. The PDF doesn’t name the conference. Hosted by Rutgers WINLAB.
https://www.winlab.rutgers.edu/~gruteser/papers/Status%20Updates%20Through%20Queues.pdf
Liu, Yingying, Junzhou Fang, and Chenxiong Qian. “When Agent Context Goes Stale: Incoherence in Volatile Agent Context.” arXiv:2610.05281 [cs.AI, cs.OS]. October 4, 2026.
For a deeper understanding and more insights, explore these additional resources.
See more