Application caching Application caching

Application caching

Application caching

IntroductionAbout 11 minutes AI-generated

An application cache saves an answer so that a later request can reuse it. A shop can read a product’s name and price from its database once, save the product card, and return that copy to the next hundred readers. Those readers avoid the source lookup and the work of building the card again.

The saving comes with another copy to manage. The database can change while the saved card stays the same. The cache can fill up, lose entries or stop answering. The application must still know which requests may share a card, when the card is too old, and how much work it can send to the source when no useful copy is available.

Every example follows one invented shop. In shop north, product P7 is a blue mug priced at GBP 20.00. Later, its price rises to GBP 22.00. The catalogue is public, and the cached card is for display. Checkout reads the authoritative source within its normal transaction and stock checks; a cached card does not authorise a sale.

Redis supplies the worked shared cache in this collection. The decisions begin before choosing it: the same questions arise with another shared store or a cache inside the application process. We start with one request and one saved card.

Reusing an answer

A cache entry pairs a key, the name used to find an answer, with a value, the saved answer itself. For P7, the key identifies a particular product card and the value holds its display name and price. The application asks for the key before doing the source work.

Suppose no card has been saved for P7 yet. The server reads its name and price from the database, combining the relevant product and price records. It builds the card, saves a copy under P7’s key and returns the answer to the caller.

Figure 1. One request misses, reads the database, saves P7’s answer and returns it to the app. The copy stays in the cache, ready for reuse. Motion and timing are illustrative.

A lookup without a saved answer is a miss. A later lookup that finds the usable copy is a hit; it can return the saved answer without reading the database again.

This arrangement is called cache-aside. The application’s server sits beside the cache and decides when to read the source and fill the cache. Neither the source nor the cache performs those steps for it. A library can wrap the sequence in one function, but the same decisions still exist.

The database may already keep its storage pages in memory. That saves disk reads inside the database. An application cache saves a different piece of work: the request to the database, the query it runs, and any assembly already included in the cached answer. A database page in memory is not a ready-made product card.

The source remains responsible for accepted changes. Losing every cached card loses an optimisation, not the product catalogue. Rebuilding those cards still takes source work, however, so being able to reconstruct the data does not mean being able to serve every request during a cache failure.

What a hit saves

Suppose reading and assembling a card takes 20 ms. A shared-cache lookup takes 1 ms and saving a new copy takes another 1 ms. These are invented times, held constant to make the paths visible. They leave out work common to every request, such as receiving and sending HTTP.

Work for one product-card request in the illustrative workload
PathWork in orderElapsed timeSource reads
No cacheRead and build the card20 ms1
Cache hitLook up the saved card1 ms0
Cache missLook up, read and build, save22 ms1

With 90 hits and 10 misses in 100 requests, the mean time for this work is 3.1 ms: (90 × 1 + 10 × 22) ÷ 100. The source receives ten reads instead of a hundred. But each miss takes 2 ms longer than the uncached path. A cache has made the common request cheaper while adding work to the uncommon one.

The fraction of lookups that hit is the hit ratio, 90% here. It helps describe reuse, but it does not say what that reuse saved. Avoiding a 20 ms calculation matters more than avoiding a trivial lookup. If every request asks for a new answer, all hundred miss and the cache adds cost throughout.

Placement changes that cost. A local cache lives in the memory of one application process. It avoids a network trip, but another process cannot see its entries. A shared cache is a separate service that several processes can ask.

The shop also has products P8 and P9. Each needs its own cached card: P7’s answer cannot serve P8.

Now run two server processes, A and B, behind a load balancer that routes requests to either one. Each server receives requests for all three products. Assume each fill finishes before the next request, and the useful copies remain available.

Figure 2. The same products now reach two servers. A local copy in A cannot prevent B’s miss. A shared copy can. Each key’s fill finishes before it is requested again here: six misses locally, three shared. Once warm, both arrangements hit. No expiry or eviction; timing is illustrative.

With local caches, A filling P7 does nothing for B. Each process must fill P7, P8 and P9: six misses altogether. With a shared cache, either server can reuse each completed fill: three misses. Once every needed copy is warm, both arrangements hit. Sharing avoids duplicate cold fills here; it does not make every possible workload cheaper.

