Application caching
Freshness and invalidation
The shop raises the blue mug’s price from £20 to £22. Its cached product card still says £20. Nothing is broken in the lookup: the cache returns exactly what it was given. The answer has become stale because the source changed.
A freshness rule decides whether the application may still use that answer. Expiry ends reuse after a time limit; invalidation ends it because something changed. Neither stops a read already in flight from bringing the old price back. We need to follow both the age of the answer and the order in which work completes.
What does fresh mean here?
The public product card, the merchant’s edit page and checkout all read the same product, but need different promises. A catalogue may allow a short delay before a price change appears. A merchant who has just saved £22 expects to read back that change. Checkout needs the authoritative price when it decides what to charge.
| Reader | Required promise | What £20 would mean after the change |
|---|---|---|
| Public product card | Reuse an observation for at most thirty seconds, in this example. | Permitted briefly, if its observation is young enough. |
| Merchant after saving | See the completed write, or a later revision. | Too old, even one second after saving. |
| Checkout | Use authoritative state in the checkout transaction. | The card’s price cannot authorise the sale. |
The first promise is an age limit. It does not say that the card always contains the latest price. If the price changes a moment after a source read, that read can still be reused within the allowance. The second promise is usually called read your writes. It relates the read to a particular completed change, rather than to a clock.
Write the promise before choosing a cache setting. Also say where it applies: here, the age limit is checked when the application hands the answer to its response path. It cannot make a browser tab update itself thirty seconds later. A page that must keep tracking the price needs its own refresh behaviour.
Expiry measures time in the cache
A time to live, or TTL, says how long an entry may remain available after it is stored. It knows when the cache received the copy. It does not know when the source produced it.
The answer is already ageing while the server waits to save it. A longer delay leaves a younger-looking cache entry holding an older observation. Reading a lagging replica can make the observation older still.
A second cache layer can extend reuse again if it starts a fresh TTL for a copied answer. Moving the answer did not observe the source again. Carry the original age information through every layer instead of starting a new allowance.
Redis illustrates the distinction directly. SET key value EX 30 stores a value and its expiry together. Calling EXPIRE key 30 later renews that lifetime without reading the source. Neither operation establishes how current the value is.
Enforcing an age limit
To enforce the catalogue’s thirty-second rule, keep the time of the source observation with the answer. At insertion, subtract the time already spent from the allowance. At return, check the age again: time may have passed in a queue or while decoding the value. Reject an answer whose allowance has run out, even if the cache still holds it.
If the allowance has already run out before insertion, the application needs a new source read. It must fail the request if it cannot obtain a suitable answer in time. A refresh failure does not extend the deadline. Handling cache misses develops the waiting and source-capacity decisions.
The timestamp must describe a meaningful observation. A source read that takes a new, current snapshot gives a useful starting point. Recording time just before that read is conservative: it counts the read’s own duration too. Stamping the answer when it arrives would hide that duration.
A lagging replica needs more information. Reading it now does not mean its state is current now. Either include a trustworthy bound on its snapshot age or use a source read with the required freshness. An old transaction snapshot has the same problem. For example, PostgreSQL’s Repeatable Read transactions keep their earlier snapshot across later queries.
Elapsed time is simplest inside one process, using a monotonic clock that does not jump with wall-clock adjustments. Its readings cannot simply be compared with another machine’s monotonic clock. A shared cache needs an agreed time basis and a bound on clock error; subtract that uncertainty from the allowance. If those assumptions are unavailable, the application cannot claim a strict age limit from a timestamp alone.
This measures time since a valid observation, not time since the product last changed. A price unchanged for a year can be freshly checked today. Equally, a thirty-second-old observation can contain a price replaced twenty-nine seconds ago.
Invalidate after the source commits
Waiting for expiry may be unnecessary when the application already knows the source changed. After the merchant’s update commits, delete the cached card. The next miss reads the source and builds the £22 card. This is invalidation: remove the permission to reuse an answer because its dependency changed.
The order matters. Delete first, and a reader can miss while the source still says £20. That reader refills the old card; the writer then commits £22 and leaves the refill behind. Committing first avoids this particular gap.
But the commit and the deletion are still separate operations. The source can accept the write and the application can stop before sending the delete. The delete can fail, or its reply can be lost. The source price remains £22 in all those cases. Treat the invalidation as unfinished work to retry, rather than pretending the source write was undone.
An age limit gives the old copy an eventual stopping point while invalidation is delayed. That limit must be the observation-age rule established above if the promise concerns source age. A new insertion TTL on an old fill would start another interval.
Updating the cached card after committing is another choice. It avoids a subsequent miss when it works. A design often called write-through organises source and cache updates together on the write path, but the name does not make two stores one transaction. Both deletion and replacement still have to account for reads that began before the change.
A fill can arrive after the deletion
Suppose a reader obtains the £20 card from the source, then pauses before saving it. The merchant commits £22 and deletes the cache entry. When the paused reader resumes, it saves its £20 result. Deletion removed the cache’s copy, but could not remove the answer already held by the reader.
Every operation succeeded, yet a new insertion TTL now grants the old answer another lifetime. Successful individual operations have produced the wrong combined result.
Replacing the cache with the new price has the same weakness: the delayed fill overwrites it. Atomic cache commands ensure that each individual operation happens as a unit. They do not join the earlier source read, the source commit and the later cache write into one operation.
The race is not specific to Redis. Scaling Memcache at Facebook describes old fills arriving after invalidation and a token mechanism for refusing them. The optional Versioned cache fills article builds that kind of conditional publication step by step.
An age check and an ordering check answer different questions. The delayed observation can still be young enough under the catalogue’s age rule while predating the merchant’s write. Rejecting publication also does not decide whether the reader’s waiting caller may receive its saved result. Apply the caller’s freshness promise separately.
Find every answer that changed
A product can affect more than its own card. The shop also caches a list of products under £21. Raising the mug’s price changes whether it belongs in that list.
Deleting the product card repairs only the next card lookup. Even if the list stores product IDs and reads current cards separately, it still includes a product that no longer meets its filter. A price change affects both the displayed value and the list’s membership.
Find these dependencies from the questions the cache answers. When the affected keys are known, delete them directly. If tracking every filtered list is too difficult, invalidate a broader group, such as north’s product-list results. That is easier to get right, but it discards unchanged answers too.
A broader invalidation means more misses and more work at the source. It needs the same capacity controls as a cold cache, developed in Handling cache misses. Where the product allows a delay, expiry can be the simpler choice for derived answers. Make that a declared allowance rather than an accidental omission from the invalidation code.
Recovering missed changes
Retrying a delete helps only if something remembers that it is due. One design writes a change record alongside the product update in the same source transaction. A background consumer reads committed records and invalidates the affected answers. This record is an outbox: work saved durably before the request can disappear.
The transaction makes the update and its change record succeed or fail together. After a crash, a consumer can find pending records and continue. A source change stream can provide another route, with its own retention and resume rules. Both require a way to recover if consumption falls behind what the retained history can cover.
Notifications can be late, repeated or reordered. A repeated deletion cannot restore an old value, although it can remove a newer fill and cause another miss. A consumer that installs values from notifications needs a revision check so an older event cannot overwrite a newer one. The outbox closes the lost-notification gap; it does not stop an earlier source read from filling after deletion. These delivery concerns also appear in AWS’s outbox guidance.
Every source writer must reach the repair path. A bulk import or an administrator’s update can bypass application code that deletes keys. Either include those changes in the same mechanism or choose an age policy that explicitly tolerates them. Measure pending work and failures; a consumer that has stopped is not an invalidation guarantee.
Redis keyspace notifications report changes to Redis keys. They do not discover a price change in a separate database. They also lose events sent while a subscriber is disconnected, so they cannot serve as this durable source-change record.
Absence, deletion and access changes
A cached not-found answer becomes stale when the missing product is created. Invalidate it after the creation commits, or allow its stated negative-cache lifetime to run out. Creation changes the answer just as surely as a price edit does.
Deletion runs the other way. The source no longer contains the mug, but its cached card still exists. Removing a record therefore needs the same dependency work as changing its price, including lists that contain it. A late fill can restore a deleted product’s card just as it restored the old price.
A timeout is different from either result. It says that the application did not get an answer, not that the product is absent. Cache keys gives absence its own representation so a failed source call cannot quietly become a cached “not found”.
The catalogue here is public. Now consider a restricted product view whose policy requires current access on each request. Revoking a reader’s permission changes whether the answer may be returned even when the product bytes are unchanged. Check that permission through the required authoritative path before returning the cached content. A content TTL, or a user ID in the cache key, cannot replace that check.
Put the revision in the identity
A versioned key separates answers from different source revisions. Revision 1’s card goes under a key ending in :r1; revision 2’s goes under :r2. A late revision 1 fill can no longer overwrite revision 2’s card.
The remaining question is how a reader chooses which key to use. A cached “current revision” pointer can itself be stale. One straightforward design reads the revision from the authoritative source on every request, then looks for that exact card.
This design still performs a source read on a hit. It pays when reading a small revision is cheaper than rebuilding the complete representation. It is less useful when the supposedly small lookup does almost all the work that caching was meant to save.
On a miss, the payload and the revision must come from the same source snapshot. Suppose the first lookup chose revision 2, but the product changes again before the application fetches it. The second read must return the product with its own revision. Store it under that revision’s key, rather than labelling new data with the earlier number.
revision = source.read_current_revision(context)
if revision is absent:
return not_found
key = product_key(context) + ":r" + revision
card = cache.get(key)
if card matches context, format and revision:
return card
# Read the product and its revision in one source snapshot.
product = source.read_current_product(context)
if product is absent:
return not_found
# It may have changed since the first read. Use its own revision.
key = product_key(context) + ":r" + product.revision
card = build_card(product)
cache.set(key, card, cleanup_ttl)
return card This is pseudocode for the selection rule; Caching with Redis covers bounded calls, decoding and cache errors. An unusable cache result follows the miss path. Failure to save a correctly built card need not prevent returning it. Failure to read the authoritative revision cannot be replaced with an arbitrary old key while preserving the same promise.
The source must advance the revision for every change that affects the card. Revisions cannot be reused for different data, including a deleted and recreated product. If the card combines several records, its revision must cover those dependencies too. A product revision alone cannot validate a separately changing discount table.
A hit reflects the revision current at the authoritative lookup. The source may change again before the response arrives; no cached key freezes it. This is still useful: a request made after an acknowledged write can select that write or a later revision, provided its source read has that guarantee.
The old :r1 key needs expiry or eviction for memory cleanup, even after nobody selects it. That expiry controls storage use rather than establishing which revision is current. If the revision lookup is too expensive, Versioned cache fills explores protocols that retain ordering information at the cache. They must also account for losing that information.
Reading after a write
Return to the merchant who saved £22. The simplest read-back path bypasses the cached card and makes a fresh authoritative read after the acknowledged commit. It must use a read path that includes that commit: a lagging replica or an older transaction snapshot may still return £20.
The write response can also return revision 2. A later request can then say “revision 2 or newer”. That number is useful only if the application can honour it. It must reject a revision 1 hit and obtain a suitable source result, wait within the request’s deadline, or report that it cannot satisfy the read. Carrying a revision number without enforcing it changes nothing.
Checkout keeps its authoritative read within its normal transaction and stock checks. A current product read alone does not reserve stock or make the rest of checkout atomic. The cache saves catalogue work; it does not decide that a sale can proceed.
| Need | A useful starting design | What must remain true |
|---|---|---|
| Allow a short catalogue delay | Reuse within an observation-age limit. | The source observation and elapsed-time bound are trustworthy. |
| Show changes sooner | Invalidate after commit, with a retryable change record. | Every affected answer and every writer reaches that path. |
| Reuse expensive assembly at a validated revision | Read the authoritative revision, then select a matching card. | Revision, payload and dependencies agree. |
| Read back a completed edit | Bypass the cache for a suitable authoritative read. | The read includes the acknowledged commit. |
The choices can coexist. The public card can tolerate a bounded delay, invalidation can shorten that delay, and the merchant can bypass both paths after saving. Decide what each reader needs first, then test the orders in which the source change, notification and fill can arrive.
Sources and further reading
The figures model shop north’s mug, in GBP, with invented timings. The collection’s native experiment ran on Redis 8.10.3 with an in-process Python source model. It reproduced source revision 2 beside cached revision 1 with a new thirty-second TTL after the late fill. A separate one-second age check rejected a delayed observation aged 1.108 seconds. That check used one process’s monotonic clock; it establishes no cross-machine clock or replica guarantee.
- Redis, SET and EXPIRE: setting and renewing entry lifetimes.
- Redis, Keyspace notifications: which changes they describe and what a disconnection loses.
- Nishtala et al., Scaling Memcache at Facebook, section 3.2.1: stale fills and invalidated lease tokens.
- Meta Engineering, Cache made consistent: reordered fills and invalidations, and the loss of remembered versions on eviction.
- AWS, Caching challenges and strategies: freshness choices and the source demand caused by cache failure.
- AWS Prescriptive Guidance, Transactional outbox pattern: recording work with a source change and handling repeated delivery.
- PostgreSQL 18, Transaction isolation: when a query or transaction takes the snapshot it reads.
- On this site: Versioned cache fills for conditional publication; Handling cache misses for refresh and source protection; Operating a cache for checking whether delivered answers meet the promised freshness.