Application caching Deciding what and where to cache

Application caching

Deciding what and where to cache

Deep diveAbout 12 minutes AI-generated

A cache earns its place when reusing an answer saves more work than keeping and finding that answer costs. The answer might be a database record, a product card assembled from several records, or the result of an expensive calculation. What matters is that another request can use it before it becomes unsuitable.

For the shop’s public catalogue, the choice is what to save and where to keep it. Saving a finished product card avoids more work than saving the underlying record. Keeping it inside one server makes a hit cheap, but another server cannot use that copy. The best choice depends on the requests the application actually receives.

The traces and timings below are illustrative. They show how to compare the choices; measurements of your own application decide between them.

Find the work a hit would remove

Start with one request without an application cache. The application asks the database for the mug, turns the returned data into a product card, and sends it to the caller. A hit can skip the database call. If the cached value is already the card the caller needs, it can skip assembly too.

Figure 1. Where the copy sits in the work determines what a hit can skip. Warm-cache paths are shown; common response work is omitted.

The cached record can serve several uses. A card, a product-detail page and an internal report might each build something different from it. Storing a finished card saves more of this particular request, but another use may need a different cached answer. A result computed from several products can save still more work, while depending on changes to every product that contributed to it.

Moving the reuse point therefore changes both the work saved and the number of copies to maintain. A separate card for each shop, language and currency uses more space than one record that can be transformed for several requests. Those variants also divide the requests that can share a copy. Cache keys develops the identity of an answer; here we keep the context fixed at shop north, en-GB and GBP.

The database may already cache the mug’s data pages in memory. That avoids a storage read, but a query still crosses the application–database boundary and runs in the database. An application hit can remove that call and the work after it. It does not follow that the saving is large: an indexed lookup in a nearby database may already be cheap.

Measure the existing path before choosing the copy. A trace can show whether time goes into the database call, assembly, another service or sending a large response. Source measurements can show repeated work that limits throughput even when individual requests are quick. If the uncached path meets the latency and capacity needs at an acceptable cost, keeping it is a useful decision. Fixing a wasteful query may also improve every request, including the ones a cache would miss.

The card is for display. Checkout reads the authoritative source within its normal transaction and stock checks; a source read alone does not reserve stock. Reusing the card cannot replace that decision, however much time it would save.

Look for answers that will be reused

A costly answer that nobody asks for again is a poor cache entry. Its first request pays the original work and the fill, and every later request asks for something else. A request trace makes that visible: record the identity of the answer each request needs, in arrival order.

Figure 2. Colours identify products. Each completed fill precedes the next request; this illustrative cache retains every answer.

Take eight requests in this order: mug, mug, spoon, mug, bowl, mug, spoon, mug. Start empty, let each fill complete before the next request, and keep every answer. The first request for each of the three products misses. The five later requests hit, so the hit ratio is 5 ÷ 8, or 62.5%.

Here each request asks for one card, so requests and lookups have the same count. A page asking for ten cards could have nine hits and one miss. That is a 90% lookup hit ratio, but the page still waits for a source result. Keep the unit beside the number.

A repeated request becomes a hit only while the earlier copy is still usable. Expiry, invalidation and eviction can all end that reuse. The working set is the set of answers being actively reused over the period that matters. It can change while the total catalogue stays the same size.

Requests for the same product may still need different answers. A different language or currency can require another card. Measure repetition using the complete cache key; counting product IDs alone can promise hits the real cache cannot safely provide.

Hits also save unequal amounts of work. Suppose a warm cache serves nine hits whose source lookups would each take 1 ms, followed by one miss that takes 100 ms at the source. The 90% hit ratio removes only 9 of the uncached path’s 109 ms of source work. Most work remains in that one miss. These are invented fixed costs, but the distinction is practical: count source calls and the work they would have done.

Retention and correctness constrain each other. Keeping a copy longer may improve reuse while letting it drift further from the source. Decide what an acceptable answer means before extending its lifetime. Freshness and invalidation develops that promise, and Cache memory and eviction explains which useful copies can fit.

Count the cost of both paths

A hit avoids source work. A miss adds work: it first checks the cache, then reads the source and saves a copy. Suppose a lookup takes 2 ms, the source work takes 20 ms and a fill takes 3 ms. A hit costs 2 ms; a miss costs 25 ms against the uncached 20 ms. These invented times are constant, with one lookup per request and no queueing.

