Application caching Versioned cache fills

Application caching

Versioned cache fills

Deep diveAbout 9 minutes AI-generated

A server can read the right answer and save it too late. While it waits, another request changes the source and deletes the cached copy. The delayed fill then puts the old answer back. A conditional fill checks whether that result still has permission to enter the cache.

Freshness and invalidation avoided the old copy by asking the source which revision to use on every request. Here we keep the ordinary cache-aside path. The extra check happens when the server saves an answer for reuse, a step we will call publication.

We want to stop an old fill undoing an invalidation the cache has already processed. The cache cannot detect a change it has not heard about. That boundary separates a useful ordering guarantee from a promise to return the latest value.

The old fill arrives last

Keep the parent’s price change: the mug goes from £20 at revision 1 to £22 at revision 2. A server that read before the edit still holds revision 1 after invalidation. Deletion removed the cache’s copy, not the server’s private result.

Making each command atomic does not join the source read and the later cache write into one operation. Publication needs a condition that can change while the source read is in flight.

Remembering a newer revision

A source revision identifies a particular state of the product. Suppose invalidation carries revision 2 and leaves that number in the cache, even after removing the card. A later fill carries revision 1. Comparing the two tells the cache something useful: it has already heard about a newer product.

The comparison and replacement must happen atomically. If the application reads the remembered number and writes the card in separate calls, an invalidation can arrive between them. The earlier check then says nothing about the state being overwritten.

Reordered notifications need the same care. Once the cache remembers revision 2, a late notification for revision 1 must not lower the number. Retain the maximum known revision. That maximum prevents a known regression; it does not prove that the source has made no further change.

Figure 1. The lower case deliberately uses an unsafe rule. Missing revision knowledge must block or validate the fill, not invent permission.

Losing the remembered revision removes the evidence that a newer answer existed. Treating missing as zero would accept the old fill again. Meta’s account of cache consistency describes this failure when version knowledge is evicted.

Missing must mean unknown. A design that needs the remembered revision must restore trustworthy knowledge or bypass that fill path. It cannot bootstrap its knowledge from the delayed candidate whose age it is trying to judge. Keeping the number in a separate key only moves the lifetime problem to that key.

The source’s numbering must survive deletion and recreation too. Restarting a recreated product at revision 1 can make new data look older than the deleted product. Use an identity and revision scheme that orders those changes correctly, as the parent’s versioned keys require.

Reserve permission before reading

Instead of remembering the newest source revision, remember permission for one attempt. On a miss, the server first reserves a fresh token in the cache, then reads the source. Publication succeeds only while the cache still holds that matching reservation.

The key has three possible states. It is absent; it is loading, with a token; or it is ready, with the product and its source revision. Invalidation deletes either a loading or a ready record. Successful publication replaces the loading record with the ready one, consuming the token.

One record, three states
Record before the operationOperationResult
AbsentReserve fresh token ALoading A
Loading APublish with AReady card; A is consumed
Loading A or ready cardInvalidateAbsent
Absent, loading B or ready cardPublish with ARejected; record unchanged
Figure 2. The reservation precedes the read. Comparing the token and publishing are one atomic cache operation; deletion can revoke either a loading or a ready record.

Deletion revokes the permission as well as removing any saved answer. Missing state now works in our favour: absence cannot authorise publication.

There are only two orders at the publication boundary. If publication happens first, deletion removes the ready card. If deletion happens first, publication finds no matching reservation and fails. Neither order leaves that attempt’s card in the cache after both operations finish.

The reservation must precede the source read. Read revision 1 first, then let revision 2 commit and its deletion finish. A reservation made now would grant fresh permission to publish an old result. Starting a new attempt therefore means both a new token and a new source read.

One implementation in Redis

Redis can reserve the missing key with SET NX, which writes only when no value exists. The token is a fresh identifier, never reused for another attempt. A securely generated random identifier is a practical choice, with uniqueness assumed. The labels A and B in these examples are shortened names, not a two-token pool.

# Before reading the source; token is new for this attempt.
SET product:v1:north:P7:en-GB:GBP loading:<token> NX PX 5000

# Only after SET returns OK:
product = source.read_current_product(context)
publish_if_still_loading(key, token, product)

The five-second reservation lifetime is an illustrative cleanup setting for a stuck attempt. It is not the card’s freshness allowance. A request that finds an existing loading record needs a bounded waiting or fallback policy; Handling cache misses owns that decision. Permission to publish does not prove that only one process is still doing source work.

After reading, the server runs this short Lua script with the same key and token. The raw product JSON includes its source revision. The loading: and ready: prefixes distinguish record states; a reader must only decode a ready record as a card.

-- KEYS[1]: complete product key
-- ARGV[1]: token; ARGV[2]: product JSON; ARGV[3]: ready TTL in ms
if redis.call('GET', KEYS[1]) ~= 'loading:' .. ARGV[1] then
  return 0
end
redis.call('SET', KEYS[1], 'ready:' .. ARGV[2], 'PX', ARGV[3])
return 1

Redis executes a script atomically, so deletion cannot occur between this comparison and replacement. Return value 1 means publication succeeded; 0 means permission was absent or no longer matched. The source read remains outside the script and outside its guarantee.

Use the same conditional operation on every completion path. An error, a timeout or an uncertain result must never trigger an unconditional SET. If publication succeeded but its reply was lost, repeating the script finds a ready record and returns 0. That is safe for the cache, but the second reply does not tell the client whether the first publication succeeded.

