All notes

Cache Invalidation Starts with How Stale Data May Be

Separate display tolerance, authoritative decisions and the races involved in refreshing cached versions.

English edition, edited for length. Read the complete Chinese original.

The administrator modified the product prices, and the database was updated. However, the page continued to display the old prices. The engineer explained that the cache would expire after five minutes, but the product manager questioned why the settlement price immediately changed. The dispute was not about caching technology, but rather about the ambiguity of “how long the displayed data can be outdated, and which data source should be used for transactions.”

Caching strategies should begin with the tolerance of the data. Article titles may allow for temporary, outdated values, while account balances and purchase eligibility typically require authoritative validation. Uniformly caching all interfaces for the same duration cannot guarantee accuracy and may also waste many opportunities for caching.

Old promises need to be distinguished between presentation and action

Assume that product details can briefly display the old price, but the final price is always calculated by a trusted database. The page should display the final amount before placing an order, without relying on cached values for transaction authorization. Changes in account permissions may require immediate effect and cannot continue to use the old permission list. The same TTL applies to titles, prices, and permissions, ignoring the different consequences. First, record the allowed categories of outdated data and exceptions to operations, which provides a basis for technical choices.

The TTL (Time-To-Live) limit on an object’s lifespan does not necessarily restrict the delay between reading from the source and writing to the cache. If a read is paused for a long time, it will re-obtain its full validity when the cache is repopulated. To guarantee the maximum data age, it is necessary to preserve the source version or the source timestamp, and to reject outdated writes according to the rules. However, simply stating that data cannot be older than five minutes after writing does not prove that the data is only five minutes old. This counterexample highlights the difference between “cache validity” and “data age.”

Even highly accurate data can completely bypass caching, or caching that doesn’t affect authorization-based derived views. A single database query, if not a bottleneck, is often easier to maintain than a complex caching protocol. When measuring performance, first identify which resources should be cached to avoid the default assumption that “everything should be cached.” For data with high accuracy costs, the benefits must be sufficient to justify the additional mechanisms.

A common process involves first reading from the cache. If the data is not found in the cache (a cache miss), it reads from the database. Then, it writes the results to the cache. When writing, it updates the database and removes the cache entry. This seems logical, but if a read request first retrieves the old database value, and a subsequent write request updates and removes the cache entry, the read request then re-populates the cache with the old value, the old data reappears.

Reducing the expiration time can only limit the error window, but cannot eliminate it. The concept of “delayed double deletion” also relies on the assumption of request duration, and cannot cover arbitrarily long pauses. It can be a constrained engineering solution, but should not be described as a strict guarantee of consistency.

First, confirm whether the business can accept this window. If it can, clearly define the maximum acceptable age and transaction validation; if not, you need to rely on authoritative reads, such as versioning, atomic conditions, or bypassing caches, rather than repeatedly stacking deletion steps.

Versioned Keys: Turning Coverage into Choice

Maintain version numbers for different business objects, with the cache key including the version. New version prices are written to new keys, while old requests can only be written to old version keys. When reading the current version, select the new key. If you try to update the old version, it will not overwrite the new content.

However, the current version’s pointer itself also needs to be correctly read and updated. If it is cached for a long time, readers may still choose the old object. The versioning scheme concentrates the problem on small, clear metadata, but it does not automatically eliminate all consistency costs.

product:42:version:17 -> immutable value
product:42:current    -> 17

The versions should come from a reliable sequence of business updates, not from the current time generated randomly by different nodes. Deleting objects also requires a tombstone or version status, otherwise old caches might continue to be treated as valid objects after deletion. Old versions can be cleaned up using longer expiration times, without requiring synchronization to block each update.

The immutable version object solves the problem of overwriting old writes, but the current pointer may still be outdated or inconsistently updated. If writer A produces version 18 and writer B produces version 19, writer A cannot revert the pointer back to 18. Using a reliable version sequence and conditional updates, or reading the current version from an authoritative database. The get followed by set does not guarantee atomic updates across processes, and requires storing the actual comparison update capabilities that are supported. The pointer cache’s expiration also contributes to outdated commitments.

Content deletion is indicated using tombstone or authoritative status. Reading older versions will not revive resources that have been revoked. Permission data should be checked for current authorization before reading, rather than relying on outdated, publicly available information. Older versions retain beneficial rollback and in-flight request functionality, but this does not mean they are permanently accessible. Cleanup is based on references, deadlines, and resource policies, to avoid deleting older pages that still require assets immediately after a new version is released.

