DeepSeek Context Caching: How It Works, Pricing, and Cache Hits

DeepSeek context caching automatically reuses eligible prompt-prefix processing on the hosted API. Cached input has a lower token rate, while output is billed separately. The practical task is to preserve useful repeated material and check the usage returned with each request. See DeepSeek’s caching guide and pricing table.

This guide explains the current matching rules, compares cache metrics across three API formats, and provides a Python diagnostic. It also works through a realistic cost calculation so you can distinguish a large cached-input discount from the savings on a complete request.

Documentation and prices checked November 18, 2026. The Python example was checked offline; no paid API benchmark or measured speedup is claimed.

In this guide

How DeepSeek Context Caching Works

Reuse requires a complete match to a prefix unit already saved to disk. Units form at input/output endpoints, when shared prefixes are detected, and at intervals within long sequences. The current rules explain two patterns:

Request patternWhat can be reused
A+B, then A+B+CThe later request can reuse persisted A+B.
A+B, then A+C, then A+DIf only A+B exists initially, request two establishes shared A; request three can reuse it.

Here, A is shared material. These are eligibility examples, not guaranteed hit sequences.

DeepSeek context caching documentation explaining prefix persistence and cache hit rules with matching examples

For a document assistant, that distinction changes the experiment you should run. Keep the reference unchanged, ask several useful questions, and inspect every response. One miss is insufficient evidence that your prompt layout is wrong. Conversely, one hit does not establish the savings for an entire day of traffic.

Think about the material your application actually repeats: instructions, a reference document, or earlier conversation turns. Similar meaning alone is not a reason to budget for reuse. Compare the assembled inputs, including their ordering, before comparing their costs.

DeepSeek Cache Hit and Cache Miss Pricing

The following official model rates are in USD per 1 million tokens. At the review date, deepseek-flash serves DeepSeek-V4.1-Flash-1017 and deepseek-v4-pro serves DeepSeek-V4-Pro-0813.

ModelPeriodInput: hitInput: missOutput
deepseek-flashOff-peak$0.003$0.15$0.60
deepseek-flashPeak$0.006$0.30$1.20
deepseek-v4-proOff-peak$0.022$0.66$1.98
deepseek-v4-proPeak$0.044$1.32$3.96

Peak windows are 01:00–04:00 and 06:00–10:00 UTC, Monday through Friday, excluding Chinese public holidays. Other hours are off-peak. Convert UTC for your U.S. location and the relevant date; daylight saving time affects local scheduling.

DeepSeek Flash and V4 Pro cache hit, cache miss and output token pricing during peak and off-peak hours

Calculate the Whole Request, Including Output

For a text request, let H be cached input tokens, M uncached input tokens, and O all billed output tokens. Use the applicable model and tariff for each request:

Request cost in USD =
(H × cache-hit rate + M × cache-miss rate + O × output rate)
÷ 1,000,000

Consider an illustrative Flash off-peak request with 10,000 cached input tokens, 1,000 uncached input tokens, and 1,000 output tokens. These are assumed counts, not results from the Python script below.

ComponentCalculationCost
Cached input10,000 × $0.003 ÷ 1,000,000$0.00003
Uncached input1,000 × $0.15 ÷ 1,000,000$0.00015
Output1,000 × $0.60 ÷ 1,000,000$0.00060
TotalSum of the three components$0.00078

If all 11,000 input tokens missed, the same token volume would cost $0.00225, including output. The difference is $0.00147, or 65.33% of the complete request cost.

The cached-input unit price is 98% below the miss price in this example. That percentage applies to the 10,000 hit tokens. The variable input and generated output explain why the overall saving is smaller.

Include initial misses when evaluating a batch. If two of ten otherwise identical requests were all misses and eight had the illustrated hit counts, the batch would cost $0.01074 instead of $0.02250: a 52.27% saving. This is a hypothetical distribution, not a prediction about which calls will hit.

This calculation covers model tokens. Keep separately priced services outside this subtotal, and include all billed attempts when estimating cost per completed task. A comparison that silently drops retries or unsuccessful outputs overstates the benefit.

How to Measure Cache Hits Across API Formats

