Skip to content

Cache Eviction Policies in Modern Web Apps: LRU, LFU, W-TinyLFU and ARC

Cache Eviction Policies in Modern Web Apps: LRU, LFU, W-TinyLFU and ARC

English original published: 2026-06-14T10:04:31.377+03:00. Original English article

Corrected educational edition. Technical review against primary sources: 2026-10-28. Code examples were not compiled or runtime-tested. The original English publication date is preserved; the Hebrew edition uses its actual publication date, not the English original date.

Welcome to Coding with Alex at sysseder.com.

Rent and housing allocation can serve as a metaphor for limited memory: who gets space, how long they keep it, and what happens when demand changes. This article uses that analogy to discuss a software problem, without claiming that a particular paper appeared today on Hacker News or drawing an economic conclusion: cache resource allocation.

In our software systems, memory is our prime real estate. We have a limited amount of high-speed "housing" (RAM) to store our data, and an endless queue of incoming requests demanding a spot. How we decide who gets to stay in our cache, who gets evicted, and how we distribute this digital "wealth" (bandwidth and latency savings) is one of the most critical design decisions we make.

A poorly matched eviction policy can retain low-value entries or cause repeated misses and database load. We will compare recency, frequency and adaptive approaches, including W-TinyLFU and ARC, with LIRS as a related scan-resistant policy. Caffeine uses Window TinyLFU; Redis documents its own approximate LRU/LFU policies. These are not interchangeable implementations, and no claim is made that every named algorithm powers every named product. source1 source2

The Cracks in the Classic LRU Model

LRU is a common eviction policy. With a hash map and doubly linked list, lookup and recency-list updates are typically expected O(1), subject to hashing and concurrency costs. Access moves an entry to the recent end; when capacity is full, the least-recent entry is evicted. source

One important LRU weakness is susceptibility to one-hit wonders.

A batch job, crawler or full scan may read many entries only once. If these entries enter a capacity-limited LRU cache, they can evict frequently reused keys and reduce hit rate, increasing backend load. This is cache pollution; a zero hit rate or database outage is a possible workload-specific outcome, not an inevitable result. source

The Anatomy of Cache Pollution

[Hot Key A] -> [Hot Key B] -> [Hot Key C]  (Healthy State)
      |
      v  (Enter a massive, single-use database scan)
[Scan Key 1] -> [Scan Key 2] -> [Scan Key 3] (Hot keys are evicted!)

To prevent this, modern systems engineering has moved toward frequency-aware and adaptive eviction policies. Let’s look at how we can implement and leverage these smarter strategies.

Enter LFU and the Frequency Problem

To combat the one-hit-wonder problem of LRU, we can look at Least Frequently Used (LFU). LFU keeps track of how many times an item has been requested. A one-hit wonder won't easily evict a key that has been accessed 100 times.

However, LFU has its own structural vulnerability: historical accumulation. In a naive lifetime-count LFU without decay, expiry or resets, an item accessed 10,000 times during a sale can remain favored long after demand falls. It is not literally guaranteed to stay forever: other counters and replacement rules matter. Decay reduces this historical bias. source

To build a resilient production system, we need algorithms that balance both recency (LRU) and frequency (LFU) while incorporating a mechanism for historical decay.

Understanding W-TinyLFU for In-Memory Caching

For JVM applications, including integrations used with Spring, one option is the Caffeine cache library. Its documented admission/eviction policy is W-TinyLFU (Window Tiny Least Frequently Used). source

Frequency sketches estimate popularity with bounded metadata rather than a separate exact counter for every observed key. Caffeine’s TinyLFU uses a packed 4-bit Count-Min Sketch. Four bits describes each counter, not total bytes per cached entry: multiple counters, table sizing and object overhead also matter. The Python teaching example below uses one byte per counter plus Python overhead, not packed 4-bit storage. source

The W-TinyLFU Architecture

W-TinyLFU divides the cache layout into two main areas:

  • The Window Cache (LRU): A small recency window initially admits arrivals. Its size is implementation- and workload-dependent; Caffeine can adapt the window. This helps handle bursts but does not guarantee a throughput or hit-rate target. source
  • The Main Cache (Segmented LRU): Divided into a "Probation" segment and a "Protected" segment.

Conceptually, a candidate leaving the window is compared with a probation-region victim using estimated frequency. Admission aims to favor more valuable candidates. Exact tie-breaking, adaptive sizing and concurrency mechanics are implementation details; this sketch of the policy is not a complete Caffeine reimplementation. source

The Python example below illustrates approximate bounded counters and periodic aging, not a complete W-TinyLFU cache. It validates dimensions, uses deterministic hashes, caps counters and ages them after a chosen number of observations. It is runtime-untested, not thread-safe, and makes no claim of near-zero memory or production accuracy.

# Educational model only; runtime-untested and not thread-safe.
# One byte per counter plus Python object overhead, NOT packed 4-bit storage.
from hashlib import blake2b

