LLM Caching Interview Questions — AI Engineering Practice Quiz

Reviewed by Mark Dickie · Last updated

LLM caching is the practice of storing responses to repeated prompts so that subsequent identical or similar requests can be served without re-calling the model. For an AI engineering interview, you should understand cache key construction (prompt hashing, including or excluding temperature and system messages), cache invalidation and TTL strategies, the difference between exact-match and semantic (embedding-based) caching, and the cost-latency trade-offs that make caching worthwhile. You should also be able to reason about when caching hurts: stale answers, privacy constraints, and cache poisoning risks.

What does an LLM caching interview test?

Interviewers probe whether you can design a caching layer that actually saves money without degrading answer quality. That means knowing the concrete decisions: what goes into the cache key, how long entries live, how you detect semantic similarity, and how you measure whether the cache is pulling its weight.

ConceptWhat to knowCommon interview angle
Exact-match cacheHash the normalized prompt; return stored response on hit"How would you key the cache?" — normalization matters
Semantic cacheEmbed the prompt, compare against stored embeddings via cosine similarityThreshold tuning: too loose returns wrong answers
TTL & invalidationExpire entries after a set window or on model version change"What happens when the model is updated?"
PrivacyDo not cache prompts containing PII or per-user dataMulti-tenant isolation, opt-out flags
Hit-rate metricsCache hit ratio, latency saved, cost avoided per 1k requestsJustify the cache with numbers, not vibes

How should you structure an LLM cache key?

  1. Normalize the prompt — strip trailing whitespace, lowercase where case-insensitive, sort JSON keys if the payload is structured.
  2. Include all inputs that affect output: system prompt, user message, model ID, temperature, top-p, and any tool definitions.
  3. Hash the normalized payload (SHA-256 is typical) to get a fixed-length key.
  4. Decide whether to namespace by tenant or user so cross-contamination does not occur.
  5. On a hit, return the stored response; on a miss, call the model, store the result, and return it.

For semantic caching, step 3 changes: you embed the prompt instead of hashing it, then run a nearest-neighbor lookup against stored vectors. A similarity threshold of 0.95 is a common starting point, but the right number depends on your domain. A threshold that is too low means semantically different prompts get the same cached answer, which is the failure mode interviewers want you to name.

Key facts

  • Tarmac has 29 AI Engineering interview questions on this topic, 10 of them on this page, at difficulty 1–4 of 5.
  • Tarmac tracked 4,175 job postings asking for AI Engineering in August 2026.
  • Roles asking for AI Engineering advertise a median base salary of US$182,450, across 806 job postings as of August 2026.
  • Tarmac last reviewed these AI Engineering interview questions on 14 September 2026.

At a glance

Questions10 shown · 29 in the bank
Difficulty1–4 of 5
FormatsTrue / false, Design exercise, Code output, Find the bug, Short answer, Multiple choice, Multiple answer, Ordering, Fill in the blank, Flashcard

What you'll review

  1. llm caching
  2. latency cost
  3. agent loops

Practice questions

Try one before you open the answer. Pick an option and press Check; it's marked on the spot.

AI Engineering/ai-production/llm-caching

With provider prompt caching, putting a large, stable system prompt and document context at the start of the request (with the variable user input last) can substantially cut per-call cost and latency on repeated requests.#

Options

Show answer

True. Prompt caching keys on a prefix of the request, so a long unchanging prefix — system instructions, few-shot examples, a fixed knowledge block — can be cached once and reused, with cache reads billed at a steep discount and skipping recomputation, which lowers latency. The catch is ordering: anything that varies must come after the stable prefix, otherwise it breaks the cacheable prefix and you pay full price. Structure prompts stable-first, variable-last.

Why:

Prompt caching keys on a prefix of the request, so a long, unchanging prefix (system instructions, few-shot examples, a fixed knowledge block) can be cached once and reused — cache reads are billed at a steep discount and skip recomputation, lowering latency. The catch: ordering matters. Anything that varies must come after the stable prefix, otherwise it breaks the cacheable prefix and you pay full price every call. Structure prompts stable-first, variable-last to maximize hits.

AI Engineering/ai-production/llm-caching

You are building a customer-support chatbot backed by an LLM API. The same questions (e.g., "What is your return policy?") are asked frequently, and you want to reduce latency and API costs by adding a caching layer. At a high level, design this caching layer: where the cache sits in the request flow, what you use as the cache key, when you serve from cache vs. call the LLM, and when you invalidate or refresh cached entries. Describe your design in a few paragraphs.#

Show answer

