Free-tier quotas get spent on two things: repeated identical requests and unnecessary calls in general. A response cache and task deduplication are the cheapest economics around: zero rubles of infrastructure, minus 20–50% of spending in typical pipelines. Techniques and ready-made constructs below.
Response cache: a dictionary keyed by the prompt hash
import hashlib, json
_cache = {}
def cached_ask(client, model, messages, ttl=86400):
key = hashlib.sha256((model + json.dumps(messages)).encode()).hexdigest()
if key in _cache:
return _cache[key]
r = client.chat.completions.create(model=model, messages=messages)
_cache[key] = r.choices[0].message.content
return _cache[key]Hash of model + prompt = the key. Email classification, news summarization, answers to typical questions — in real pipelines 20–50% of requests repeat. In n8n — a cache node in front of the LLM node; in agent wrappers — the same dictionary around the call.
Deduplication before sending
- Normalizing the input: case, spaces, punctuation — “Say ok” and “say OK” must not be two different tasks.
- Grouping batches: 50 emails from one source with the same template — one template request plus local filling, not 50 calls.
- Cutting out the junk: spam, duplicates, and empty records are filtered by rules before the LLM node — free savings for the cheap tier.
- A cache-friendly head: the provider’s cache (the prompt cache) reinforces the local one — a stable head in both systems.
What can be cached and what cannot
| Request type | Cache | Why |
|---|---|---|
| Classification, summarization | Yes | Deterministic result |
| Code generation from a brief | With care | The same prompt ≠ the wanted result across iterations |
| Date-sensitive data | No | The answer will be stale by the second use |
| Personal dialogues | No | Dialogue context is unique |
The economics of the technique
A calculation from pipeline practice: a classification bot with 500 requests a day and a 30% repeat share saves 150 requests/day = 4,500 a month against the Groq quota (1000 RPD) — that is 4.5 days of quota. On a paid API the same share is direct money on the bill. Plus speed: a cache answer arrives instantly — the pipeline’s UX improves.
Compatibility with the provider’s prompt cache: the local cache saves request quotas, the provider’s saves on token price; they work together at different levels. The discipline of the cache-friendly head is in the workflow material.
Typical caching mistakes
The list is collected from pipeline reviews where the cache “did not work”: almost always the culprit is not the dictionary mechanics but the key, the normalization, or the lifetime. The seven points below close most such cases, and there is one check after every fix — a run of a typical pipeline day with a hit counter. The order is simple: first the key and normalization, then the TTL and the journal, and only then the storage.
- A key without the model name: switching models on the same prompt returns the old answer — the hit looks valid while the quality has slipped. The model name in the hash solves the problem at the key stage itself, before any manual answer checks.
- A hash over raw text: without normalizing case and spaces, “Say ok” and “say OK” become two entries, and the hit statistics deceive. The normalization from the deduplication block is applied to the cache key too — one pass covers both layers.
- One TTL for everything: classification lives for weeks, dated data for hours; a shared lifetime either freezes answers or devalues the cache. The TTL is split by request type according to the table above, and test runs live in a separate namespace; when the rules change, the TTL set is reviewed together with the cache as a whole.
- A cache without a journal: if hits are not counted, the technique’s economics stay invisible and it is unclear whether the layer pays off at all. The hit counter is written next to the spending journal — otherwise the efficiency measurement has nothing to feed on.
- Caching “live” context: a system prompt with a date, an exchange rate, or a username makes every request effectively different — no hits, while memory grows. Variable fields move out of the text into call parameters, and the key matches again.
- The cache as a substitute for deduplication: the layer above must cut the junk and group batches before the call; the cache catches only exact repeats and does not protect against extra requests with slightly different texts.
- Storage without cleanup: the dictionary grows for the whole life of the process, memory leaks, and entries from two weeks ago will never be needed again. The simplest option is a periodic cleanup by TTL while traversing the dictionary; the same trick works for a file cache.
After the fix, compare the repeat share in the journal with the cache-hit share for the same day. If the numbers match, the layer is tuned honestly; a gap of several times points to the key, the normalization, or “live” context in the system prompt. The dictionary mechanics from the ready-made construct do not change — only the wrapper around it gets fixed.
Frequently asked questions
Where is the cache stored? In process memory (a dictionary) for simplicity; for persistence — SQLite or a file; for distributed setups — Redis.
Invalidation? A TTL by time or an explicit cleanup when the rules change. Test runs — a separate cache namespace.
Cache creative tasks? No: generation “in spirit” must not repeat — sameness kills variation.
Measuring effectiveness? A cache-hit counter in the journal: a hit share below 10% — the cache was set up in vain; above 30% — it works.
A cache in a multi-threaded pipeline? An in-process dictionary is safe under a simple lock; for distributed workers — Redis with the same hash-based key. The key scheme does not change — only the storage does, so migrating between the options does not touch the calling code. Take the simplest lock possible: concurrent writes in pipelines are few, and cache reads are cheap.
What to do when changing models? If the model name is part of the key, old entries do not interfere: a new call gets a new key with no false hits. When the processing rules or the system prompt change, the cache is cleared entirely, and test runs keep living separately. The separate cache namespace survives afterwards too: a test run must not mix its answers into the production layer.
Cache streaming? The assembled final text is cached: the stream is delivered to the client as usual, and after completion the answer goes into the dictionary. A repeated request is delivered in full — for pipelines that is usually exactly what is needed; interactive dialogues bypass the cache.
How to estimate the benefit before implementing? A week of recording hashes without a cache will show the potential repeat share on your real data. If it is below the threshold from the effectiveness measurement, start with deduplication and junk filtering, not with the cache. That same week of recording will show which request classes duplicate most often: a ready-made queue for deduplication.
Cache and deduplication are the first optimization layer of any pipeline: free infrastructure, an instant result, measurable savings. The techniques above are ready to be dropped in. Practice is current as of autumn 2026.
