Application caching
Cache memory and eviction
A full cache has to choose. Keeping the next answer may mean removing one that another request will soon need. The useful question is therefore not how many answers fit, but which answers save enough source work to deserve their space.
The shop’s catalogue still holds every product. Its cache needs only the copies worth keeping. We will give those copies a small memory budget and follow how changing demand affects the choice. Redis supplies a concrete example later in the article; the same questions apply to other cache implementations.
The catalogue, the working set and the cache
A shop may list thousands of products while most customers look at the same few. Repeated requests can benefit from a cache much smaller than the catalogue.
For example, six requests alternating between a mug and a jug need only those two answers. After their first fills, retaining both is enough for the remaining four requests to hit. Loading unrequested products would save no further source work for that workload.
The working set is the set of answers in active use over an interval. Choose the interval when measuring it: a minute of lunchtime traffic may use a different set from a day of catalogue browsing. Within that set, repeated answers usually earn their space more readily than answers requested once.
The cache’s resident set is what it actually holds now. That can include yesterday’s popular products and omit today’s. A promotion might shift demand from mugs to bowls without changing the catalogue’s size. Retention rules try to make the residents follow useful demand.
Count complete answer identities. The mug in another language or currency is another cached card, even though it is the same product. Cache keys explains that boundary. Here the representation stays fixed, so a product name can stand for one complete card identity.
What one entry costs
The stored value is only part of an entry. The cache also holds its key and enough information to find it, expire it and choose whether to keep it. Its memory allocator may reserve a larger block than the entry needs. An in-process cache also pays for the objects and references that make up its representation.
A small value can therefore cost more memory than its encoded bytes suggest. Add the key, value, tracking information and allocation overhead when estimating its budget. Actual costs depend on the implementation and representation.
A limit of three entries would admit either three small cards or three large results. A limit in bytes distinguishes them. A catalogue-list result might occupy the room of several product cards. If it is used once, keeping it may buy nothing while displacing several useful copies.
Estimate from representative groups of answers. Sample ordinary cards, cards with longer names or extra fields, cached absences and larger derived results. Include the complete keys and the format actually stored. Multiplying every entry by one mug card’s size hides the larger answers and any different allocation costs.
A narrower representation can leave room for more useful copies. Storing only the fields the card needs avoids carrying a full product description on every hit. Compression can reduce stored and transferred bytes, but adds compression on fills and decompression on hits. A maximum entry size is simpler: return an oversized source result without caching it. Its later requests still pay the source cost.
Leave room for the rest of the process
Measuring every entry still leaves part of the process unaccounted for. Connections need buffers. Commands and encoding need temporary memory. An allocator can retain pages after entries are removed. Replication and persistence, when enabled, add their own activity. The host or container also needs room beyond the cache process.
A cache allowance is therefore not a promise about total resident memory. Measure the process under the intended connection count and request sizes, including large fills and any enabled background work. Repeat after churn: fill entries, remove many, then refill with different sizes. The remaining gap to the host limit must cover the peaks this deployment can reach.
There is no useful universal headroom percentage. A small cache with many clients and a large cache with few clients do not have the same proportions. Choose an entry budget that fits the measured process, then check that it still saves enough source work. For a local cache, include the application’s other allocations in that same exercise.
Expiry does not reserve a place
Expiry makes a copy unusable when its lifetime ends. Eviction removes a resident to make room. A card can be evicted while it would still be acceptable to return, so a 30-second TTL does not promise 30 seconds of hits.
The application must handle both as misses. Eviction loses a reusable answer, not an accepted product change: the source still owns the product. This is why the same eviction budget should not hold irreplaceable application state.
Logical expiry and physical reclamation are separate events. An implementation can reject an expired entry at lookup and reclaim unused expired entries during background work. Memcached, for example, documents both lookup-time checks and background reclamation. Reaching a deadline need not return all the associated memory to the operating system at that instant.
Shortening the TTL may reduce retained data, but it can also remove a card just before its next request. That increases source work even when the cache had room to keep it. Choose expiry for the answer’s permitted lifetime, and enforce a memory budget separately. The shared 30-second insertion TTL is not an unconditional source-age guarantee; Freshness and invalidation explains that promise.
Decide what enters and what leaves
An eviction policy chooses residents to remove. An admission policy decides whether an incoming answer should be stored at all. These are different decisions. The source result can be returned to the caller even when the cache declines to keep it.
Popularity can change while the catalogue stays the same. To compare retention rules, use one invented sequence of eighteen requests. The answers are five cards, named mug, jug, spoon, bowl and vase, plus a larger catalogue result. Start with an empty 3 KiB cache. Each card occupies 1 KiB, including the model’s overhead; the catalogue result occupies 3 KiB.
The requests arrive in four phases:
| Phase | Requests in arrival order |
|---|---|
| Repeated favourites | mug, jug, mug, jug, mug, jug |
| Browsing | catalogue, vase |
| Favourites return | mug, jug |
| New popular cards | spoon, bowl, spoon, bowl, spoon, bowl, spoon, bowl |
Every fill finishes before the next request. There are no updates, expiry or failures. These charged sizes describe the example, not Redis allocations.
Model assumptions and the default trace
This is an invented sequential trace. Each product card costs 1 KiB; the catalogue result costs 3 KiB. A miss costs two source-work units, except the bowl (12) and the catalogue (20). The units are illustrative costs, not measured latency. Each fill completes before the next request; there are no updates, expiry or failures. Charged sizes include the model’s overhead and are not Redis measurements.
LRU removes the resident with the oldest last access. LFU counts uses since admission, including the fill, and removes the lowest count; ties use LRU. Its counts never decay. Second request admits a key seen in the preceding eight requests, then uses LRU. That bounded history costs memory outside the entry budget. An answer exceeding either size limit is returned without being stored.
- Mug misses. Read the source (2 work units). Keep Mug, charging 1 memory unit. Residents: Mug. Hits: 0; source reads: 1.
- Jug misses. Read the source (2 work units). Keep Jug, charging 1 memory unit. Residents: Mug, Jug. Hits: 0; source reads: 2.
- Mug is a hit. Reusing it avoids 2 units of source work. Residents: Mug, Jug. Hits: 1; source reads: 2.
- Jug is a hit. Reusing it avoids 2 units of source work. Residents: Mug, Jug. Hits: 2; source reads: 2.
- Mug is a hit. Reusing it avoids 2 units of source work. Residents: Mug, Jug. Hits: 3; source reads: 2.
- Jug is a hit. Reusing it avoids 2 units of source work. Residents: Mug, Jug. Hits: 4; source reads: 2.
- Catalogue misses. Read the source (20 work units). Evict Mug, Jug to make room. Keep Catalogue, charging 3 memory units. Residents: Catalogue. Hits: 4; source reads: 3.
- Vase misses. Read the source (2 work units). Evict Catalogue to make room. Keep Vase, charging 1 memory unit. Residents: Vase. Hits: 4; source reads: 4.
- Mug misses. Read the source (2 work units). Keep Mug, charging 1 memory unit. Residents: Vase, Mug. Hits: 4; source reads: 5.
- Jug misses. Read the source (2 work units). Keep Jug, charging 1 memory unit. Residents: Vase, Mug, Jug. Hits: 4; source reads: 6.
- Spoon misses. Read the source (2 work units). Evict Vase to make room. Keep Spoon, charging 1 memory unit. Residents: Mug, Jug, Spoon. Hits: 4; source reads: 7.
- Bowl misses. Read the source (12 work units). Evict Mug to make room. Keep Bowl, charging 1 memory unit. Residents: Jug, Spoon, Bowl. Hits: 4; source reads: 8.
- Spoon is a hit. Reusing it avoids 2 units of source work. Residents: Jug, Spoon, Bowl. Hits: 5; source reads: 8.
- Bowl is a hit. Reusing it avoids 12 units of source work. Residents: Jug, Spoon, Bowl. Hits: 6; source reads: 8.
- Spoon is a hit. Reusing it avoids 2 units of source work. Residents: Jug, Spoon, Bowl. Hits: 7; source reads: 8.
- Bowl is a hit. Reusing it avoids 12 units of source work. Residents: Jug, Spoon, Bowl. Hits: 8; source reads: 8.
- Spoon is a hit. Reusing it avoids 2 units of source work. Residents: Jug, Spoon, Bowl. Hits: 9; source reads: 8.
- Bowl is a hit. Reusing it avoids 12 units of source work. Residents: Jug, Spoon, Bowl. Hits: 10; source reads: 8.
Least recently used, or LRU, removes the entry whose last use is furthest in the past. The model counts filling an entry as a use.
With LRU and no smaller entry limit, the 3 KiB catalogue result evicts both favourites. The vase then evicts the catalogue, so the returning mug and jug each miss. Limiting entries to 1 KiB instead skips the catalogue fill. The vase fits beside mug and jug, preserving both for their next requests. That choice avoids two reads; it would be a different trade if the large result returned often enough to repay its space.
This is admission to the cache, after obtaining an answer. It does not protect the source from the request that produced that answer. Limits on how much missing work may run belong to Handling cache misses.
Recent use and frequent use
LRU’s bet is that a recently requested answer is likely to be requested again. A scan can defeat that bet: each new answer looks recent and can replace a repeatedly useful one.
Least frequently used, or LFU, favours entries with more uses. Keep the 1 KiB entry limit for this comparison. The mug and jug each accumulate four uses before demand changes, including their fills. LFU protects them when the spoon and bowl arrive. When counts are equal, this model evicts the least recently used candidate.
The spoon and bowl then compete for the remaining space. Each leaves before its next request, so neither gains the resident use count needed to displace the old favourites. The policy keeps rewarding demand that has ended.
This simple frequency rule deliberately never forgets. A practical policy needs to reduce the influence of old requests, through decay or a recent history. Redis’s LFU uses decaying estimated counts. Its LRU and LFU sample candidates rather than choosing the exact least-used resident in this example. The same request history therefore cannot predict Redis’s next eviction.
The third rule, Second request, keeps a new answer only if its key appeared in the preceding eight requests. Once admitted, an answer follows LRU for eviction. One-off browsing never enters the cache, so it cannot displace the favourites. The price is slower adaptation: a newly popular answer must miss twice before its third request can hit.
A reuse filter must remember something about answers it did not store. The model keeps eight request identities outside its entry budget. That history also needs bounded memory in an implementation. Caffeine’s Window TinyLFU design combines a window for recent arrivals with estimated frequency when competing for longer retention. It makes a more nuanced decision than this second-request rule, with bookkeeping of its own.
None of these rules knows the next request. Recent use adapts quickly but can follow a scan. Frequency can resist that scan but remember old popularity too long. Requiring reuse can reject one-off answers while delaying new useful ones. Judge the combination on the changes your workload actually contains.
Count the work saved by the space
Hit count treats every answer as equally valuable. A card that needs a costly join may save much more work per hit than a cheap lookup. Assign each ordinary card read two source-work units, the bowl twelve and the catalogue twenty. These are illustrative costs, not measured milliseconds. The eighteen uncached requests would cost 94 units in total.
With the 3 KiB budget, LRU and a 3 KiB entry limit, ten requests hit and save fifty units. The first four repeated mug/jug reads save eight; three spoon hits save six; three bowl hits save thirty-six. The large catalogue and vase never hit.
| Answers | Space when resident | Hits | Work saved |
|---|---|---|---|
| Mug and jug together | 2 KiB | 4 | 4 × 2 = 8 |
| Spoon | 1 KiB | 3 | 3 × 2 = 6 |
| Bowl | 1 KiB | 3 | 3 × 12 = 36 |
| Catalogue and vase | 3 KiB and 1 KiB | 0 | 0 |
The mug and jug produce more hits than the bowl, yet save less work while occupying twice as much space together. A policy that improves the overall hit ratio could still lose the expensive hits. Keep source cost and entry size beside request frequency when evaluating it. Also count the cache work those hits require, as Deciding what and where to cache does.
A byte or weight limit does not itself optimise work saved per byte. Caffeine, for example, can constrain entry count or a supplied weight, but its documentation says relative weights do not select eviction victims. A weight bounds occupancy; deciding which answer earns that occupancy is another part of the design.
Put the budget into Redis
For Redis, set maxmemory and choose maxmemory-policy explicitly. The following configuration illustrates a disposable cache with a 64 MiB allowance. That number is a starting point for an experiment, not a size recommendation.
# Configuration for an owned disposable Redis instance
maxmemory 64mb
maxmemory-policy allkeys-lru The allkeys- policies can remove any key. The volatile- policies consider only keys with an expiry; without eligible keys, they cannot make room. noeviction retains keys and rejects writes that need more memory, while reads can continue. Keep state that must survive outside this disposable budget. Redis’s eviction documentation defines the full policy set.
The collection’s native lab forced the refusal path on Redis 8.10.3 by selecting noeviction and lowering maxmemory to one byte. A new SET … EX 30 then returned an OOM error. The application still held its successful source result: the mug at revision 2, GBP 22.00. It could return that result despite the failed fill.
This deliberately impossible limit tests error handling. It does not measure how many cards a useful cache can hold, or prove any eviction policy’s quality. The source in this experiment was a Python dictionary; the Redis rejection was observed on an owned local instance. Caching with Redis provides the runnable lab and the application adapter that keeps the source result when an optional fill fails.
Measure entries and the process separately
After loading representative answers into a disposable instance, inspect both a key and the process:
MEMORY USAGE product:v1:north:P7:en-GB:GBP
INFO memory
INFO stats
INFO commandstats MEMORY USAGE reports allocations for the key, value and administrative overhead. For nested data types it samples elements by default; SAMPLES 0 examines all of them. Repeat across the size groups, and record the Redis version, encoding and allocator with the results. The illustrative 1 KiB card budget is no substitute for those measurements.
| Field | What it tells you |
|---|---|
used_memory | Bytes Redis has allocated through its allocator. |
used_memory_dataset | That allocation total with Redis’s reported management overhead subtracted. |
used_memory_rss | The process’s resident memory as seen by the operating system. |
mem_not_counted_for_evict | Memory excluded from the eviction calculation. |
Summing per-key estimates does not account for the whole process. Nor does a high ratio of RSS to allocated bytes prove allocator fragmentation: process overhead contributes too. Look at the byte amounts, the allocator fields and how they change through the load.
Some replication and AOF buffers are excluded from Redis’s eviction calculation. Large operations can also exceed the configured allowance temporarily. Leave measured headroom beyond maxmemory, and check the whole deployment during its enabled persistence or replication work.
The accounting changes with the implementation. Memcached places items into allocation size classes, so a slightly larger value can need a larger chunk. A local Caffeine weight limit reflects the application’s weight function, not an automatic measurement of the Java heap. Use the implementation’s measurements to connect the abstract entry budget to actual memory.
Check the choice against changing requests
Start with a trace of complete keys, arrival times, answer sizes and source costs. Record updates, invalidations and expiry as well: a repeated key cannot hit if its previous copy is no longer usable. Keep the cold start in the trace and include periods of steady demand, scanning and changed popularity.
Hold those inputs fixed while changing one choice. Return to the eighteen requests above, keep LRU and the 1 KiB entry limit, and compare memory budgets. With 2 KiB, the vase displaces a favourite and the returning favourites need refilling. With 3 KiB, all three small cards fit through that interval.
| Budget | Hits | Source work remaining | Work saved |
|---|---|---|---|
| 2 KiB | 10 | 44 | 50 |
| 3 KiB | 12 | 40 | 54 |
| 5 KiB | 12 | 40 | 54 |
| 8 KiB | 12 | 40 | 54 |
Moving from 2 to 3 KiB lets the mug and jug survive the vase request, saving two more reads and four work units. Going to 5 or 8 KiB saves nothing further on this trace. Every remaining miss is the first request for its answer, including the catalogue result, which the size rule excludes. More room cannot remove those first source reads.
Now hold 3 KiB fixed and compare policies. With the same entry-size limit, the model’s LFU saves only 12 work units because it keeps the old popular cards. Second request saves 36, and LRU saves 54. Those results select a candidate for this trace; they do not rank the algorithms for every workload.
Replay production-shaped requests against the chosen implementation on a disposable deployment. Preserve concurrency and arrival timing, and measure application latency, useful hits and source work as well as memory. A sequential model cannot reproduce delayed fills, concurrent requests or Redis’s sampled victim choices. Compare repeated runs rather than treating one exact eviction order as a requirement.
Read counter differences over the same interval. In Redis, evicted_keys and expired_keys distinguish two reasons entries leave. Command rejection counts and application fill failures expose another reason useful copies never arrive. The application must still decide whether a found value is usable; a server hit is not necessarily saved source work.
Write down what would overturn the choice. If extra memory removes few source reads, reconsider buying it. If a size limit repeatedly rejects expensive reusable answers, change the representation, threshold or allocation between answer types. If old popularity dominates after a shift, test a policy that forgets faster. If process peaks approach the host limit, reduce the budget or change the deployment before relying on a healthy hit ratio.
For this invented trace, 3 KiB with LRU and a 1 KiB entry limit is enough to capture all the available repeated reads. A real choice needs the same argument with measured bytes and a representative history. Operating a cache carries those measurements into diagnosis, rollout and recovery as requests continue to change.
Sources and further reading
Checked 28 October 2026. The replay and byte diagrams are illustrative models. The noeviction refusal was observed on local Redis 8.10.3; its source was an in-process Python dictionary. No native memory sizing or eviction-quality result is claimed.
- Redis, Key eviction: limits, eligibility, approximate policies and excluded buffers.
- Redis, MEMORY USAGE and INFO: per-key allocation estimates, process measurements and counters.
- Caffeine, Eviction and Design: count and weight limits, and admission using recent and frequent use.
- Memcached, Performance and efficiency: item allocation, other process memory and reclamation of expired entries.