I would place a caching layer between the chatbot frontend and the LLM API. When a request arrives, the system first normalizes the input text (trimming whitespace, lowercasing, removing extra punctuation) and computes a hash of the normalized string to use as the cache key. The system then checks the cache: if an entry exists and has not expired, it returns the cached response immediately, skipping the LLM call entirely and saving both latency and cost. If no valid entry is found (a cache miss), the request is forwarded to the LLM API, the response is received, and the system stores it in the cache under the computed key before returning it to the user. To prevent the cache from growing without limit as new questions arrive, I would use an LRU eviction policy with a max-entry cap — for example, evicting the least recently accessed entries when the cache reaches 10,000 entries. Each cached entry is also assigned a TTL — for example, 24 hours — so that stale answers are automatically evicted and refreshed. Additionally, if the underlying knowledge source changes (e.g., the return policy document is updated), I would proactively invalidate or clear the relevant cache entries to ensure users receive up-to-date information. This design reduces repeated LLM API costs and improves response time for common questions while maintaining a reasonable freshness guarantee.

Why:

This is a foundational design question that tests whether the candidate understands the basic mechanics of an LLM response cache: interception before the LLM call with proper hit/miss behavior, key derivation from normalized input, bounding cache size with an eviction policy, and freshness via TTL or explicit invalidation. The original rubric paid twice for the same miss/hit design point (c1 and c3 overlapped); they are now merged into a single criterion, and the freed weight goes to cache eviction/bounding — a concrete mechanism a shallow answer would miss.

AI Engineering/ai-production/llm-caching

The code below implements a simple in-memory cache for LLM responses. Trace the execution and determine the exact stdout produced.#

cache = {}

def get_response(prompt):
    if prompt in cache:
        return cache[prompt] + " (cached)"
    cache[prompt] = "response_for_" + prompt
    return cache[prompt]

print(get_response("hello"))
print(get_response("world"))
print(get_response("hello"))
Show answer
response_for_hello
response_for_world
response_for_hello (cached)
Why:

On the first call get_response("hello") the cache is empty, so the if prompt in cache condition is False. The function executes cache["hello"] = "response_for_" + "hello", storing "response_for_hello", and returns that string. The second call get_response("world") likewise misses the cache, stores "response_for_world", and returns it. The third call get_response("hello") now finds "hello" in cache, so it returns cache["hello"] + " (cached)", which is "response_for_hello" + " (cached)", yielding "response_for_hello (cached)". The three print statements each emit one line, producing the expected output.

AI Engineering/ai-production/llm-caching

A team built a simple in-memory cache for LLM responses. They notice that switching models or changing the temperature sometimes returns a response generated under a different configuration. Find the bug.#

class LLMCache:
    def __init__(self):
        self._store = {}

    def get_or_call(self, prompt, model, temperature, llm_client):
        cache_key = hash(prompt)
        if cache_key in self._store:
            return self._store[cache_key]
        response = llm_client.generate(prompt, model, temperature)
        self._store[cache_key] = response
        return response
Show answer

The bug is on line 6.

Why:

Line 6 builds the cache key from hash(prompt) alone. Because model and temperature are not part of the key, a second call with the same prompt text but a different model or temperature hits the stale entry and returns the previously cached response instead of calling the LLM with the new configuration. The fix is to include all parameters that affect the output in the key, e.g. hash((prompt, model, temperature)).

AI Engineering/ai-production/llm-caching

What is prompt caching, and how should you structure a prompt to benefit from it?#

Show answer

