BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
Backend Engineering

Advanced · Lesson 9 of 12

Software Architecture

Cache Reads Without Serving Stale Orders

Mariam changes her pickup branch, then her tablet sends her back to the old one. Trace the order revision, cache key and late reader that explain why.

A customer checks a paper pickup slip as a shopkeeper moves a notebook parcel between wooden cubbies.

Mariam changes the pickup branch for order SH-481 from Al Majaz to Al Khan. Her phone shows a confirmation with the new address. She opens the same order on her tablet a moment later and sees Al Majaz again. Which branch should she drive to? The database recorded her edit correctly. The tablet received a perfectly valid response assembled before the edit, and the service mistook a reusable copy for a current one.

We will design the read path for that one order. The expensive part is assembling its lines, discounts, pickup instructions and localized labels. The cheap part is looking up the order's owner and current revision by primary key. That difference makes caching worthwhile even if a read still reaches the database. Our promise is specific: an authorized read that begins after a successful edit must show the committed revision or a newer one. A read already in progress when the edit commits may finish with the older revision.

Decide exactly what a cache hit buys

Start with a concrete response. Order SH-481 belongs to customer 52 in shop 7. At revision 12 it contains two notebooks for AED 27, to be collected at Al Majaz. Both English and Arabic views use the same facts, but the pickup instructions and field labels are already rendered into the selected language. The customer view excludes the clerk's internal notes. If two requests could correctly receive different bytes, consider whether they should share a cached representation at all.

Use a key such as shop:7:order:SH-481:r12:customer:ar:fmt3. The shop component separates order numbers that are unique only inside a merchant. The revision names one committed state. The audience and language identify this particular view. The final component changes when the response format or the bundled translations change. Derive the shop and audience from the authenticated request. A caller who knows every component of a key still has to pass the current authorization check before reading its value.

For this example the response is identical for every authorized customer viewer of that order and contains no viewer-specific fields. If you add a personal discount preview, that assumption breaks. Either move the preview outside the shared value or include the actual pricing context and its revision. Likewise, if pickup directions come from a separately editable branch directory, embed the agreed instructions in the order snapshot or incorporate the directory revision. Changing a branch's directions without changing any input to the key quietly makes two different responses look interchangeable.

Follow a cold read and a warm one

At 10:00:00 the tablet requests the Arabic view. A primary-database lookup checks shop, owner and order state in one operation and returns revision 12. The application asks Redis for the corresponding key. On a miss, assemble the representation from a consistent database snapshot, using the revision observed in that snapshot to label the result. If the snapshot already contains revision 13, build and store revision 13 under its own key. Never label a body with a revision copied from an earlier, separate lookup.

Set the body and its expiry in one operation. For this example, SET with EX 60 gives a newly stored copy a lifetime of sixty seconds. The next request checks access and revision again, then gets the prepared Arabic body in one cache read. There is no need to repeat all the line-item queries or run the formatter. An English request initially misses, even if Arabic is warm. Giving these variants separate entries costs memory and saves the client from receiving the wrong instructions. Redis SET command

Why sixty seconds? It is an example retention choice, not a business guarantee. Suppose a busy order is viewed once every five seconds and the prepared body costs appreciably more than the revision lookup. Several reads can reuse each build. For an order opened once in a month, a far longer lifetime mostly retains unused bytes. Measure visits per order and the size of each language variant. Expiry is also how old revision keys leave the cache without a cleanup process having to discover all their names.

Put the change on a timeline

At 10:00:10 the phone submits the new branch with expected revision 12. The database checks ownership and the permitted state transition, updates the pickup branch and advances the revision to 13 in the same transaction. Return success only after commit, with Al Khan and revision 13 in the response. If another editor has already changed the order, resolve the write conflict against the current record. A cached copy supplies neither the authorization nor the concurrency check for a mutation.

Event Authoritative revision What the reader can reuse
Arabic read before edit 12 Arabic customer view of revision 12
Branch change commits 13 Existing revision 12 copies can age out
First Arabic read after commit 13 Revision 13 Arabic body, built on a miss
English read after commit 13 Only the English view of revision 13