Read the response’s usage object using the schema for your endpoint. DeepSeek’s Chat Completions, Responses, and Messages-compatible interfaces use different accounting conventions.

DeepSeek Chat Completions API usage fields showing cached and uncached prompt token counts
InterfaceCached inputUncached inputTotal input
Chat Completionsprompt_cache_hit_tokensprompt_cache_miss_tokensprompt_tokens
Responsesinput_tokens_details.cached_tokensinput_tokens minus cached inputinput_tokens
Messages compatibilitycache_read_input_tokensinput_tokensinput_tokens + cache_read_input_tokens + cache_creation_input_tokens

In Messages compatibility, cache_creation_input_tokens is currently zero. In Chat Completions, prompt_tokens_details.cached_tokens duplicates the hit count; adding both would double-count cached input.

DeepSeek Responses API documentation showing cached input tokens in the response usage object

For monitoring, calculate the cache-hit rate by token count: cached input divided by total input. This measures token coverage. Keep it separate from the percentage of requests containing any hit.

Request cache-hit rate by token count = hit tokens / total input tokens

Workload cache-hit rate by token count =
sum(hit tokens) / sum(total input tokens)

For example, a 100-token request with 100 hits and a 9,900-token request with no hits produce 1% coverage overall. Averaging their individual percentages would produce 50%, which badly misrepresents the workload. If the denominator is zero, report the ratio as unavailable.

Missing usage is not zero usage. Preserve a separate “unavailable” state when a wrapper drops fields or a response is incomplete. Otherwise, a logging defect can appear to be a sudden caching failure. Keep the raw usage object when your logging policy permits, making future accounting corrections possible.

Streaming Responses Need Their Final Usage Record

For Chat Completions, full usage arrives on the last content chunk before [DONE], with or without include_usage; there is no separate usage-only chunk. For Messages compatibility, use final message_delta.usage without adding initial message_start usage. See the Chat Completions reference and Messages streaming guide.

DeepSeek Anthropic Messages API streaming documentation explaining cache read tokens and final usage accounting

For Responses, inspect response.usage in the final response.completed, response.incomplete, or response.failed event. Preserve an unavailable state if usable metrics are missing. See the Responses streaming guide.

A disconnected stream may leave your local record incomplete. Keep that record separate from confirmed zero hits and reconcile it through your normal billing process. The nonstreaming example below avoids this collection problem.

Python Example: Check Your Actual Cache Usage

This example sends three questions about one document through the official Chat Completions endpoint. It prints observed token counts and refuses inconsistent data. It deliberately avoids an “expected output” that could suggest a guaranteed cache pattern.

  1. Use Python 3 and make your DeepSeek API key available in the DEEPSEEK_API_KEY environment variable.
  2. Create a UTF-8 file named reference.txt containing a document you are authorized to send to the hosted API.
  3. Save the code as check_deepseek_cache.py in the same folder and run python check_deepseek_cache.py.

Authentication and the endpoint follow DeepSeek’s first API call guide. The example uses standard-library modules, disables thinking, and caps the requested output at 128 tokens. Running it makes three billable model requests if all three calls succeed.

import json
import os
import time
import urllib.request
from pathlib import Path

api_key = os.environ.get("DEEPSEEK_API_KEY")
if not api_key:
    raise SystemExit("Set DEEPSEEK_API_KEY before running this script.")

document = Path("reference.txt").read_text(encoding="utf-8")
if not document.strip():
    raise SystemExit("reference.txt must contain your reusable document.")

questions = [
    "Summarize the document in two sentences.",
    "What are its most important limitations?",
    "What should a reader do next based on this document?",
]
fields = (
    "prompt_cache_hit_tokens",
    "prompt_cache_miss_tokens",
    "prompt_tokens",
    "completion_tokens",
)