Prompt caching lets the provider reuse the computed attention state for a large, stable prefix of your prompt (system instructions, few-shot examples, a long document) across requests, so repeated calls are cheaper and lower latency because the cached prefix is billed at a reduced rate and skips recomputation. To benefit, put the stable, reused content at the front of the prompt and the variable, per-request content (the user's question) at the end — caching keys off the longest matching prefix.

Why:

Caching works on a prefix match: the provider stores the key/value attention state for an unchanged leading span and reuses it on subsequent calls, cutting both cost and time-to-first-token. The practical rule is order-dependent — keep the big invariant blob (system prompt, tool definitions, long context document, few-shot exemplars) at the start and anything that changes per request at the tail, otherwise the cache misses on every call.

AI Engineering/ai-production/llm-caching

Every request to your assistant prepends the same 4,000-token system prompt plus a long, static policy document, then appends a short user message. To cut per-request cost and latency with no quality loss, which technique fits best?#

Options

Show answer

Use prompt (prefix) caching of the stable leading portion of the context. Caching stores the processed key/value state for your unchanging system prompt and policy doc, so later requests reuse it instead of re-processing those tokens, lowering input cost and time-to-first-token while leaving outputs identical. Changing temperature affects randomness not cost, retrieving the prompt by vector search is pure overhead, and raising max_tokens only caps output length.

Why:

Prompt caching stores the processed key/value state for a stable prefix (your unchanging system prompt + policy doc); on later requests the model reuses it instead of re-processing those tokens, which lowers input cost and time-to-first-token while leaving outputs identical — ideal when a large prefix is constant and only the tail varies. Changing temperature (b) affects randomness, not cost. Retrieving the system prompt via vector search (c) adds machinery and a retrieval step to fetch text you already have verbatim — pure overhead. Raising max_tokens (d) only sets an upper bound on output length; it does not reduce the cost of re-reading the same input every call and can increase cost if it lets responses grow.

AI Engineering/ai-production/llm-caching

A provider offers prompt caching (server-side KV-cache reuse for repeated prompt prefixes). Which of the following are accurate statements about using it effectively? Select all that apply.#

Options

Pick every one that applies.

Show answer

The accurate statements are that the static portion (system prompt, tool definitions, long document) should be placed first so it forms a cacheable prefix, that cached tokens are cheaper and faster to process than uncached input, that the per-request variable part should be appended after the static prefix to maximize cache hits, and that caching is especially high-value for long stable system prompts or document sets reused across many requests. Prompt caching does not touch output-token costs — output is always freshly generated.

Why:

Prompt caching reuses a saved KV state for the part of the prompt that didn't change. Placing static content first (a) and appending variable content after (c) is the structural requirement — the cache key is a prefix, so any change before the cached region breaks the hit. Cached tokens are processed at a fraction of the normal input-token cost and with lower latency (b) — that is the entire economic rationale for the feature. Long, stable content (e) — a 10,000-token system prompt reused across thousands of requests — is the highest-leverage use case because the savings multiply per request. Prompt caching does not touch output tokens (d): output is always freshly generated from the current conversation state; caching only affects input-prefix processing costs.

AI Engineering/ai-production/latency-cost

Order the optimisation steps for reducing both latency and cost of an LLM feature that is too slow and too expensive in production.#

Put these in order

Show answer

Optimise latency and cost in this order:

  1. Profile the request to identify whether latency is dominated by TTFT, generation length, or network overhead
  2. Reduce the prompt to the minimum context that preserves answer quality (trim redundant instructions and history)
  3. Enable prompt caching for the stable prefix of the prompt shared across requests
  4. Switch to a smaller or cheaper model for the parts of the task that do not require frontier capability
  5. Re-evaluate latency and cost metrics after each change to verify improvement before applying the next
Why:

Optimising blindly wastes effort — profile first to know what is actually slow (TTFT implies compute bottleneck; generation length implies output tokens; high network overhead implies infrastructure). Then trim the prompt because every input token costs money and adds prefill latency. Enable caching on the stable prefix to amortise that cost across repeated calls — the savings are proportional to how much of the prompt is reused. Downsize the model only after the prompt is already lean; routing a bloated prompt to a cheaper model often produces lower quality than a tight prompt to a frontier model. Throughout, measure after each change so you attribute gains correctly and avoid stacking optimisations that cancel each other.

AI Engineering/ai-production/llm-caching

Prompt _____ is a provider feature that stores the computed key-value representations of a repeated prompt prefix, so subsequent requests that share that prefix skip re-processing it — reducing both _____ and input token cost for the cached portion.#

Show answer

Prompt caching is a provider feature that stores the computed key-value representations of a repeated prompt prefix, so subsequent requests that share that prefix skip re-processing it — reducing both latency and input token cost for the cached portion.

Why:

Prompt caching (available on Anthropic, OpenAI, and others) stores the KV-cache entries for a stable prompt prefix server-side. Requests that hit the cache skip the prefill computation for those tokens, cutting TTFT and charging a lower per-token price for cache hits. It is most valuable when the system prompt or retrieved context is large and reused across many requests — the typical pattern in RAG and agent loops with a fixed system prompt.

AI Engineering/agents/agent-loops

How should an agent loop be laid out to get value from prompt caching?#

Show answer

Put the stable material first and never edit it: system prompt, then tool definitions in a fixed order, then the conversation. Caching matches on an exact prefix, so a timestamp, a request id, a re-ordered tool list, or a freshly summarised recap invalidates from that point and everything after reverts to full price. Place the cache breakpoint after the stable block so the growing transcript sits behind it. Then verify rather than assume — read the cache-read token counts, and if they stay at zero across repeated calls something in the prefix changes every request, with nothing but the bill to tell you.

Why:

Two things trip loops up here. The first is a silent invalidator in the stable block — a rendered timestamp, a tool list built from an unordered map, a user id interpolated into the system prompt — which means the cache never hits and no error is raised. The second is the tension with context trimming: summarising the oldest turns is the single most destructive edit to a cached prefix, because it rewrites the front. Batch trims so one invalidation is amortised over many iterations, and check the usage numbers after any change to how the prompt is assembled.

Related interview questions

Job market

See ai-engineering salaries and hiring demand from live job postings.

The other 19 questions

This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 19 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.

Start with this topic

Free · the whole bank · 100 marked answers per 30 days · written feedback on the paid plan

What moved, monthly

One email a month when the bulletin comes out: what moved in the markets we track, and the new question topics we published. Confirm your address to join. Unsubscribe any time.