Consider a reader that started before the edit. It observed revision 12, missed the cache, and paused after assembling the old response. It wakes after the writer commits and stores Al Majaz. With the revision in its key, it can only populate the obsolete revision 12 entry. A fresh read gets revision 13 from the primary and has no route to the obsolete entry. That is logical invalidation: the old bytes may still exist, but the service no longer selects them for a new request.

A cheaper design uses one mutable key per order and language. The writer commits the change, then deletes the old entries. The next miss usually rebuilds the new representation. Microsoft describes this common cache-aside sequence and the reason to change the source before invalidating the copy. Now replay our paused reader. If it fills the mutable key after deletion, the old branch comes back with a brand-new expiry. Even successful deletion is insufficient for the promise we made to Mariam. Microsoft's cache-aside guidance

Follow the copies outside the service

The tablet might never contact the application if an HTTP cache can answer the request directly. For this personal order endpoint, choose Cache-Control: no-store on the response and configure the app to fetch the order when the detail screen opens. This directs compliant HTTP caches to avoid storing the exchange. It does not delete an order object the mobile app has already retained in memory. Treat that object as a previous screen state and refresh it explicitly. HTTP caching semantics, RFC 9111

There is another race on the phone itself. A slow refresh for revision 12 could arrive after the edit response for revision 13. Keep the highest displayed revision for the same order and view context and discard responses older than it. Clear private view state on sign-out and recheck permissions on the server at every fetch. This client rule helps a single screen avoid going backwards. It cannot make an independent tablet aware of yesterday's edit without contacting a current source.

For the clerk handing over the parcel, the action matters more than the display. Even a genuinely current view can become obsolete between opening the page and pressing “collected.” The handover command must check the branch, status, permissions and expected revision in the database transaction that records collection. Otherwise two perfectly fresh screens at different times can still lead to an invalid action. Caching accelerates the read; the write boundary decides whether the proposed action is still allowed.

Prove the property under an inconvenient ordering

Build a deterministic test with a reader, a writer and two synchronization points. Seed SH-481 at revision 12, empty the cache, and let the reader take its snapshot. Pause it immediately before the fill. Let the writer change the branch and commit revision 13, then release the reader. Start a third request only after both have finished. Assert its order ID, revision, locale and branch. If you switch to the mutable-key implementation, this test should expose the stale fill without depending on lucky timing or a long sleep.

Run that test with an already warm English view and a cold Arabic one. Both later requests must return Al Khan. Also test that a formerly authorized viewer is denied after access is withdrawn, even while the order body remains cached. Use a controlled clock to advance past sixty seconds and check that a miss reproduces the same content from the database. Finally disconnect the cache. A slower but correct database read is appropriate when capacity allows. If the authoritative revision lookup fails, the stated guarantee rules out silently returning a cached pickup location.

Track the cost of the remaining primary lookup and the work actually avoided on hits. Sample cache age, assembly time, fallback rate and the lag between commit and the first correct post-edit read. A high hit rate would have looked excellent in the original incident. The useful measurement is whether someone who has just changed branches gets the correct pickup address within the promised read latency. If the projection is cheap and the primary lookup dominates, simplifying the query and omitting the cache may be the better engineering decision.

اقرأ الدرس بالعربية

Exercise: locate the stale copy

At 10:01 a branch edit commits revision 14. A tablet request starts at 10:01:02, reads revision 13 from a lagging replica, and finds a revision 13 cache hit with fifty seconds left. Would reducing the expiry to five seconds meet the shop's promise? Which test would distinguish a bad revision lookup from a bad cache fill?

Answer. The replica selected the wrong revision before expiry mattered. Use a sufficiently current authoritative lookup for this endpoint. In a test, make revision 14 available on the primary while deliberately holding the replica at 13. Observe the revision selected, the key requested and the revision embedded in the returned body. Selecting 13 diagnoses the lookup path. Selecting 14 but finding a body labeled 13 diagnoses an incorrectly populated entry. The test passes when the post-commit request returns revision 14 with its agreed branch, even while the old cache entry remains present.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Find a Tail Latency Regression

Checkout barely moves at the median, but its p99 triples. Trace a missing 610 milliseconds, shorten a connection hold and decide whether to roll out the fix.

Read article ↗