Inferensys

Glossary

Least Recently Used (LRU)

Least Recently Used (LRU) is a cache eviction algorithm that removes the item that has not been accessed for the longest period when the cache is full and space is needed for a new entry.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
CACHE EVICTION ALGORITHM

What is Least Recently Used (LRU)?

A core algorithm for managing finite cache capacity by prioritizing recently accessed data.

Least Recently Used (LRU) is a cache eviction policy that removes the item that has not been accessed for the longest time when the cache reaches its capacity limit. It operates on the principle of temporal locality, assuming that data accessed recently is more likely to be needed again soon. The policy is typically implemented using a combination of a hash map for O(1) lookups and a doubly linked list to maintain access order, where the most recently used (MRU) item is at the head and the least recently used (LRU) item is at the tail.

In agent-side caching, LRU is crucial for managing the session memory of an AI agent, efficiently storing API responses and computed results to avoid redundant external calls. When the agent's context window or allocated memory is full, LRU ensures the oldest, unused data is purged first. This directly supports inference optimization by maximizing the cache hit ratio and minimizing latency, though it may perform poorly if access patterns lack strong recency, a scenario where alternatives like LFU (Least Frequently Used) or ARC (Adaptive Replacement Cache) might be more effective.

CORE ALGORITHM

Key Characteristics of LRU

Least Recently Used (LRU) is a foundational cache eviction policy. Its defining characteristic is its singular focus on the recency of access to determine which items to remove when the cache is full.

01

Recency-Focused Eviction

LRU's core logic is simple: the item that has not been accessed for the longest time is evicted first. It assumes that recently used data is more likely to be used again in the near future (temporal locality).

  • Implementation: Typically requires tracking access order, often using a doubly linked list combined with a hash map for O(1) operations.
  • Contrast with LFU: Unlike Least Frequently Used (LFU), which counts total accesses, LRU cares only about the timing of the most recent access.
02

Data Structures & O(1) Complexity

A canonical, efficient LRU implementation uses two data structures in tandem to achieve constant-time operations for get and put.

  • Hash Map (Dictionary): Provides O(1) lookup by key to find the corresponding node in the linked list.
  • Doubly Linked List: Maintains items in order of access. On any access (get or put), the touched node is moved to the head (most recent). The node at the tail is the least recently used and is evicted on capacity overflow.

This combination guarantees O(1) time complexity, which is critical for high-performance caching layers.

03

Susceptibility to Scan Attacks

A significant weakness of pure LRU is its vulnerability to one-time scans or looping access patterns that pollute the cache.

  • Scenario: If a process sequentially reads a dataset larger than the cache capacity, every existing item is evicted because each new item becomes the 'most recent'.
  • Impact: This causes 100% cache misses for the legitimate, working-set data that follows the scan, severely degrading performance.
  • Mitigation: Advanced variants like LRU-K or Adaptive Replacement Cache (ARC) were developed to be more resilient to such patterns by considering frequency alongside recency.
04

Ideal for Stable, Locality-Heavy Workloads

LRU excels under specific, predictable access patterns where its core assumption holds true.

  • Strong Temporal Locality: The same data is accessed in clusters over short periods (e.g., a user repeatedly querying their own recent transactions).
  • Stable Working Set: The set of 'hot' data fits within the cache capacity and changes relatively slowly.
  • Common Use Cases: CPU caches, database buffer pools, and in-memory caches for web session data often use LRU or its variants due to these predictable patterns.
05

Implementation in Agent-Side Caching

In the context of AI agents and tool calling, LRU can manage the cache of API responses or computed results within an agent's session.

  • Caching Deterministic Calls: Ideal for caching the results of pure function calls or idempotent API requests where the same input (prompt, parameters) yields the same output.
  • Managing Session Context: Used to keep the most recently accessed pieces of context, conversation history, or tool results within a limited token window or memory budget.
  • Integration with Semantic Cache: Can be a component in a larger system where a semantic cache first finds a similar request, and an LRU policy manages the physical storage of those cached results.
06

Evolution: LRU-K and ARC

Pure LRU's limitations led to the development of more sophisticated algorithms that retain its benefits while adding robustness.

  • LRU-K: Tracks the times of the last K references to an item. Eviction is based on the K-th most recent access time. This filters out one-time accesses (noise) and better identifies truly 'hot' items.
  • Adaptive Replacement Cache (ARC): Maintains two LRU lists: one for recently used items (T1) and one for frequently used items (T2). It dynamically adapts the size of these lists based on the workload, effectively balancing recency (LRU) and frequency (LFU). ARC is self-tuning and generally outperforms both LRU and LFU.
ALGORITHM MECHANICS

How LRU Works: Implementation Mechanism

The Least Recently Used (LRU) cache eviction algorithm is implemented using data structures that efficiently track access order to identify the item unused for the longest time.

LRU is implemented using a combination of a hash map and a doubly linked list. The hash map provides O(1) access to cache items via a key, while the doubly linked list maintains the items in order of access. On a cache hit, the accessed node is moved to the front (most-recent position) of the list. On a cache miss, a new item is fetched, added to the front of the list, and inserted into the hash map.

When the cache reaches capacity, the eviction process removes the node at the tail (least-recent position) of the linked list and deletes its corresponding entry from the hash map. This combination ensures that both item lookup and the repositioning of accessed items are constant-time operations, making LRU efficient for high-throughput systems. Alternative structures like ordered dictionaries (e.g., Python's OrderedDict, Java's LinkedHashMap) encapsulate this logic.

AGENT-SIDE CACHING

Frequently Asked Questions

Essential questions about the Least Recently Used (LRU) algorithm, a fundamental policy for managing finite cache memory in AI agents and high-performance systems.

The Least Recently Used (LRU) algorithm is a cache eviction policy that removes the item that has not been accessed for the longest period when the cache reaches its capacity limit. It operates on the principle that data accessed recently is more likely to be needed again soon. In an agent-side caching context, LRU is used to manage the temporary storage of API responses and computed results, ensuring the cache holds the most relevant data for an AI agent's current session. The policy is typically implemented using a combination of a hash map for O(1) lookups and a doubly linked list to track access order, where the most recently used item is moved to the front (head) and the least recently used item is evicted from the back (tail).

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.