Each local process consumes memory for its own copies and can hold different versions. A shared cache avoids those separate copies, but both servers now wait on another service for each lookup, including its network and connection delays.

A local cache is a plausible starting point when repeated work stays within one process. Sharing is useful when reuse is spread across many instances or duplicating the useful data costs too much memory. An adequate source query may need no application cache at all. Deciding what and where to cache develops the measurement and placement decision, including when a second cache layer earns its extra complexity.

Which requests can share an answer

So far, each product ID has named one answer within shop north. Using P7 alone as the key works only while it keeps naming that same answer. Suppose another shop, south, also has a product P7, priced at GBP 18.00. A key containing only the product ID lets the south request find north’s card.

Figure 3. Both lookups hit. Only the key that includes the shop finds the right answer. Keys are shortened here; language, currency and format stay fixed.

The wrong answer is a successful cache hit. Nothing timed out, and the source did not change. The application simply gave two different questions the same name.

The complete key in this collection is product:v1:north:P7:en-GB:GBP. It names the product-card format, shop, product, language and currency. Changing the shop or the requested representation can change the answer, so it changes the key. The source and application supply that representation; Redis does not translate a name or convert a price.

The v1 part names the value’s format. It is separate from revision: 1, which records the source product version. Raising the price produces revision 2 in the same format. Changing the meaning or structure of the stored fields may require a new format.

Not every request difference belongs in the key. Two readers of the same public card can share it; their request IDs need not create separate entries. A personalised answer may need a different boundary. Cache keys works through those choices, including permissions, query parameters and how to represent a product that the source says does not exist.

When the source changes

Now return to north’s card and raise the source price to GBP 22.00. The cached GBP 20.00 was once the right answer. It is now stale: it describes an earlier source state. Whether it remains acceptable depends on the use. A browsing page may allow a short delay; checkout must make its decision through the source’s transaction and stock rules.

One way to end reuse is expiry. Give the entry a time to live, or TTL, and lookups stop returning it when that time ends. Our example uses 30 seconds from insertion. Expiry does not fetch a replacement: the next miss still has to do that work.

Another way is invalidation: remove a copy because something has made it unsuitable. After committing the price change, the server deletes the cached card. Until that deletion finishes, the source says GBP 22.00 while the cache can still return GBP 20.00.

Figure 4. Commit £22, delete the old copy, then refill on the next miss. The purple pulse is the deletion; the coral ball is a later read. These are separate operations, with no overlapping read in this example.

The deletion happens after the source commits. Deleting before commit would let a request miss, read the old source price and save it again. With commit first, the next ordinary miss can read the new value.

There are still two separate operations. If the application stops after commit but before deletion, the source keeps GBP 22.00 and the cache can keep GBP 20.00. A reader can also obtain GBP 20.00 before the commit, then save it after the deletion. Commit-then-delete handles the simple sequence, but does not prevent that overlapping read from restoring an old card.

A 30-second TTL limits how long this insertion can be reused. It does not prove that its source data is at most 30 seconds old: the read may have taken time before insertion or observed an older source snapshot. Freshness and invalidation follows those gaps, defines the freshness promise and shows when reading the source is the clearer solution.

When requests arrive together

A popular product can receive several requests while one fill is still running. If four requests arrive just after P7 expires, all four can miss before any of them saves a replacement.

Without coordination, each caller starts its own source read. With a shared fill, the first caller starts the read and the other three wait for its result. Either arrangement still owes all four callers an answer.

Figure 5. Four requests leave the app; four answers return. Sharing the fill inside one server process avoids three database reads. Waiting must be bounded in a real service.

The four independent reads are a small cache stampede: several requests rebuild the same missing answer at once. Sharing that work is called request coalescing. It reduces the source reads from four to one without reducing the number of callers.

That sharing needs a boundary. Combining work inside one server process does not stop another process from starting its own fill. A slow or failed fill also needs a bounded wait, so callers cannot accumulate indefinitely. Those details become part of the application’s miss path.

Now imagine the entire cache is empty. The misses may be for thousands of different products, leaving little work to combine. At 1,000 card requests a second, a warm cache with 90% hits sends 100 reads a second to the source. If every request misses, it can send 1,000. This tenfold increase is an illustration, not a measured capacity limit.