for number, question in enumerate(questions, start=1):
    payload = {
        "model": "deepseek-flash",
        "user_id": "cache_demo_user_01",
        "thinking": {"type": "disabled"},
        "stream": False,
        "max_tokens": 128,
        "messages": [
            {
                "role": "system",
                "content": "Answer briefly using the reference. "
                           "Say when the reference does not answer the question.",
            },
            {
                "role": "user",
                "content": "Reference:\n" + document
                           + "\n\nQuestion: " + question,
            },
        ],
    }
    request = urllib.request.Request(
        "https://api.deepseek.com/chat/completions",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Authorization": "Bearer " + api_key,
            "Content-Type": "application/json",
        },
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=120) as response:
        result = json.load(response)

    usage = result.get("usage")
    if not isinstance(usage, dict) or any(
        usage.get(field) is None for field in fields
    ):
        print(f"Request {number}: usage unavailable or incomplete")
    else:
        hit, miss, total, output = (usage[field] for field in fields)
        if any(type(value) is not int or value < 0
               for value in (hit, miss, total, output)):
            raise ValueError("Unexpected usage values.")
        if hit + miss != total:
            raise ValueError("Input counts do not reconcile.")
        coverage = f"{hit / total:.2%}" if total else "N/A"
        print(f"Request {number}: hit={hit}, miss={miss}, "
              f"input={total}, output={output}, coverage={coverage}")

    if number < len(questions):
        time.sleep(3)  # Demonstration pause, not a readiness guarantee.

The three-second pause is an illustrative choice, not a documented readiness threshold. There is no guarantee that this short run will produce a hit. Use representative material from your workload instead of adding filler to manufacture a larger prefix.

The demonstration identifier represents one test user. For a deployed application, derive the identifier from trusted backend state using the isolation approach below. Do not assign this shared demo value to all customers.

An HTTP or network exception stops this small diagnostic. It does not automatically retry and create more requests. If the script prints “usage unavailable or incomplete,” inspect the response and any intermediary before interpreting your cache performance. Review answer quality separately; this diagnostic intentionally prints only usage.

How to Structure Prompts for Better Reuse

A useful starting layout is stable instructions, reusable reference material, then the current task. Treat this as an engineering recommendation: preserve the information needed for a correct answer while making accidental changes easier to identify.

System message:
  Stable task instructions and response requirements

User message:
  Reference document, with consistent formatting
  Current question
  Any request-specific details needed to answer it

For instance, a support assistant could place the relevant product policy before the customer’s question. Store the request’s trace ID in application logs instead of inserting it ahead of the policy. When a date matters to the answer, include it deliberately where it belongs; do not remove necessary facts for a higher percentage.

  • Version reusable content. Record a document or prompt version with your measurements. Compare runs using the same version before attributing a difference to caching.
  • Keep construction predictable. Avoid incidental reordering of reference sections, examples, or messages. Normalize your own formatting where doing so preserves meaning.
  • Make dynamic content visible. During development, compare two assembled prompts and locate their first difference. Inspect content order, not just the template file.
  • Preserve relevant conversation history. Maintain the sequence the task requires. Do not silently drop a user correction because an older prefix is easier to reuse.
  • Measure useful work. Keep answer accuracy, required context, and total token volume beside cache coverage.

Retrieval-augmented generation requires a tradeoff. A query-specific document selection may repeat less content but send far fewer tokens. Compare the cost and quality of a compact relevant selection with a larger reusable reference. A high coverage percentage is not enough to justify sending material the task does not need.

Make one layout change at a time. For example, first move unnecessary tracing metadata out of the prompt, then compare a representative set of tasks. Changing the model, reference length, retrieval method, and question set simultaneously makes any improvement difficult to explain.

Troubleshooting Zero Hits and Missing Cache Metrics

Start with the symptom you can actually observe. The checks below are diagnostic recommendations based on the documented matching and usage rules, not a promise that every miss has a client-side fix.

SymptomWhat to check next
The second related request has zero hitsCompare its prefix with the persisted-unit patterns above. Observe more representative requests before judging the layout.
Coverage changes after an application updateCompare prompt versions, message ordering, selected model, and the intended user-isolation identity.
The prompt looks identical, but results varyCompare the assembled inputs rather than screenshots. Keep an all-miss budget available.
No cache fields appearConfirm the endpoint’s usage schema and inspect whether your SDK, proxy, or logging layer omitted fields.
Streaming usage is absentCheck whether the final usage-bearing event or chunk was received.
Coverage rises but spending does not fallCompare total input, output, retries, tariff periods, and completed-task counts.