This is one Redis implementation of a broader mechanism. Scaling Memcache at Facebook describes fill tokens invalidated by deletion. Memcached’s meta protocol offers miss placeholders and compare-and-set operations. A local cache can use equivalent synchronisation around the record. Each implementation must preserve the same ordering and missing-state rules.

When the permission disappears

Expiry, eviction and an empty restart can all remove the loading record. The old token then fails because absent is not a match. A new attempt reserves a different token, so the old token still fails. Once the new attempt publishes, the record is ready rather than loading and cannot match either token.

A reservation can expire while its server is still reading. Another server may reserve a new token and start its own read. Both can now be doing source work, though only the new attempt can publish. The token protects the cache; it does not by itself protect the source from duplicate work.

A counter reset to a familiar number would break that reasoning. An old attempt could match a newly created record with the same generation. A generation counts cache state changes; a source revision identifies product state; a token identifies one attempt. The v1 in our key identifies the representation format. These values name different things.

Losing all cache state is also different from restoring earlier cache state. An old snapshot or a lagging promoted replica could bring token A back after its deletion. The old attempt could then match it. Our reasoning assumes one cache history that never restores a revoked reservation.

Redis replication is asynchronous by default, and its documentation warns that even acknowledged writes can be lost during failover. WAIT does not establish the recovery boundary this protocol needs. A deployment must make attempts from before recovery unusable, or bypass the cache for the required source validation. A longer reservation lifetime does neither.

What the cache has not heard

Now suppose a server reserves token A and reads revision 1. The source commits revision 2, but its invalidation is delayed. The cache still holds loading A, so the server can publish revision 1 with its matching token. The old card remains available until invalidation arrives or another validity rule rejects it.

Figure 3. A matching token proves that its reservation has not been revoked. It does not prove that the source is unchanged.

The matching token established only that permission had not been revoked. No processed invalidation was undone; the cache had not heard about the commit. The parent’s delivery mechanism and observation-age rule still decide how long the old card may be used.

A lagging source replica creates another path to the same result. A server reserves a fresh token after revision 2 committed, then reads revision 1 from that replica. Publication can succeed. Reserve-before-read orders the attempt; it does not make the chosen source current.

Late and repeated deletes have a different cost. They can remove a newer revision 2 card, causing another miss, but a delete cannot restore revision 1. Call this extra work, rather than treating every removal of a newer card as a stale result.

Finally, a rejected cache fill does not settle the waiting caller’s request. The reader server still holds revision 1 in memory. The public card may be allowed to use it within its observation-age allowance; a merchant requiring revision 2 or newer may not. Apply that requirement separately. A strict request may need another authoritative read, or fail if its deadline leaves no time. Checkout continues to use authoritative price and stock checks within its transaction.

Choose where to establish the revision

These designs answer different questions. Choose the one that establishes what the reader needs without depending on cache knowledge you cannot keep valid.

What each check establishes
DesignWhat it establishesWhat it depends onSource work
Remember maximum source revisionA fill does not go below the known revision.Trustworthy revision knowledge survives, or missing knowledge blocks the path.Source reads on misses; recovery may need validation.
Revocable fill tokenAn invalidated attempt cannot publish later.Unique tokens, atomic replacement and no resurrection of revoked records.A new source read for each new attempt.
Authoritative revision selectorThe selected revision was current at that source read.A suitable source read and a revision covering the whole answer.A source revision lookup on every request.

None freezes later source changes. If the authoritative lookup is cheap enough, the parent’s versioned-key design may be simpler to justify. Conditional fills earn their complexity when avoiding that lookup matters and the cache can uphold the required history.

Exercise the competing orders

Download versioned_lab.py and its helper, cache_lab.py, into one directory. You need Python 3 and a local redis-server executable on macOS or Linux. No Python packages are required. Run without Python’s -O option so the checks remain active:

python3 versioned_lab.py --json versioned-results.json

If Redis is not on your path, add --redis-server /path/to/redis-server. The script starts its own temporary Redis with TCP and persistence disabled, then removes it on exit. It prints a pass for each checked schedule and saves the commands and replies in the JSON file.

The native experiment ran these schedules against Redis 8.10.3. Redis executed the reservation, deletion and Lua publication; a Python dictionary modelled the authoritative product. Each step waited for the preceding command’s reply, making the order repeatable without relying on a lucky race.

Observed cache results in the controlled experiment
SchedulePublicationCache afterwards
Read 1 → commit 2 → delete → unconditional fillAcceptedRevision 1
Reserve A → read 1 → commit 2 → delete → publish ARejectedAbsent
Reserve A → read 1 → publish A → commit 2 → deleteAccepted, then deletedAbsent
Expire A → reserve B → read 2 → publish A, then BA rejected; B acceptedRevision 2
Repeat B’s successful completionRejectedRevision 2 unchanged
Reserve A → read 1 → commit 2 → publish A; delete still pendingAcceptedRevision 1 until deletion

The source is revision 2 at the end of every schedule in the table. The delayed revision-1 reader still holds its old candidate; replacement B has reread revision 2. Only the cache outcome is decided by the publication check; the caller’s result needs its own freshness decision.

The experiment also rejected an old token on a fresh, empty Redis instance. It reproduced the unsafe alternatives: reserving after the read, splitting comparison from publication, and treating a lost revision as zero. Metadata loss was induced with deletion; a lagging source was modelled by returning revision 1. Neither a real eviction workload nor replication failover was measured.

When testing an implementation, keep those counterexamples. A test that only publishes a current card cannot distinguish a conditional fill from an unconditional write. Force the old answer to arrive last, lose the metadata, repeat a completion, and delay the invalidation. Check source, cache and caller separately.

Sources and further reading

← Back to Freshness and invalidation