class CountMinSketch:
    def __init__(self, width: int, depth: int, sample_size: int):
        if width <= 0 or not 0 < depth < 2**32 or sample_size <= 0:
            raise ValueError("width, depth and sample_size must be positive; depth < 2**32")
        self.width = width
        self.depth = depth
        self.sample_size = sample_size
        self.table = [bytearray(width) for _ in range(depth)]
        self.observations = 0

    def _hash(self, key: str, row: int) -> int:
        # Deterministic row-specific digest; no formal hash-independence claim.
        data = key.encode("utf-8")
        seed = row.to_bytes(4, "little")
        digest = blake2b(data, digest_size=8, person=b"cms" + seed).digest()
        return int.from_bytes(digest, "little") % self.width

    def increment(self, key: str):
        for row in range(self.depth):
            column = self._hash(key, row)
            if self.table[row][column] < 15:
                self.table[row][column] += 1
        self.observations += 1
        if self.observations >= self.sample_size:
            self._age()

    def estimate(self, key: str) -> int:
        # Minimum reduces collision inflation; it does NOT eliminate collisions.
        # Capping and aging mean this is not an exact lifetime count.
        return min(self.table[row][self._hash(key, row)] for row in range(self.depth))

    def _age(self):
        for row in self.table:
            for column in range(self.width):
                row[column] //= 2
        self.observations = 0

TinyLFU-style aging periodically reduces counters so old accesses lose influence. The trigger is based on observed accesses/sample accounting, not simply insertions into the cache. The educational example halves counters every sample_size increment calls; production Caffeine has its own saturation and sample accounting. Collisions can inflate estimates, while capping and aging change their interpretation; taking a minimum does not eliminate collisions. source

Adaptive Caching: Self-Tuning Policies

Workloads can shift between interactive requests, scans and batch processing. The best policy cannot be inferred from day versus night or from the label transactional versus batch; compare representative access traces, entry costs and miss penalties.

Rather than fixing the balance manually, Adaptive Replacement Cache (ARC) adapts its target balance between recent and repeatedly used entries using feedback from history, including ghost-list hits. Its frequency component is not a lifetime LFU counter list. source

How ARC Dynamically Balances the Scales

ARC maintains resident lists T1 and T2 and nonresident ghost-history lists B1 and B2. T1 represents recent entries and T2 entries seen repeatedly. At most C values are resident; the combined resident-plus-history directory has at most 2C entries in the standard equal-sized-page model. L1=T1+B1 and L2=T2+B2 are conceptual groupings, not two lists that each hold twice the cache capacity. source

Resident entries: |T1| + |T2| <= C
Resident + ghost-history entries: |T1| + |T2| + |B1| + |B2| <= 2C

[ T1: recent values       ] <--> [ T2: repeatedly used values ]
[ B1: evicted-key history ]      [ B2: evicted-key history     ]

Ghost lists store keys/metadata, not cached values.
A ghost-list hit still requires fetching the missing value.

A request for a key in B1 raises the target for T1; a request for a key in B2 lowers it, favoring the repeatedly used region. A ghost hit is still a miss for the value: the data must be fetched again. This changes a replacement target within a fixed cache budget, not necessarily the amount of physical RAM allocated. source

Adaptive feedback reduces manual tuning of this particular balance, but does not remove the need for workload validation, capacity planning, observability or handling backend failures.

Production Checklist: Choosing Your Cache Architecture

How do you apply this to your daily dev stack? Here is a quick reference guide on choosing the right caching engine based on your architecture:

  • For Redis / Distributed Caching: Evaluate volatile-lru or allkeys-lfu only after checking the eligible key set and workload. volatile-lru can evict only keys with expiry; allkeys-lfu considers all keys and uses an approximate decaying frequency signal. If no eligible keys exist, a volatile policy behaves like noeviction. Do not mix correctness-critical rate-limit state into an evictable cache without evaluating semantics. A high-variance workload alone does not prove that the best choice is LFU. source
  • For In-Memory App Caching (JVM/Go/Rust): Prefer maintained libraries to an ad-hoc concurrent cache when their semantics fit. Caffeine is a Java library using Window TinyLFU. Ristretto is a Go cache using TinyLFU admission with sampled LFU eviction, not simply a W-TinyLFU port. Check the actual Rust/Go/JVM library, consistency guarantees, contention and workload behavior. source1 source2
  • For CDNs and Edge Nodes: Verify the provider’s documented cache behavior rather than assuming ARC or LIRS. Eviction policy alone does not solve a thundering herd: concurrent misses may still need request coalescing, controlled refresh and appropriate TTL/invalidation design.

Conclusion & Discussion

Memory is limited, and replacement policy affects which requests avoid backend work. Frequency-aware and adaptive approaches such as W-TinyLFU or ARC can help for some access patterns, but no policy ensures resilience, speed or lower bills for every application. Choose based on representative measurements and correctness requirements, including expiration and invalidation.

Which eviction policy do you use, and what measurements led to the choice? Share your observations in the article comments.

Until next time, keep your code clean, your databases shielded, and your latency low. Happy coding!

The Python code is a teaching model and is runtime-untested. It has no admission window, segmented LRU lists, thread-safety, full cache API or production memory bound. The diagrams illustrate policy concepts, not performance measurements. Original code and claims are preserved in the faithful HOLD version.

Sources for corrections

Post a Comment

Previous Post Next Post