The source version cannot be simply replaced by a timestamp because of the potential for causality issues. Differences in clocks between multiple writers, updates and restores of historical data within the same time frame, and other factors can lead to conflicts or inconsistencies. A clear sequence of database updates or a defined business version is easier to prove, but still requires transactional binding. The two dimensions of versioning, content version and caching rules version, represent business changes and key-to-transformation strategies, respectively.

Cache Stampede: A Coordination Problem

After popular keys expire, one thousand requests simultaneously access the database. Even if each query is fast, the resulting competition can quickly exhaust the database connection pool. Options include: merging requests with the same key within a single process, or setting controlled refresh locks. However, coordinating across processes requires consideration of leases, timeouts, and the exit of lock holders.

When you want to allow old values to continue serving while refreshing in the background, it’s a practical option. You should set separate expiration and maximum age limits for the new and old values. If the refresh fails, the old values should not be indefinitely extended. For sensitive data such as inventory or permissions, continuing to serve old values may violate business rules, and should not be enabled solely because it can reduce latency.

Increased random jitter in expiration times can reduce the synchronization peaks caused by many keys failing simultaneously. However, the jitter only distributes the load, it is not a mechanism for ensuring correctness. The metrics should distinguish between cache hits, stale services, refresh failures, and source server reads to avoid masking long-term outdated data with high hit rates.

Requests for merging within the same process can only affect the current instance. Cross-instance locks require leases and recovery mechanisms. After a refresh, the process may write to the old result. It is important to write defensively, either by version or condition, and not to assume that acquiring a lock grants permanent ownership. Lock timeouts do not necessarily mean that the old task has stopped; they share the same boundaries as task queue leases. Network side effects and result writing rely on downstream guarantees and cannot simply involve increasing a single memory variable.

When allowing the use of older services, record both the expiration date of newly created objects and the absolute expiration date of existing objects. Failure to refresh will not automatically reset the age of old objects. If the maximum expiration period is exceeded, a controlled error or other approved result will be returned. Random jittering is used to distribute expiration peaks, but the user’s maximum expiration limit must still comply with the contract and cannot be indefinitely extended for the sake of load. Performance optimization and data correctness are independently verified.

Pre-refreshing low-access resources may waste computation, while hot resources can be triggered for controlled refresh upon access. The choice depends on reuse and upstream costs, and there is no unified background task execution for all keys. Observing the refresh success rate in relation to the actual age of the objects helps determine whether high hit rates are simply due to continuously providing old values. Cache failures can be refreshed from the source, but refreshing also requires capacity protection, and it is not possible to make unlimited simultaneous requests to the database.

Empty results also have caching semantics.

Objects that do not exist can be temporarily cached, reducing the frequency of malicious or erroneous requests accessing the database. However, once the object is subsequently created, the negative cache will make it temporarily unavailable. The creation process requires invalidating the corresponding key, or choosing a short, acceptable duration.

A read failure should not be treated as if the cache is empty. If the database timeout returns an empty list, caching it for 10 minutes will extend the duration of the short failure, leading to the disappearance of the long-term data. The caching layer must distinguish between successful empty results and failed results. The interface should also preserve this distinction.

The results related to permissions must also consider the scope of the user and tenant. If the list of objects visible to user A is placed in a shared key, the hit rate may be good, but data isolation will be compromised. When designing cache keys, the primary considerations should be semantic meaning and security boundaries, followed by string length.

Failure, an empty success status, upstream failures, and permission denials cannot all be represented by a single null value. The object wrapper can contain status, business version, source time, and format version, and validation is performed to ensure the correct type. After a format upgrade, old objects cannot be misinterpreted as new forms or rules. Version rules and security failure strategies provide a transition. Serialization tools do not replace business validation, and caches can also be corrupted by incorrect data or writers.

Multi-tenancy and user scope are explicitly defined in the key and read authorization. Simply concatenating the user ID into the key still requires logging and high-volume costs, and should not be used as a dimension. Public, shareable objects and private states use different storage strategies. Even if the shared cache hit rate is high, related paths should be immediately disabled as soon as cross-permission access occurs. Performance metrics cannot compensate for the isolation errors.

Observe the Obvious, But Don’t Just Focus on Success

A high cache hit rate does not necessarily mean that users are receiving the correct values. By recording object versions, cache ages, and refresh delays, we can identify situations where updates have not propagated for a long time. Comparing sampled cache results with authoritative sources is particularly useful for verifying the failure of protocols during the initial deployment phase.

The cost of caching should also include the cost of memory, serialization, network round trips, and maintenance complexity. For data with low access volume, directly querying the database may be simpler than introducing a distributed cache. First, identify the performance bottleneck, and then choose the smallest, most manageable caching range.

