Concepts / Query Caching Criteria

Query Caching Criteria

Under exact caching, a stored result is used only when the incoming request is the same item as the stored one. Similar-looking requests are not the same item.

  • Programming

Why Avoid Repeating Work

Imagine an AI application that receives the same kind of question many times a minute. Each time a question arrives, the application may call a model, run a multi-step reasoning process, search a vector index, or query a database. Some of these actions are slow, and some cost money to run. If the application has already produced an answer for a request, running the whole process again is wasted effort.

Exact caching is a way to avoid that waste. The system keeps a record of past results and reuses them when the same request comes back. This article follows one question from start to finish: when the system receives a request, how does it decide whether a stored result can be used, and what has to be true before that reuse is safe? The answer depends on the word exact, so we start there.

What Exact Caching Means

Definition

Exact caching reuses a stored result only when the exact same item is requested, so the lookup key must match precisely.

The word exact defines what counts as a hit. A cache hit happens when an incoming request matches a stored key. A cache miss happens when no stored entry matches, and the system must do the work itself. In the product example used by the source, the request is a request to summarize one particular product. Before doing any work, the system checks whether a summary of this exact product already exists. If it does, the stored summary is fetched. If it does not, the system creates the summary and stores it for next time.

The lookup key is the request itself, and only an identical key produces a hit. A summary of one product cannot be handed back for a different product, even if the two products sound alike. The same pattern applies to embedding-based retrieval. When an incoming query is already in the vector search cache, the stored result is fetched. If it is not, a vector search runs for that query and its result is cached. In both cases the purpose is to avoid redundant work: repeating a search or a summary that has already been done for the same request.

Key point

Under exact caching, a stored result is used only when the incoming request is the same item as the stored one. Similar-looking requests are not the same item.

How a Lookup Key Turns Into a Hit or Miss

Think of the cache as a table of keys, where each key points to a stored value. The system turns an incoming request into a key, looks that key up, and either finds a value or does not. Because the match is exact, even a tiny difference in the key produces a different key and therefore a miss.

summary|product-A100stored summary of productA100summary|product-A101no entry: missexact match required
How does an incoming request become a lookup key, and why does a single character difference produce a miss instead of a hit?

In this picture, the stored entry is keyed to product A100. An incoming request for product A101 produces a different key, so the lookup finds nothing and the request is a miss, even though the two products are almost identical. The same logic would reject a summary for a request that differed only in spacing or wording, because the key, not the meaning a person would assign to it, is what the system compares.

Tracing Requests Through a Cache

The best way to understand exact caching is to watch the cache change. Below is a short run of four requests to summarize products. The cache starts empty. For each request, the system first checks whether a summary of this exact product already exists. Study the timeline, then notice what changes after each step.

Request 1: Product AMiss. Cache holds ARequest 2: Product BMiss. Cache holds A, BRequest 3: Product AHit. Stored summary fetchedRequest 4: Product CMiss. Cache holds A, B, Cnextnextnext
After each request in a sequence, what is stored in the cache, and which requests were hits and which were misses?
Worked example

Following the Cache Step by Step

The cache starts empty. Requests arrive in this order: summarize Product A, summarize Product B, summarize Product A, summarize Product C. For each request, state whether it is a hit or a miss, and list what the cache holds afterward.

  1. 1
    Request 1 (Product A)

    The cache is empty, so no entry matches. This is a miss. The system creates the summary for Product A and stores it. The cache holds A.

  2. 2
    Request 2 (Product B)

    The key for Product B does not match the key for Product A. This is a miss. The system creates and stores the summary for Product B. The cache holds A and B.

  3. 3
    Request 3 (Product A)

    The key matches the stored entry for Product A exactly. This is a hit. The stored summary is fetched, and no new summary is created. The cache still holds A and B.

  4. 4
    Request 4 (Product C)

    No stored key matches Product C. This is a miss. The summary for Product C is created and stored. The cache holds A, B, and C.

Result

Requests 1, 2, and 4 are misses, and request 3 is the only hit. Only the repeated request for Product A avoided new work.

What do you think happens?

Before reading the result, predict: if a fifth request asks for Product A again, is it a hit or a miss?

  • Hit

  • Miss

Reveal answer
Answer:

Hit

Product A's summary is still stored from request 1, and nothing in this run has removed it. The key matches exactly, so the stored summary is fetched.

Where an Exact Cache Lives

An exact cache can be implemented with in-memory storage, which allows fast retrieval. The source notes a limit to this choice: in-memory storage is restricted in how much it can hold. Because of that limit, a cache can instead be built on a database such as PostgreSQL or Redis, or on tiered storage, which is used to balance speed against storage capacity.

Storage choiceWhat it offersWhat it costs
In-memory storageFast retrievalRestricted in how much it can hold
Database such as PostgreSQL or RedisCan hold more results than in-memory storageReads are generally slower than in-memory storage
Tiered storageBalances speed against storage capacityRequires deciding how results move between tiers

Storage options for an exact cache, as described in the source. The cost column reflects the stated tradeoff between speed and capacity.

Key point

Faster storage tends to hold less, and larger storage tends to be slower to read. Choosing a cache location means deciding where on that spectrum your results should live, given the volume of requests your application handles.

Keeping the Cache From Growing Forever

A cache that only ever grows will eventually become a problem, especially when storage is limited. The source states that an eviction policy is crucial for managing cache size and maintaining performance. An eviction policy is the rule the system uses to decide which entries to remove when space is needed.

The source names three common eviction policies. Least Recently Used (LRU) looks at how recently each entry was used. Least Frequently Used (LFU) looks at how often each entry was used. First in, first out (FIFO) looks at the order in which entries arrived. The source lists these names without describing their internal mechanics, so the names themselves are the core facts to remember.

