Caching is the single biggest lever on DeepSeek API spend, and also the most misunderstood. Most teams assume the discount is something the server hands out automatically. It is automatic — but whether you receive it is entirely a property of how you write your prompt. Two applications making the same number of calls, against the same models, can end up on opposite sides of the cache-hit line purely because one of them puts a timestamp at the top of its system message.
Here is the mechanics, three runnable patterns, and the specific mistakes that quietly reset your hit rate to zero.
What DeepSeek context caching actually caches
Context caching does not cache answers, and it does not cache your conversation. It caches the model's key/value attention state for a prefix of your input: the expensive intermediate work the model does before it writes a single output token.
Every request is a token sequence. Before generating anything, the model runs that sequence through its transformer stack. When a later request begins with the exact same tokens as an earlier one, the stored KV state for that shared prefix can be reused instead of recomputed. Same answer quality, faster time to first token, and the cached portion of your input is billed at a lower input rate than fresh tokens. Generated tokens are never cached, and off-peak requests are cheaper than peak ones to begin with — current rates live at aicreditsapi.com/pricing.
One rule decides your bill: the longest identical prefix
Caching is a strict prefix match evaluated from token 0 forward. The instant your prompt diverges from one the server has already seen and kept, everything after that divergence is a miss.
The consequence is counterintuitive: one changing character near the start of your prompt costs far more than a large changing block near the end. Inject a timestamp, a session UUID, or a user's name into your system message and you invalidate the entire prefix behind it. Every request becomes a full miss and caching does nothing for you — which is exactly why so many teams report that "caching doesn't work."
Put the long-lived material first and the volatile material last. That is the whole strategy:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
# A large, stable block. The exact same string on every request.
POLICY = """
Refunds: within 30 days, no questions asked.
Escalations: anything mentioning legal goes to the duty manager.
Tone: plain, direct, no exclamation marks.
"""
ticket = "Customer says their CSV export failed twice this morning."
# BAD: a changing value sits in front of the stable block, so the whole
# prefix after it is a miss on every single request.
bad_messages = [
{"role": "system", "content": f"Session {os.urandom(4).hex()}. {POLICY}"},
{"role": "user", "content": ticket},
]
# GOOD: stable prefix first, volatile input last.
good_messages = [
{"role": "system", "content": POLICY},
{"role": "user", "content": ticket},
]
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=good_messages,
)
print(resp.choices[0].message.content)
Measure it: read the cache fields on the response
You cannot optimize what you cannot see. DeepSeek reports cache accounting alongside ordinary token usage, so you can log a hit rate per request instead of guessing. Field naming follows DeepSeek's own convention; the helper below is defensive, so it works whether your gateway surfaces those fields as attributes or as extra usage keys. Run the loop twice — the second pass over an identical prefix is where the hits show up.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
def cache_stats(usage) -> dict:
extra = getattr(usage, "model_extra", None) or {}
def pick(name):
value = getattr(usage, name, None)
if value is None:
value = extra.get(name)
return value or 0
hit = pick("prompt_cache_hit_tokens")
miss = pick("prompt_cache_miss_tokens")
total = hit + miss
return {
"hit": hit,
"miss": miss,
"hit_rate": round(hit / total, 3) if total else 0.0,
}
messages = [
{"role": "system", "content": "You are a terse technical editor."},
{"role": "user", "content": "Explain a KV cache in two sentences."},
]
for i in range(2):
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=messages,
)
print(f"call {i + 1}:", cache_stats(resp.usage), "|", resp.choices[0].message.content[:60])
A cache-friendly batch pattern
The highest-leverage shape is many questions against one large shared context: a codebase digest, a contract, a spec, a policy manual, a long transcript. Build that shared block once as a string, keep it byte-identical across every call, and vary only the tail.
One caveat before you copy this: caching only engages once a prefix is long enough to be worth storing, so this pattern pays off with genuinely large stable blocks — not with a three-line system prompt. Measure it rather than assuming it.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1",
)
RULES = [
"Rule 1: no bare except clauses.",
"Rule 2: every public function needs a docstring.",
"Rule 3: prefer pathlib over os.path.",
"Rule 4: no mutable default arguments.",
"Rule 5: type hints on every public signature.",
"Rule 6: no print() in library code, use logging.",
"Rule 7: max line length 100 characters.",
"Rule 8: imports grouped stdlib, third-party, local.",
]
SPEC = "\n".join(
["You review Python pull requests against this style guide."] + RULES
)
QUESTIONS = [
"Which rule does a bare 'except:' violate?",
"Does os.path.join break any rule here?",
"Is 'def f(items=[]):' a problem?",
]
hits = misses = 0
for q in QUESTIONS:
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": SPEC}, # byte-identical every call
{"role": "user", "content": q}, # the only thing that varies
],
)
usage = resp.usage
extra = getattr(usage, "model_extra", None) or {}
hits += getattr(usage, "prompt_cache_hit_tokens", None) or extra.get("prompt_cache_hit_tokens", 0) or 0
misses += getattr(usage, "prompt_cache_miss_tokens", None) or extra.get("prompt_cache_miss_tokens", 0) or 0
print("Q:", q)
print("A:", resp.choices[0].message.content[:120])
print()
total = hits + misses
print("cache hits:", hits, "| misses:", misses)
print("hit rate:", round(hits / total, 3) if total else "n/a")
What silently kills your cache
A changing system prompt. Per-user personas, A/B-tested instructions, or an injected timestamp at the front resets the prefix for every request.
Reordered tool definitions. Function schemas are part of the prefix. If your framework serializes them with a different key order between deploys, the tokens differ and the cache misses — even though the meaning is identical.
Retrieved context pasted too early. If you put RAG chunks above your stable instructions, every new chunk reshuffles the shared prefix. Put instructions first, retrieved chunks after them.
Rebuilding the same string differently. A set iterated in nondeterministic order, or f-string concatenation versus a join, produces different tokens for identical intent.
Cache eviction between calls. Cached prefixes expire after a period of inactivity. A steady request stream keeps them warm; a slow trickle lets them go cold.
When caching will not save you anything
Caching rewards repetition, and only repetition. If every request is genuinely unique, you will see full misses and zero savings no matter how long your prompts are: one-shot short prompts, a chatbot where each user has separate history and no shared system prompt, a pipeline whose input document changes on every call.
The other honest caveat is structural. Only input is cached, never output. A workload dominated by generated text will barely move regardless of how good your hit rate looks. In those cases the real levers are different: send only the tokens you need, cut few-shot examples that are not earning their keep, and route routine work to the cheaper model.
Pick the model first, then cache
Model choice and caching are separate decisions, and you should make them in that order. Caching discounts the input of whichever model you choose — it does not make the wrong model right.
deepseek-v4-flash is the sensible default for nearly everything: fast, inexpensive, and the model that benefits most from aggressive caching in high-volume pipelines. deepseek-v4-pro costs more and earns its place on work that genuinely needs stronger reasoning — long multi-step analysis, difficult code review, planning across many constraints.
| Situation | Model | Why |
|---|---|---|
| High-volume classification, extraction, routing | deepseek-v4-flash | Inexpensive at scale; caching multiplies the savings on a shared prefix. |
| Batch Q&A over one large document | deepseek-v4-flash | The document becomes the cached prefix; only the question varies. |
| Multi-step reasoning over that same document | deepseek-v4-pro | Stronger reasoning on the hard steps, with the shared context cached to blunt the extra input cost. |
| One-shot unique prompts, no shared context | deepseek-v4-flash | Caching will not help here, so keep the model inexpensive instead. |
Both models are reachable through the same OpenAI-compatible endpoint, so switching between them is a one-string change. If you are outside China without a Chinese phone number or bank account, AiCredits is the practical route to DeepSeek credits — card or PayPal, no local verification hoops, and the same base_url and SDK you already use. Rates, including how cache hits are billed, are at aicreditsapi.com/pricing.
Five-minute checklist
Put the longest-lived content at token 0: system prompt, policy, schema, shared document.
Guarantee that content is byte-identical across requests — no timestamps, no session IDs, no random ordering.
Keep volatile input last.
Log hit and miss tokens per request and track hit rate as a dashboard metric, not a vibe.
Grow the cache footprint with one large stable block rather than many small prompts.
Re-measure after every prompt refactor. A harmless-looking formatting change can drop your hit rate to zero.
Caching is not a switch you flip. It is a property of how you write prompts — and the teams that save the most are simply the ones whose prompts were stable by design.
FAQ
No. The cached state is the same computation the model would have performed on that prefix anyway, so quality and determinism are unchanged. You are skipping recomputation, not skipping the reasoning.
No. It happens server-side and automatically. The only control you have is prompt shape — how much identical prefix your requests share and how stable it stays.
Yes. Caching applies to the input prefix, while streaming only affects how the output is delivered. Cache fields arrive with the usage information at the end of the stream.
Usually something near the start of the prompt is changing between calls — a timestamp, a user name, a reordered tool schema — or the shared prefix is simply too short to be cached. Check your hit-rate logging before blaming the provider.
Rarely. The shared prefix has to be substantial and reused often before the discounted input tokens move your total meaningfully, because generated output is never cached.
Start with deepseek-v4-flash and only move a task to deepseek-v4-pro when output quality is the bottleneck. Caching makes the costlier model easier to justify, but it does not make it free.