When the database update is successful and the cleanup call fails, it’s not possible to return “All updates have been completed” without leaving an indication that a retry is intended. The cleanup task can be persisted and retried, or it can rely on a clearly defined TTL (Time-To-Live) window. However, these two approaches have different implications. Retrying should save the object version and key range, preventing background tasks from cleaning up the new version. Verify that the new values have propagated to the controlled cache layer by comparing resources.

Platform notifications or keyspace events can be used to trigger refreshes, but their delivery guarantees must be verified against the risk of data loss, and they cannot replace authoritative business state. Observation mechanisms help detect changes, and reliable consistency comes from version and transaction boundaries. When the cache is unavailable, there are controlled fallback and rate limiting mechanisms. When the update mechanism is unavailable, there are clear strategies for handling outdated data. It is more recoverable to proactively communicate these failure scenarios than to repeatedly clear the entire cache during an incident.

Start counting from the age when the item was originally manufactured.

After reading the previous version (version 10) from the database, the process pauses. Version 11 has been released and the cache has been cleared. The old request is then re-filled. If the TTL (Time To Live) starts from the time of writing, it will regain a complete, fresh window, but the source data is already quite old. The object wrapper stores the source version and timestamp. Both reading and writing check the age commitment. A long pause cannot be converted into new data simply by writing late. Timestamps and versions have different purposes: the time limit controls tolerance, and the version relationship identifies the order of content.

Regarding data with timestamps from unreliable sources, we can only guarantee the lifespan of the cached object. We should not claim a strict maximum information age. When stronger guarantees are required, use the authoritative version to read or modify the architecture. There is also a time drift between source clocks across nodes, so it is not possible to compare machine times arbitrarily. The data guarantee should align with the actual information capabilities, and should not be expanded simply because the TTL name appears reasonable.

The test saves the source read time, the fill-in time, and the final returned version. After a controlled pause exceeds the allowed window, it recovers. The correct strategy may reject old writes or continue to serve according to approved outdated policies, but the results are consistent with the documentation. Reducing TTL only shortens certain windows, but does not replace version coordination; delaying double deletion depends on the upper limit of the pause, and cannot cover indefinite stops. Using this counterexample as a long-term regression sample is more useful than repeatedly arguing about the validity period in each incident.

The current version’s pointer represents an independent consistency problem.

The “un-mutating key” product:42:version:18 and 19 can coexist. If “A” writes 18 instead of 19, it will not overwrite the 19 object, but if “A” writes 18 back from 19, the reader will still return the old value. Pointer updates must have a reliable version sequence and conditional guarantees, or be directly selected by an authoritative source. Normal read-then-write operations do not produce cross-instance atomicity, and verification is required for actual CAS, transaction, or coordination capabilities.

The lifespan of the pointer itself also affects the visibility of updates. Content objects can be long-cached, and selecting metadata may require shorter or authoritative reads. Separating these allows for concentrated consistency costs, but doesn’t mean they disappear. Deleting resources in an authoritative selection expresses a tombstone or unreadable state, and old objects still exist and cannot be resurrected. Permission changes are first granted, then shared content is read, and cached versions do not grant permanent access.

When reverting a pointer, it is crucial to explicitly determine whether the business allows reading old content. Older versions, if rolled back, may no longer be available. The code rule version recovery and content version recovery actions are recorded separately. The old version retains the “in-progress” service page and investigation, but cannot be used to indefinitely expose sensitive content for convenience. Cleanup should be based on approved references and lifecycle, not inferred from random filenames.

A refresh lock does not provide permanent write access.

After Mr. A obtains the updated lease agreement, he pauses. Mr. B takes over and writes the new version. Mr. A may still write the old results. The update object requires version compatibility or immutable results with a reliable choice, and cannot simply check if Mr. A previously obtained the lock. Merging Promise in the same process only coordinates this instance; cross-node requests may still return the old results. If the goal is to reduce redundancy rather than strict consistency, allowing a small amount of redundancy may be simpler, but it is important to honestly specify the guarantees.

After a lock acquisition fails, the waiting party has a limited time. The failed Promise cannot remain indefinitely in the map. Cancellation, exceptions, and normal completion states all trigger cleanup, along with concurrency and a total budget. Simultaneously expiring popular keys can cause a sudden spike in load, while random jitter can disperse many keys, but it does not resolve business serial or qualification issues related to a single hot spot. Limited public resources are pre-warmed, but cannot proactively pull all parameter combinations, which can cause stress events.