Figure 3. Invented constant times, with one lookup per request and no queueing. Teal is lookup work, blue source work and gold a fill. The dots show hits in teal and misses in coral.

Across twenty requests with sixteen hits and four misses, the mean is (16 × 2 + 4 × 25) ÷ 20 = 6.6 ms. The common hit pulls the mean down, but each miss still takes 25 ms. A faster average has come with slower misses.

A percentile describes a point in the ordered request times. Using the nearest-rank definition, p95 is the nineteenth of twenty requests: 95% finish in that time or less. With sixteen hits, the nineteenth is a 25 ms miss. With nineteen hits and one miss, it is a 2 ms hit. The remaining miss is just as slow in both workloads.

That calculation uses the twenty individual times, sorted from fastest to slowest. It is not a way to derive p95 from a mean. Real hits and misses each have their own spread of times, and a slow hit can overlap a quick miss. Measure the complete request distribution, including failures and timeouts separately, when judging the application.

The mean is useful for an earlier calculation. Call the cache lookup and checks C, the source work S, the fill W, and the hit fraction h. A fraction h pays C; the rest pays C + S + W. Adding those contributions gives C + (1 − h)(S + W).

With the 2 ms lookup, 20 ms source and 3 ms fill, the cache saves mean time only when 2 + (1 − h) × 23 < 20. That needs a hit ratio above about 21.7%.

Now suppose a source improvement reduces its work to 2 ms while the cache costs stay the same. A miss takes 7 ms. Sixteen hits and four misses give (16 × 2 + 4 × 7) ÷ 20 = 3 ms, slower than 2 ms uncached. The lookup now costs as much as the work it replaces; only a perfect hit ratio draws level.

Saving source capacity is a different result. Sixteen hits still remove sixteen source calls in that second case, even though the mean request time grows. That may be worthwhile when source capacity is the constraint. Count CPU, reads or downstream charges as appropriate; milliseconds from concurrent calls are not milliseconds of wall-clock time saved by the whole service.

The model holds source time constant. A real database can respond faster when caching reduces its queues, or become slower when many misses arrive together. Cache clients can queue too. These effects can change both paths, which is why arithmetic narrows the choices and an experiment decides between them.

Choose where the copy lives

An in-process cache keeps entries in the application’s own memory. A lookup need not cross a network, and it can return an object the application can use directly. Each process owns its memory, though. If Server A fills an entry and the next request reaches Server B, B cannot read A’s copy.

A shared cache puts the copy in a service both servers can reach. A’s fill can then serve B. Every hit pays for communication with that service, and both servers depend on its availability.

Separate copies can also have separate lifetimes. Suppose A fills the GBP 20.00 card at time zero and B fills it ten seconds later. Each copy has a thirty-second insertion lifetime. At twenty seconds the source price becomes GBP 22.00, with no invalidation.

Figure 4. A close-up of the copies held by the two arrangements. Requests fill A at 0 s and B at 10 s; A requests again at 31 s. Only expiry is used, with a 30-second lifetime from each fill.

A’s copy expires at thirty seconds, while B’s lasts until forty. A request to A at thirty-one seconds reads GBP 22.00 from the source and saves it. B can still return GBP 20.00. A reader routed from A to B could see the price go backwards: local expiry does not coordinate the servers.

The shared copy gives either server access to A’s completed fill. It is still separate from the source, so it can be stale too. Sharing reduces duplicate work; it does not establish a freshness guarantee. Freshness and invalidation follows concurrent reads and delayed fills.

Process lifetime adds another difference. Restart A and its local entries disappear. Add ten application processes and each starts without the copies held by the others. A shared service can retain its entries across those application changes, while its own restart or failure can affect the whole fleet. AWS’s account of operating caches describes the cold-load problems this creates.

A library such as Caffeine is a concrete in-process choice for Java applications. It manages bounded memory and expiry inside the process. Redis, Valkey and Memcached are shared-store choices for this kind of application data. Memcached’s simple key/value model is enough to store a finished card; Redis and Valkey also offer server-side data operations that some cache designs need. Choose those capabilities when the design uses them, alongside client support and the deployment you can operate.

Memory and transfer costs follow the placement. If twenty local caches retain the same card, the fleet holds twenty copies, with each library’s object overhead. A shared design can reduce that duplication, but its deployment may keep replicas and each lookup transfers the value. A large card requested constantly can make transfer and decoding a significant part of the hit. Measure the actual stored and transferred representation.

