DeepSeek caching: arrange request prefixes and check hits
Put stable text at the start of repeated DeepSeek requests and check cache hits in usage token counts, following the docs. No API was run here.
Task and deliverable · Prepare the input and environment · Mechanism and data flow
At a glance
Repeated text requests often carry the same system prompt or the same long document. The official page says DeepSeek API's disk-based context caching is on by default for all users and needs no code changes. Each request triggers cache construction, and when a later request shares an overlapping prefix with an earlier one, the overlapping part is read from the cache and counts as a "cache hit." This tutorial uses that rule to arrange prefixes and to read two usage fields to check the result. The completion checks and the manual stop and cleanup steps here are editorial recommendations, not official behavior.
Task workflow
A hit needs a complete match with a persisted prefix unit
The docs say a hit requires the corresponding prefix to be "persisted", meaning written to the disk cache. Because of the Sliding Window Attention mechanism, storage and matching of cached prefixes differ from before. Each cached prefix is an independent, complete unit, and a later request hits only if it fully matches one such unit. Sharing some leading text is therefore not enough: the shared part must be exactly an existing unit. Use the current complete persisted-prefix-unit rule to assess a hit.
Prefix units are persisted at three points
The first is the request boundary: each request produces two cache prefix units, one at the end of the user input and one at the end of the model output, and a later request that fully matches either can hit. The second is common prefix detection: when the system sees a common prefix across several requests, it persists that prefix as its own unit, and a later request that fully reuses it can hit. The third is fixed token intervals: for long inputs or outputs, the system carves out units at fixed intervals so a long prefix is not uncacheable merely because it never reaches an end position. The source gives no number for that interval.
Read the result from usage; output stays random
The
usagesection of the response has two added fields.prompt_cache_hit_tokensis the number of input tokens in this request that hit the cache, andprompt_cache_miss_tokensis the number that did not. They describe only how the input was matched. The disk cache matches only the prefix of the user's input; the output is still generated by computation and inference and is influenced by parameters such astemperature, which adds randomness. A hit count therefore says nothing about whether an answer is correct or whether two outputs will match.Build and cleanup timing carries no fixed guarantee
The docs describe the cache as working without a guarantee of a 100% hit rate. Construction takes seconds, and once the cache is no longer in use it is cleared automatically, usually within a few hours to a few days. These are the docs' rough descriptions, not promises. A request sent right after another may therefore not find the cache that was just being built.
Task and deliverable
Repeated text requests often carry the same system prompt or the same long document. The official page says DeepSeek API's disk-based context caching is on by default for all users and needs no code changes. Each request triggers cache construction, and when a later request shares an overlapping prefix with an earlier one, the overlapping part is read from the cache and counts as a "cache hit." This tutorial uses that rule to arrange prefixes and to read two usage fields to check the result. The completion checks and the manual stop and cleanup steps here are editorial recommendations, not official behavior.
Prepare the input and environment
- An account and credentials that allow you to call the DeepSeek API. The source page gives no endpoint, model name, authentication method or permission requirement, so verify them in the official documentation before you start. This tutorial does not invent them.
- A set of repeated text requests you are allowed to use: a shared system message, the same document or the same conversation history, plus a question that changes.
- An environment you control for sending requests and saving the
usageobject from each response. The source supplies no runnable client code, so you must prepare that part yourself. - Acceptance that caching makes no hit guarantee: the docs state there is no guarantee of a 100% hit rate, so one miss is not by itself an error.
Mechanism and data flow
A hit needs a complete match with a persisted prefix unit: The docs say a hit requires the corresponding prefix to be "persisted", meaning written to the disk cache. Because of the Sliding Window Attention mechanism, storage and matching of cached prefixes differ from before. Each cached prefix is an independent, complete unit, and a later request hits only if it fully matches one such unit. Sharing some leading text is therefore not enough: the shared part must be exactly an existing unit. Use the current complete persisted-prefix-unit rule to assess a hit.
Prefix units are persisted at three points: The first is the request boundary: each request produces two cache prefix units, one at the end of the user input and one at the end of the model output, and a later request that fully matches either can hit. The second is common prefix detection: when the system sees a common prefix across several requests, it persists that prefix as its own unit, and a later request that fully reuses it can hit. The third is fixed token intervals: for long inputs or outputs, the system carves out units at fixed intervals so a long prefix is not uncacheable merely because it never reaches an end position. The source gives no number for that interval.
Read the result from usage; output stays random: The usage section of the response has two added fields. prompt_cache_hit_tokens is the number of input tokens in this request that hit the cache, and prompt_cache_miss_tokens is the number that did not. They describe only how the input was matched. The disk cache matches only the prefix of the user's input; the output is still generated by computation and inference and is influenced by parameters such as temperature, which adds randomness. A hit count therefore says nothing about whether an answer is correct or whether two outputs will match.
Build and cleanup timing carries no fixed guarantee: The docs describe the cache as working without a guarantee of a 100% hit rate. Construction takes seconds, and once the cache is no longer in use it is cleared automatically, usually within a few hours to a few days. These are the docs' rough descriptions, not promises. A request sent right after another may therefore not find the cache that was just being built.
Workflow map
| Stage | What happens |
|---|---|
| A hit needs a complete match with a persisted prefix unit | The docs say a hit requires the corresponding prefix to be "persisted", meaning written to the disk cache. |
| Prefix units are persisted at three points | The first is the request boundary: each request produces two cache prefix units, one at the end of the user input and one at the end of the model output, and a later request that fully matches either can hit. |
| Read the result from usage; output stays random | The usage section of the response has two added fields. |
| Build and cleanup timing carries no fixed guarantee | The docs describe the cache as working without a guarantee of a 100% hit rate. |
Complete the task
Split each request into fixed and changing content: Divide each request into the content that stays the same and the content that changes. In the official long-text Q&A example, the fixed parts are the system message "You are an experienced financial report analyst..." and the <financial report content> in the user message, and only the closing question changes. This split decides whether a reusable prefix unit can form later.
Place stable content at the front of messages: In messages, keep the identical system message and document first and put the changing question at the end of the user message. The official example is laid out this way: the same report content comes first, followed by a request to summarize key information, analyze profitability, or analyze the ratio of revenue to expenses. Inserting changing text before the document would break the complete-prefix match. This applies the documented rule; the exact layout is up to your request.
Send the requests in order and save each usage object: Send the three requests one after another, and record prompt_cache_hit_tokens and prompt_cache_miss_tokens from each response together with the request number and an input label. Save the two counts rather than only the answer, because the answer does not reflect cache state. You must write the recording code yourself. The source's code blocks are messages data fragments labeled text, not runnable Python or a complete API request, and they contain no sending logic.
Predict each outcome from the official examples: In the multi-round example, the second request fully contains the first request's prefix, so it can reuse the first request's cache prefix unit and counts as a hit. In the long-text example, neither of the first two requests hits. The first produces a unit A+B, and the second, A+C, does not fully match it. The system then detects the common A, which is the system message plus the report content, and persists it, so the third request, A+D, can fully match and hit. This is the official documentation's example, not an observation from this batch.
Decide success, failure, empty output and stopping: These criteria are editorial recommendations, not official behavior. Success: both fields are present, the third request's prompt_cache_hit_tokens is above 0, and you have separately checked the answer content. Failure: the request errors, either field is missing, or the third request still shows 0. That last case may mean the cache was still being built or may fall under the no-guarantee rule, so you can retry once later without concluding that caching is broken. Empty output: if the response has no answer text, record usage first, then inspect the request itself. User stopping: you decide when to stop sending. The source provides no cancellation API, and none is assumed here.
Clean up on every exit path: Whether you succeeded, failed, got empty output or stopped by hand, clean up: remove or rotate credentials from scripts, notes and shared records, and delete request logs that hold report content you no longer need. The official cache is cleared automatically after it stops being used, usually within a few hours to a few days, but this page gives no method for manual deletion or scheduling a clear. Do not treat the usual interval as a fixed guarantee. Credential and log cleanup is an editorial recommendation, not an official procedure.
Worked example
Take the official long-text Q&A. All three requests use the same system message, "You are an experienced financial report analyst...", and each user message begins with <financial report content>. The closing questions ask for a summary of key information, an analysis of profitability, and an analysis of the ratio of revenue to expenses. The docs say the first two requests do not hit the cache. After they finish, the system identifies the system message plus the report content as a cache prefix unit and persists it, and the third request hits because it fully matches that unit. When you read your records, the expectation is that the third request's prompt_cache_hit_tokens covers the shared A and prompt_cache_miss_tokens covers the input that still missed. That is only the expectation from the official example; no real record exists from this batch. The multi-round example is separate: the first request has a system message and one question, the second adds an assistant reply and a new question, and the docs say it fully reuses the first request's cache prefix unit. These code blocks are data fragments, not complete requests.
messages: [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "What is the capital of China?"}
]
messages: [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "What is the capital of China?"},
{"role": "assistant", "content": "The capital of China is Beijing."},
{"role": "user", "content": "What is the capital of the United States?"}
]
messages: [
{"role": "system", "content": "You are an experienced financial report analyst..."},
{"role": "user", "content": "<financial report content>\n\nPlease summarize the key information of this financial report."}
]
messages: [
{"role": "system", "content": "You are an experienced financial report analyst..."},
{"role": "user", "content": "<financial report content>\n\nPlease analyze the profitability of this financial report."}
]
messages: [
{"role": "system", "content": "You are an experienced financial report analyst..."},
{"role": "user", "content": "<financial report content>\n\nPlease analyze the ratio of the company's revenue to expenses."}
]
Check the result and failure paths
- Field check: confirm each response's
usagehas bothprompt_cache_hit_tokensandprompt_cache_miss_tokens, and record them against the request number. This is a static check and says nothing about answer correctness. - Order check: a later request can hit only after the shared prefix has been persisted. A miss on the second request, A+C, is expected and a hit on the third, A+D, is possible, so do not treat zeros on the first two as a fault.
- Semantic check: a hit or miss describes input tokens only. Verify answer correctness yourself against your own standard, and remember that
temperatureand similar parameters make output random. - Failure and stop check: on an error, a missing field, empty output or your own decision to stop, save the
usagerecords you already have and then run cleanup. These completion criteria are editorial recommendations, not official rules.
Scope and limits
- The source covers only this page's current prefix persistence and hit rules. It gives no price, quota, version support or account permission, so this tutorial draws no conclusion about cost or availability.
- Caching does not guarantee a hit, construction takes seconds, and clearing usually happens within a few hours to a few days. None of these is a fixed promise.
- The source's
messagescode blocks are data fragments, not complete runnable Python or API requests. They do not prove semantic correctness and contain no endpoint, authentication or error handling. - The source gives no number for the fixed token interval and describes no request-cancellation interface, and this tutorial adds neither.
No product or API was called, installed or executed in this batch. The workflow comes from the official page s1, the examples are official documentation examples rather than observations from this batch, and the completion checks and manual stop and cleanup steps are editorial recommendations, not official behavior.
Article sources
Original editorial content; official descriptions and checking suggestions are distinguished.