The source also has checkout and other work that the card cache never removed. If it cannot absorb the extra reads, unrestricted fallback can overload it. The application needs a limit on admitted source work and a defined response when that limit is reached. A timely failure can preserve capacity for requests that can still succeed.

Handling cache misses builds that path: sharing fills, bounding waits, refreshing useful copies and controlling work during cache loss. These questions matter even when the normal hit ratio looks excellent, because a daily average can hide a damaging burst.

When the cache fills

A cache has room for only some answers. When a new answer needs space, it can remove a resident entry: eviction. That is different from expiry. A card can still be within its TTL and be evicted because another entry needs its memory.

Figure 6. The least recently used card leaves, making room for the new arrival. Width shows memory use. This is an illustrative sequence; no entries expire.

One choice is to remove the least recently used card: the one that has gone longest without being used. This rule uses access history, rather than simply choosing the largest card. A later request for the removed card must read the source again.

Eviction policies use clues such as recent or frequent access to choose what leaves; they cannot know the next request. There is also an earlier choice: whether to save a returned card at all. That is admission. Skipping a rarely reused card can avoid displacing a useful one, but being large does not by itself make a card a poor choice.

The useful set changes as readers move through the catalogue. More memory helps when it retains answers that would otherwise be rebuilt; storing the whole catalogue is not automatically useful. Cache memory and eviction develops the byte budget and compares policies against changing request traces, then applies the choices to Redis’s memory controls.

Using Redis for the worked cache

Redis can supply the shared cache by storing an encoded product card as a string value under its complete key. GET reads it, SET stores it, and DEL removes it. The EX option on SET sets an expiry in seconds as part of the same command.

GET product:v1:north:P7:en-GB:GBP

SET product:v1:north:P7:en-GB:GBP '<encoded card>' EX 30

DEL product:v1:north:P7:en-GB:GBP

The middle line shows the command’s shape; <encoded card> stands for the application’s serialised value. It is not a useful card to paste into a real cache. The application reads the source on a miss, builds the value and issues that command. Redis has no knowledge of the product database behind it.

A cache failure and a miss are different outcomes. A miss says the lookup completed without a value. A failure may say nothing about whether the value exists. If the source read succeeds but saving the copy fails, the application still has the card to return. If the source read fails, it has no basis for inventing a card or claiming the product is absent.

Caching with Redis turns this command sequence into a runnable adapter. It validates values, reuses client connections and keeps cache waits within the request’s time budget. Redis is one choice for this job; Valkey and Memcached are other shared stores, and language libraries provide local caches. Their capabilities differ, but none chooses the product’s acceptable freshness for the application.

Keeping the cache useful

Once the cache is running, its hit ratio is only one part of the result. Consider two invented one-minute observations of the same card service. In both, every miss reaches the source once.

The same hit ratio with different source demand
ObservationEarlierLater
Card requests per second1,0002,000
Cache hit ratio90%90%
Source reads per second100200
95% of card requests finish within30 ms90 ms
Cache errors00

The cache still answers nine lookups in ten, but traffic has doubled and source demand has doubled with it. The slower requests need investigation. The table alone cannot say whether the extra wait is in the source, the cache client or another part of the application. Tracing those paths gives the latency figures their meaning.

Answers need checking too. A fast cache can keep serving GBP 20.00 after the shop’s freshness allowance has ended. Neither a low latency nor a high hit ratio establishes that the result is still acceptable.

Operating a cache joins these observations into diagnosis and controlled changes. It also rehearses a cold or unavailable cache, because warm performance is only one mode of the service.

For the product card, a workable design now has a clear shape. Repeated reads can share an answer with a complete identity. Its permitted age determines when reuse ends. Misses receive a bounded share of source capacity, and entries earn their memory through useful reuse. The deeper articles develop each decision far enough to implement and test it.

Sources and further reading

The shop, timings, request rates and byte budgets are illustrative. The drawings model application decisions; they do not run Redis or measure a database.

  • Microsoft, Cache-Aside pattern: the lookup, source-read and fill sequence, update ordering and limitations of independent copies.
  • Redis documentation: GET, SET, DEL and EXPIRE, for command behaviour and entry lifetimes.
  • Redis, Key eviction: memory limits and removal policies for disposable cached data.
  • Amazon Builders’ Library, Caching challenges and strategies: cold caches, request coalescing and maintaining bounded dependency work when a cache is unavailable.