When a second layer earns its place

Sometimes a shared cache is doing useful source protection but the same few cards account for repeated remote lookups. A small local cache in front of it can remove those trips. Follow the counts through both layers before adding one.

Suppose 100 card requests arrive. The local layer answers 80, so only 20 reach the shared layer. The shared layer hits on 15 of those 20, leaving five source reads. Its hit ratio is 75% of the requests it receives. Across the original 100 requests, the two layers answer 95: 80% + 20% × 75% = 95%. Adding 80% and 75% would count different populations as though they were the same.

Those 80 local hits never ask the shared cache whether its answer changed. Removing a shared entry leaves local copies untouched unless the design also handles them. Copying a value into a local layer must not silently restart its permitted data age. Add the layer only when the remote work it removes justifies another memory budget and another freshness problem. The freshness article owns those mechanisms.

Test the workload you expect

The shop now has a candidate: store assembled public cards in a shared cache, so any application instance can reuse a fill. The examples give a reason to try it, but do not establish its network cost or the traffic a cold source can sustain. Compare that candidate with the uncached application and, where local reuse looks promising, an in-process version.

Use the same request mix and offered load for each. Preserve key popularity, card sizes, language and currency variants, and the timing of source updates. Run at expected concurrency and from the network locations the application will use. A loop that sends another request only after the last finishes can reduce its load as the system slows; record the arrival rate as well as the achieved completion rate.

Start with an empty cache and keep the warming period in the results. Then let the useful set settle, change which products are popular, and make the cache unavailable. Each phase can overturn a different part of the expected saving.

One candidate through four workload phases
PhaseWhat to keep beside latencyWhat would weaken the choice
Cold startSource attempts, admitted work and time until useful hits returnThe source overloads before the cache warms.
Repeated requestsUsable hits, source work avoided, cache lookup and fill costsCache overhead consumes the expected saving.
New popular productsMisses and source work while old entries still occupy memoryThe warm result depended on a popular set that no longer exists.
Cache unavailableWaiting time, errors and source work allowed throughFallback creates more source work than it can safely serve.

A cold cache and an unavailable cache are different tests. A cold cache can accept fills and gradually improve. An unavailable one may keep failing and add a wait to every request. If the warmed design needs the cache to keep source demand within capacity, losing it cannot simply send every request to the source. Handling cache misses develops the limits and coordination that make that path bounded.

Keep complete application latency distributions beside the source and cache measurements. Count an entry as a useful hit only when the application can return its answer. A value that is found but rejected for the wrong format or age is not saved source work. Test the freshness requirement through the update phases too: a fast wrong answer is a failed experiment.

A command benchmark answers a narrower question. Redis’s benchmark documentation explains how payload size, connections and network conditions affect its results. A fast GET under those conditions does not include this application’s decoding, source misses, fills or response. Use command measurements to understand a component after measuring the whole request.

Make a decision you can revisit

For the invented shop, the evidence so far favours testing one shared cache of assembled cards. The requests can share complete answers, and separate processes otherwise repeat fills. It does not yet justify a second local layer. That would need measured remote lookup cost and enough repeated requests within each process to recover its added complexity.

The decision record should name what the experiment must achieve. For example, the shop could require fewer source reads at its expected load, no regression in its agreed slow-request target, and acceptable display prices during updates. It must also specify the actual age or version promise and what happens when the cache cannot answer. A 30-second insertion TTL alone does not settle those requirements.

Compare the saved source capacity with the memory, transfer and service cost of the cache. Include the work of keeping copies valid, maintaining the client path and recovering from failures. A shared service that saves many source calls can still cost more overall than a small source improvement. An in-process cache that looks free can increase application memory enough to change the number or size of instances.

Test the candidate on a limited share of traffic with those acceptance conditions recorded in advance. Include the source demand caused by the trial itself, and keep a stop condition for latency, incorrect answers or excess source work. A return to the uncached path also needs a source budget; removing the cache is not a safe rollback if the source can no longer carry that traffic.

A changed request mix, a cheaper source query or larger cached answers can overturn the choice later. Keep the measurements that would reveal each change. Operating a cache follows that evidence in production. To build the candidate, continue with keys and values, the freshness promise and the memory budget, then the worked Redis implementation.

Sources and further reading

Checked 28 October 2026. The figures and numerical examples are bounded models, not performance observations from these products.

← Back to application caching