When refreshing fails, the old object will definitely expire and will not be automatically extended. If consecutive failures exceed the business tolerance, a controlled error or another approved result will be observed by the front-end (200 status code) and the back-end. Refreshing low-access objects may be wasteful, so choose based on reuse rate. While hitting a high but old object may not be a performance victory, it’s important to record the source age and the actual update propagation simultaneously.

Ensuring that successful outcomes and failures are treated as distinct values

Resources that can be temporarily cached when unavailable should be marked as “unavailable” in the database. A database timeout should not be treated as a signal to cache “unavailable” resources. After creating a resource, the corresponding negative object should be cleared. After deleting a resource, the old positive object should be removed. Both of these conversion directions should be tested independently. The object structure should retain state, source, and format version information. Damaged or unknown old formats should be handled with controlled failure, and parsing errors should not be converted into permanent empty lists.

The empty result of multi-tenant queries is also bound to an identity scope. This means that if user A cannot see a particular object, it does not necessarily mean that user B does not exist. The public and private states are stored separately, and the keys do not contain the full token. User keys in the logs may reveal the associated relationship, and limited aggregation and controlled sampling are used instead of full printing. The primary goal of caching is to support shared semantics, not to maximize hit rates.

Failed Update Leaves a Recoverable Obligation

The database has been submitted, but the cleanup interface failed. You can either persist the exact resources and target versions for continued retries, or explicitly accept the TTL window. These two policies have different definitions and cannot simply return “all updates” without evidence. The recovery task does not clean up new objects that appear later; it is bound to the target and version. Even if event notifications are lost, the authoritative reconciliation process is still required. Observing notifications helps to identify changes, but does not replace the actual transaction and version facts.

A failure in the caching service resulted in a large number of requests being redirected to the origin server. The original server also had limited capacity. Using access control and tiered degradation helped to prevent the problem from escalating. Unapproved old permissions or transaction results would not be returned simply because the original server was busy. This accurately informs users that the service is currently unavailable, and the logs indicate failures in the cache, the origin server, and the degraded category. Availability and security have their own boundaries, and it is not appropriate to say that “old results are better than no results” for all data.

Migration also carries the risk of rollback. New code is stored in a more complex package, and when the old code is restored, objects may be treated as ordinary business values. Cache rules should isolate incompatible serialization, or old reads should explicitly identify and invalidate them. Do not rely on JSON parsability to assume that the type is valid. Test by saving old objects, deploying new reads, then saving new objects and rolling back the old reads. Confirm that failures are due to controlled rollback, not authorization errors or missing fields. Content versions and format versions each have their own identity, and the record should not be a single, generic deployment.

Using a Cacheless Baseline to Determine if Complexity is Worthwhile

Directly querying the database for low-frequency reads might already be sufficient. Increasing caching introduces network, serialization, and failure management, which can actually slow things down. When comparing the same task, observe the workload, latency, and maintenance risks. Avoid inventing a general improvement ratio. Only cache data that is truly reusable and allows sharing, which can reduce the need to prove protocols. The technical solution can be simpler and more reliable, with the ultimate goal of completing the correct task as promised.

Intentionally Altering the Order of Events During Acceptance

Implement a scenario where the old read operation pauses after the database returns, completing the new write and delete operations, and then resumes the old read. Verify that the results are consistent with the promised consistency. Also, test the scenario where a popular key expires, a refresh fails, an object is deleted, and negative caching is used, followed by the creation of a new key.

The final document should clearly specify which data is allowed to become stale, for how long, and which operations always revert to the authoritative source. The discussion about the validity of the cache invalidation scheme can only take place if it is explicitly defined within this agreement.

First, define the acceptable window for aging. Then, demonstrate that the window is maintained by successfully completing tests that pause old backfilling, random pointer updates, and refresh failures. Compare the authoritative version with the actual returned version, record the percentage exceeding the window, and check not only the average latency. Deletion, creation, and authorization changes require separate samples. The baseline for low-access scenarios is also cache-less, and the final choice can be fewer caches and lower maintenance costs. The technical solution does not need to be overly complex for complexity’s sake.

When there are multiple caching layers, clearing the application object does not mean that the CDN and browser simultaneously exit the old values. Draw four layers: the source library, application cache, HTTP cache, and page memory, and indicate the version source, expiration period, and invalidation point for each layer. Use the same synthetic price to read from public details, forced refresh, and settlement to determine which layer still holds the value. Settlement does not rely on the cache from public details. When the client memory does not have remote clearing guarantees, clearly indicate the actions of refreshing or reconfirming the price, and do not assume that the server-side purge has successfully updated all screens.

References