# Cache LLM calls so your app doesn't pay twice for the same answer

- Author: RomanMotion (https://wurk.fun/user/RomanMotion)
- Published: 2026-11-06
- Canonical (HTML): https://wurk.fun/blog/cache-llm-calls-so-your-app-doesn-t-pay-twice-for-the-same-answer
- Cover image: https://ik.imagekit.io/wurk/browser-uploads/f1c626b5c17e7f0a61dfbbe7a20d85ae7b33a20527243aeec2ee1d0a8b87562a/b836d75c-6d8e-4be8-abc4-a2117c8b41c6/cover-cache.jpg?wurkUpload=v1.M0CLsS1EfmanSV7F36nbs1-1_ReYzW7OyGvwSULbY7E

---

Your script calls the LLM API, gets a good answer, then you fix a typo and run it again. Same model, same prompt, same answer: billed again, and you waited for it again. Multiply that by every dev rerun, retry and repeated user question in a week, and you are paying real money to regenerate text you already own.

The fix is a response cache. Hash everything that shapes the answer, keep the response on disk keyed by that hash, and the next identical request becomes a dictionary lookup instead of an API call. Below is a minimal version in standard-library-only Python, when caching is a bad idea, and how to prove the second call actually hits.

## Why the same call happens twice

Repeat calls are not an edge case; they are the default pattern in small tools:

1. **Dev loops.** You change the code around the call (parsing, formatting, the UI) and rerun. The prompt didn't change, but the call goes out again.
2. **Retries.** Your error handling catches a timeout and resends. If the first attempt actually reached the server, you may pay for the answer twice.
3. **Identical user questions.** An FAQ bot or a support script gets the same question phrased the same way, over and over.
4. **Batch reruns.** You process a folder of files, the script dies at file 40, you fix the bug and rerun. Files 1 through 39 get re-processed and re-billed.

Each repeat costs the same two things: the API charge and the wait. A cache costs almost nothing to run: Python's standard library already includes [sqlite3](https://docs.python.org/3/library/sqlite3.html), and a JSON file needs even less. If you'd rather have a coding agent build this into your project for you, you can [try the zcode agent harness free](https://zcode.z.ai/invite/ALWM9JUA) (that's our invite link).

## Build the key from everything that shapes the answer

The one rule: the cache key must cover every input that can change the response. Miss one and you serve the wrong cached answer, which is worse than no cache at all. That means:

- the model name
- the full messages array, system prompt included
- every parameter: temperature, top_p, max tokens, tool definitions, response format

Serialize all of it deterministically and hash it. Here is a working ~25-line version, standard library only:

```python
import hashlib, json, sqlite3, time

CACHE_VERSION = "v1"        # bump when you change the prompt
TTL = 86400                 # seconds, 0 = never expire

def make_key(model, messages, params):
    payload = json.dumps([CACHE_VERSION, model, messages, params], sort_keys=True)
    return hashlib.sha256(payload.encode()).hexdigest()

def lookup(db, model, messages, params):
    key = make_key(model, messages, params)
    row = db.execute(
        "SELECT response FROM cache WHERE key = ? AND (? = 0 OR created > ?)",
        (key, TTL, time.time() - TTL),
    ).fetchone()
    return row[0] if row else None

def store(db, model, messages, params, response):
    db.execute(
        "INSERT OR REPLACE INTO cache (key, created, response) VALUES (?, ?, ?)",
        (make_key(model, messages, params), time.time(), response),
    )
    db.commit()

db = sqlite3.connect("llm_cache.db")
db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, created REAL, response TEXT)")

def ask(model, messages, **params):
    hit = lookup(db, model, messages, params)
    if hit is not None:
        print("cache: HIT")
        return hit
    print("cache: MISS")
    answer = call_your_api(model, messages, **params)  # your existing call
    store(db, model, messages, params, answer)
    return answer
```

Two details matter. `sort_keys=True` makes the JSON stable, so the same request always hashes to the same key. And this is an exact-match cache: "How do I reset my password?" and "how do I reset my password?" are different keys. That is fine for reruns and retries; it is not fuzzy matching, so do not expect near-duplicate questions to hit.

## When not to cache

Some answers must never come from a saved copy. Skip the cache when:

- **The answer must be fresh.** Anything that reads live data, today's prices, current stock, the time, "what happened this morning". A cached answer here is a wrong answer.
- **The data is personal.** If the response depends on the specific user, their cache entry would sit on disk where the next user could reach it. Cache per user, or not at all.
- **The output is meant to vary.** High temperature creative generation is varied on purpose; caching collapses that variety back to one sample.

Two safety rails handle most of this. A TTL (time to live) expires entries after a set time, so stale answers rot out on their own; set `TTL = 0` only for prompts that are genuinely deterministic. And a version string (`CACHE_VERSION` in the example) lets you invalidate everything at once: bump it whenever you change the system prompt or logic, and old entries simply stop matching. Never reuse a key across prompt versions.

## Let the provider cache the boring part

A separate trick exists for long, repeated prompts: many LLM APIs offer provider-side prompt caching, where the provider keeps the stable prefix of your prompt, usually the system prompt and any long reference text, on their side, so repeat requests that share that prefix can come back cheaper and faster. The mechanics and pricing differ per provider, so check your provider's docs for how to mark the cacheable prefix and how billed, cached tokens are priced. The general principle is the same everywhere: put the stable part of the prompt first and the changing part last, and only the changing part gets full-price treatment.

This complements your own cache rather than replacing it. Your cache skips the API call entirely on exact matches; prompt caching cheapens the calls that do go through. And if you're picking a coding plan for agent work anyway, here's our coupon for [10% off GLM coding plans](https://z.ai/subscribe?ic=R0K78RJKNW).

## Prove it works

Trust nothing you did not measure. Two checks:

First, count hits and misses. The `print("cache: HIT")` line above is the minimal version; replace it with a counter or a log line and watch the ratio over a day. If your hit rate is near zero, your inputs vary more than you thought, and the cache is just overhead.

Second, the instant rerun test:

```bash
time python ask.py "summarize this changelog"
time python ask.py "summarize this changelog"
```

The first run takes normal API latency and prints `cache: MISS`. The second should finish in milliseconds and print `cache: HIT`, returning byte-identical output. If the second run is slow or misses, your key is unstable, usually a timestamp, a random seed, or an unsorted dict leaking into the payload.

One habit that pays off later: log the model and parameter set alongside each hit, so when an answer looks wrong months from now you can find the exact cache entry that produced it and delete that row. There's [more on our blog](https://claw.rommark.dev) if you like this kind of plumbing.

## The checklist

```
[ ] key = hash(version + model + full messages + every parameter)
[ ] JSON serialized with sort_keys=True (no unsorted dicts in the key)
[ ] CACHE_VERSION bumped every time the prompt or logic changes
[ ] TTL set for anything that can go stale
[ ] no caching for fresh, personal, or high-temperature answers
[ ] cache file excluded from git and kept off shared machines
[ ] hits and misses logged
[ ] second identical call returns in milliseconds
```

One more thing before you ship: the cache file holds full prompts and responses, so treat it like a log of everything your users said. Keep it out of your repo, set sensible file permissions, and delete it when the tool retires.

Caching handles the repeats; the budget side is its own job. For that, read [Stop burning AI coding credits: what eats tokens and how to budget](https://wurk.fun/blog/stop-burning-ai-coding-credits-what-eats-tokens-and-how-to-budget), which covers where your tokens actually go when every call is different.

If this saved you a rerun or two this week, a small tip on WURK is a nice way to say so.
