DeepSeek context caching is one of the few API cost levers that rewards better prompt hygiene rather than more infrastructure. The idea is simple: if many requests begin with the same token sequence, DeepSeek can reuse the cached computation for that prefix and bill the repeated part more cheaply. The catch is equally simple: caching follows tokens, not intent. Two prompts about the same topic will not share a cache if their first few hundred tokens differ.
That makes caching less of a magic discount and more of a prompt-layout discipline. You get the benefit by designing requests so the stable part comes first and the changing part comes last.
What DeepSeek context caching actually reuses
Context caching is prefix caching. The provider looks at the beginning of your request and tries to match it against previously processed prefixes. The match continues token by token until the first difference. Everything before that boundary can be a cache hit; everything after it is a miss. That is why a stable system prompt, a fixed set of tool definitions, or the same long reference document can be reused across many calls, while a timestamp near the top can poison the whole request.
Think of the cache boundary as a token boundary, not a semantic one. Reordering a JSON schema, changing whitespace in a system prompt, or inserting a random request ID can break the prefix even if the meaning is identical. The practical rule is: put everything that repeats first, and put everything that changes last.
If two requests share a token-for-token prefix, the second can reuse cached work. If they share only a topic, they will not.
Design a cache-friendly prefix
Put the system prompt, role instructions, and output format first. Keep them byte-for-byte identical across calls.
Put tool and function schemas next. Serialize them deterministically: same key order, same whitespace, same optional fields.
Put few-shot examples before the user task. Reuse the same examples across a batch.
For document Q&A, put the full document before the question. Ask many questions against the same prefix instead of rebuilding the document each time.
Move volatile data to the end: user question, timestamps, request IDs, session state, and retrieved chunks that change per call.
This layout also makes debugging easier. When a cache hit rate is low, diff the first few hundred tokens of two requests. The first differing token is your cache boundary.
Runnable example: one stable prefix, many requests
The sample below uses the OpenAI SDK against AiCredits' DeepSeek endpoint. The system prompt is deliberately constant; only the user snippet changes. Run two snippets in a row and inspect the usage object for cache hit and miss fields. The code guards for those fields so it still runs if the response shape changes.
import os
from openai import OpenAI
client = OpenAI(
base_url='https://api.aicreditsapi.com/v1',
api_key=os.environ['AICREDITS_API_KEY'],
)
# Stable prefix: keep this byte-for-byte identical across requests.
REVIEW_SYSTEM = '''You are a senior Python reviewer.
Return a short list of concrete issues.
For each issue, include: severity, line hint, why it matters, and a fix.
Do not rewrite the whole file.
Prefer correctness and security over style.
'''
def review_snippet(snippet: str) -> str:
response = client.chat.completions.create(
model='deepseek-v4-flash',
messages=[
{'role': 'system', 'content': REVIEW_SYSTEM},
{'role': 'user', 'content': snippet},
],
temperature=0.2,
)
usage = response.usage
hit = getattr(usage, 'prompt_cache_hit_tokens', None)
miss = getattr(usage, 'prompt_cache_miss_tokens', None)
if hit is not None:
print(f'cache hit tokens: {hit}; miss tokens: {miss}')
return response.choices[0].message.content
snippets = [
'def add(a, b): return a + b',
'def load(path): return open(path).read()',
]
for snippet in snippets:
print(review_snippet(snippet))
print('---')
The same pattern works for a long policy document, a codebase summary, or a fixed set of examples. Keep REVIEW_SYSTEM outside the loop and do not interpolate timestamps into it. If you need per-request metadata, put it in the user message after the stable prefix. For harder review tasks, switch the model to deepseek-v4-pro; the prefix layout stays the same, but pro costs more than flash.
Cache-friendly vs cache-hostile prompt layouts
| Prompt pattern | Cache behavior | Better pattern |
|---|---|---|
| System prompt + timestamp + user question | Timestamp changes every request; cache misses start at the timestamp | Move timestamp to the end of the user message or drop it |
| Few-shot examples + task | Stable examples can be reused across a batch | Keep examples identical; change only the final task |
| Long reference document + question | Document prefix can be reused for many questions | Put document first; batch questions against the same document |
| JSON tool schema with random key order | Same schema, different order means different prefix | Serialize schemas deterministically |
| Retrieved chunks in random order | Same chunks, shuffled order means cache miss | Sort chunks by stable ID before insertion |
The table is not about saving tokens on the first call. The first call is always a miss. Caching pays off when the same prefix is reused enough times that the cheaper hit rate outweighs the effort of keeping the prefix stable.
How to verify cache hits
Do not assume caching is working because the prompt looks stable. Instrument the response usage. DeepSeek-compatible responses can expose cache hit and miss token counts; read them defensively and log them per request. Compare a batch that reuses one prefix with a batch where each request has a unique prefix. If the hit count stays at zero, diff the first few hundred tokens.
Log cache hit and miss fields next to a request label.
Run the same prompt twice with no changes; the second call should show a hit if the prefix is long enough and the cache is warm.
Change one whitespace character in the system prompt and confirm the hit disappears. That tells you the boundary is real.
Keep a regression test that sends a fixed prefix and asserts a nonzero hit count when the provider returns the field.
When caching is not worth the complexity
One-off prompts or low-volume scripts: the first request is a miss, and there may be no second request.
Highly dynamic RAG: if every query retrieves a different document set, the prefix changes and caching rarely helps.
Prompts that need per-user context at the top: move the user context to the end, or accept misses.
Very large prefixes that hurt relevance: caching makes repeated input cheaper, but it does not make irrelevant context useful.
Cache-friendly design is a tradeoff, not a free win. It pushes you toward stable system prompts and deterministic serialization, which is usually good engineering anyway. But if the prefix is huge and rarely reused, simplify the prompt instead of optimizing the cache.
A practical checklist
Freeze the system prompt and version it outside the request.
Put tools, examples, and documents before the user question.
Serialize JSON deterministically.
Remove timestamps, random IDs, and session tokens from the prefix.
Batch questions against the same document or codebase.
Log cache hit and miss fields and review them weekly.
Check current DeepSeek rates at aicreditsapi.com/deepseek-prices; cache hits are cheaper than misses, and off-peak requests cost less than peak requests.
Use deepseek-v4-flash as the default and deepseek-v4-pro only when the task needs more reasoning.
AiCredits provides DeepSeek API credits to international developers who do not have a Chinese phone or bank account. The context caching behavior is part of the DeepSeek API; AiCredits passes it through. Check current rates at aicreditsapi.com/deepseek-prices.
FAQ
DeepSeek handles prefix caching on its side; you do not send a special cache flag in the request. Your job is to keep the prefix stable so repeated requests can match it.
Any token change in the prefix can break it: whitespace, timestamps, random IDs, tool schema order, or retrieved chunks in a different order. The cache matches tokens, not meaning.
Only when the same retrieved chunks or the same fixed knowledge base are reused. If every query retrieves a different document set, the prefix changes and caching rarely helps.
No. The first request is a miss, so caching pays off only when a stable prefix is reused across multiple calls.
Inspect the response usage fields for cache hit and miss tokens. Compare a batch with one shared prefix against a batch with unique prefixes per request.
Use deepseek-v4-flash as the default. Switch to deepseek-v4-pro when the task needs stronger reasoning; pro costs more than flash, but the prefix strategy is the same.