PolicyWhat it looks atEntry it would tend to remove when space is needed
LRU (Least Recently Used)How recently an entry was usedThe entry that has gone the longest without being used
LFU (Least Frequently Used)How often an entry was usedThe entry that has been used the fewest times
FIFO (First In, First Out)The order in which entries arrivedThe entry that arrived earliest

The three policies named in the source, compared by the property each one examines.

Requests That Should Not Be Cached

Not every request is worth storing. The source says how long a query should stay in the cache depends on how likely that query is to be called again. Two categories are called out as poor candidates.

The first category is user-specific queries, such as a question about the status of one's recent order. Such a result is unlikely to be reused by other users, so it should not be cached. The second category is time-sensitive queries, such as asking about the weather. A stored answer to a question whose correct answer changes over time becomes misleading, so caching it makes less sense.

The source also notes that many teams train a classifier to predict whether a query should be cached. The source does not describe how such a classifier is built, so the important idea is the goal: predicting the likelihood that a query will be reused.

Incoming requestIs the answerspecific to one user?Does the answerdepend on hidden userdata?Does the answerchange over time?Is the work costly ormulti-step?Cache under exact keyreusable resultDo not cacheuser-specific resultDo not share under ageneric keypossible data leakDo not cachetime-sensitive resultcheckyesnoyesnoyesnoyes
For a given request, what checks determine whether its result is safe to store and reuse?

Read the flowchart as a set of questions asked in order. The first two checks come from the source: user-specific and time-sensitive queries are poor candidates. The hidden-data check follows from the leak example in the next section. The last check reflects the source's point that caching is most valuable when a request involves multiple steps or time-consuming actions such as retrieval, SQL execution, or web search.

How Careless Caching Leaks Private Information

Caching has a hazard that goes beyond wasted storage. The source warns that caching, when not properly handled, can cause data leaks. The trouble comes from a request that looks generic but actually depends on who is asking.

Consider an ecommerce site. A user asks, 'What is the return policy for electronics products?' The question sounds the same for everyone, but in this case the return policy depends on the user's membership. To answer, the system first retrieves that user's information, then generates a response that contains it. If that response is stored under a key built only from the question text, the key does not include the user's identity.

User ACachekey: return policy forelectronicsShop backendretrieves user membershipUser B1. asks return policy for electronics2. miss, no entry yet3. answer with A's membership terms, stored under shared key4. A receives answer5. asks the same question6. hit: returns A's answer to B
How can user A's cached result end up being returned to user B when the cache key does not include the user identity?

Follow the messages in order. User A's question creates an entry. User B then asks the same question. Because the key matches exactly, the cache reports a hit and returns A's answer, which reflects A's membership. Nothing in the key was wrong by the exact-match rule; the leak comes from the key leaving out the one fact that changed the answer. A safe design either keeps such results out of the shared cache or includes the user's identity in the key so that a hit can only occur for the same user.

Common Mistakes With Cache Criteria

  • Common mistake

    Treating similar requests as the same request

    What it looks like

    Reusing the summary for Product A101 when the request asked about Product A100.

    Why it fails

    Exact caching only reuses a stored result when the exact same item is requested. The lookup key is compared exactly.

    Do this instead

    Compare the full key. If the item differs, it is a miss.

  • Common mistake

    Caching a user-specific answer under a shared key

    What it looks like

    Storing a return-policy answer that depends on membership under the text of the question alone.

    Why it fails

    The stored answer may be returned to another user, which can leak private information.

    Do this instead

    Keep user-specific results out of the shared cache, or include user identity in the key.

  • Common mistake

    Caching time-sensitive answers as if they stay valid

    What it looks like

    Storing a weather answer and returning it hours later.

    Why it fails

    The correct answer changes over time, so the stored answer becomes misleading.

    Do this instead

    Skip caching for time-sensitive queries.

  • Common mistake

    Letting the cache grow without limit

    Why it fails

    The source states that storage is limited and that an eviction policy is crucial for managing cache size and maintaining performance.

    Do this instead

    Choose an eviction policy such as LRU, LFU, or FIFO that fits how the cache is used.

Practice Tracing a Cache

MEDIUM

A cache starts empty and has room for only two entries that are kept at once. Requests arrive in this order: Product X, Product Y, Product X, Product Z. Using exact matching, state the result of each request as a hit or a miss. Then decide whether the request for Product Z forces an eviction, and if it does, which entry LRU would remove.

Hints
  • Track the cache contents after each request, the same way the timeline did.
  • A repeated request for the same exact product is a hit if its entry is still stored.
  • For LRU, look at which stored entry was used least recently before Product Z arrives.

Summary of Cache Criteria

  1. 1
    Exact caching reuses a stored result only when the exact same item is requested, so the lookup key must match precisely.
  2. 2
    An exact cache can live in in-memory storage for speed, in a database such as PostgreSQL or Redis, or in tiered storage that balances speed and capacity.
  3. 3
    An eviction policy such as LRU, LFU, or FIFO manages cache size and helps maintain performance.
  4. 4
    User-specific and time-sensitive queries are poor candidates for caching, and careless caching of user-specific answers can leak private information.

At a glance

  • Exact caching reuses a stored result only when the exact same item is requested, so the lookup key must match precisely.
  • A cache hit occurs when the key matches a stored entry; a miss means the system must do the work and usually stores the new result.
  • An exact cache can be placed in in-memory storage, a database such as PostgreSQL or Redis, or tiered storage, with a tradeoff between speed and capacity.
  • Eviction policies such as LRU, LFU, and FIFO decide which entries to remove when the cache needs space.
  • User-specific and time-sensitive queries should usually not be cached, and results that depend on hidden user data must not be shared under a generic key.

More concepts starting with Q