A fast answer is not proof of a hit. Queueing, network conditions, output length, and other variables affect elapsed time. Use token counters for cache accounting. If speed is part of your evaluation, measure time to first token and time to completion separately over comparable tasks.

Avoid an endless loop that resubmits requests until the dashboard looks favorable. It spends money without answering whether normal production traffic benefits. A bounded sample, with missing records clearly labeled, is more useful for an implementation decision.

Cache Isolation and Retention

DeepSeek documents user_id for separating downstream users’ KV caches within one account. The isolation guide recommends ASCII letters, digits, underscores, and hyphens; the UTF-8 value must be at most 512 bytes and contain no personal information.

DeepSeek API user_id isolation documentation explaining KV cache separation between users
Request interfaceIsolation field
Raw Chat Completions JSONuser_id
Chat Completions through the OpenAI Python SDKextra_body={"user_id": "opaque_id"}
Responsesuser
Messages compatibilitymetadata.user_id

The Responses mapping is specified in its compatibility documentation. Use a stable opaque identifier for the intended user boundary. As an implementation consequence, randomly changing that identity between requests makes a controlled reuse comparison harder.

Derive this value from your authenticated application state. A client-supplied identifier should not decide which documents someone may access. Cache isolation does not replace your application’s authorization checks, and combining unrelated users under one identifier is not an appropriate cost optimization.

DeepSeek describes persistence as taking seconds, with unused entries typically cleared after hours to days. Reuse is best effort, without a guaranteed hit rate or fixed TTL. See the cache lifecycle notes.

Treat this timing as an operational characteristic, not a deletion commitment for all account data. Budget for requests after idle periods without assuming the earlier discount remains available. Keep any required conversation state in your own application.

When Context Caching Is Worth Using

Prioritize a workload with repeated, necessary input and enough requests to evaluate the complete pattern. The following are practical candidates to test; their actual savings depend on observed usage.

WorkloadSuggested evaluation
Several questions about one reference documentKeep the document version fixed and measure the whole question set, including early misses.
A support assistant with stable instructionsCompare cost per resolved case while checking that relevant policy and customer details remain accurate.
A growing conversationMeasure the cost of each turn and the conversation total; track increasing context length.
Different documents on every requestFirst investigate whether better retrieval or shorter relevant input gives a larger benefit.
Short prompts with long generated answersCalculate the output share of spending before investing heavily in prefix optimization.

Set a baseline using representative tasks. Record the model, prompt version, protocol, token counts, applicable prices, and whether the answer met your requirements. Keep workload coverage and cost per successful task as separate measures.

Then compare an intentional layout change against that baseline. Include the cost of initial misses and any billed retries. If a cheaper response causes more follow-up work, count that work too. This prevents an apparently successful optimization from shifting cost elsewhere in the application.

Frequently Asked Questions

Do I Need cache_control or a Custom Cache Key?

No manual caching flag is required. DeepSeek’s Messages compatibility guide says cache_control is ignored. Its Responses guide says prompt_cache_key and prompt_cache_retention are unsupported and ignored. A successful request does not prove those options changed caching behavior.

Can I Omit Context After It Has Been Cached?

No. DeepSeek’s Chat Completions conversation guide requires the application to send the relevant history on each call. Responses is also stateless and does not support previous_response_id or conversation. Cached processing does not supply missing messages or enlarge the model’s context window.

Is There a 64-Token Minimum?

The August 2024 announcement described 64-token storage units. The current guide does not specify a universal interval size. Do not turn the historical figure into a current guarantee or pad prompts just to reach it.

Will a Cache Hit Return the Same Answer?

No. Cached prefixes still lead to newly generated output, so answers may differ. This is documented in DeepSeek’s output behavior notes. If your application needs to reuse an exact finished answer, evaluate a separate response cache with explicit rules for freshness and user access.

Does This Guide Apply to DeepSeek Running Locally?

This guide covers DeepSeek’s hosted API. For a local model server, verify that server’s prefix-caching behavior, memory management, and instrumentation directly. Do not transfer hosted API prices, retention expectations, or usage field names to a different inference engine.

Start with one recurring task, preserve its useful context, and collect complete usage records. Keep the change when it reduces the cost of successful work while maintaining the answers your users need.