AiCredits
Prompt Caching

Prompt Caching Explained: Which Providers Support It and How Much It Saves

Prompt caching explained: how prefix reuse works, which providers support it (OpenAI, Anthropic, Gemini, DeepSeek), and where the real savings come from.

Published 2026-10-21 Updated 2026-10-21 8 min

Prompt caching is prefix reuse, not model memory

Every chat completion re-sends the entire prompt. If your system message carries a style guide, a JSON schema, a tool definition file or a retrieved document, the model re-reads those same tokens on every single call — even though nothing about them changed since the last request.

Prompt caching stores the model's internal state for a prefix of tokens. When a later request arrives with the identical prefix, the provider restores that state instead of running the prefill pass again, and bills the matched tokens at a cached-input rate that sits well below the fresh-input rate. Current rates live on the pricing page; what matters here is the mechanism.

The word to internalise is prefix. Models read left to right, so caching works on the longest matching run from the very start of the prompt. Change one character near the front and every token after it becomes a miss.

The layout rule: stable content first, volatile content last

Because matching is prefix-based, prompt layout decides your hit rate. Put everything that never changes at the front — system instructions, few-shot examples, reference documents, tool schemas — and everything per-call at the end: the user's question, the file under review, the retrieved chunk.

Here is the pattern with DeepSeek models on AiCredits, which cache context automatically so you get hits without touching your request shape:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

# The stable prefix. In production swap this for your real reference document
# (schema, style guide, tool specs). The bigger and more reused it is, the more
# there is to cache. It must be byte-identical on every call.
STYLE_GUIDE = """
1. Prefer explicit over implicit.
2. No bare except clauses.
3. Functions over 40 lines must be split.
4. Every public function needs a docstring with Args and Returns.
"""

SYSTEM = (
    "You are a senior Python reviewer. Apply the house style guide below.\n"
    "<style_guide>\n" + STYLE_GUIDE + "\n</style_guide>\n"
)

def review(code: str) -> str:
    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[
            {"role": "system", "content": SYSTEM},          # stable, cached
            {"role": "user", "content": "Review this code:\n\n" + code},  # volatile
        ],
        temperature=0.2,
    )
    u = resp.usage
    print(
        "prompt_tokens:", u.prompt_tokens,
        "cache_hit:", getattr(u, "prompt_cache_hit_tokens", 0),
        "cache_miss:", getattr(u, "prompt_cache_miss_tokens", 0),
    )
    return resp.choices[0].message.content

if __name__ == "__main__":
    print(review("def add(a, b):\n    return a + b\n"))
  • Order by stability. Within the system prompt, put the most permanent material first and the semi-stable material last.

  • Never interpolate live values into the prefix. A timestamp, request ID, user name or experiment flag in the system prompt guarantees a miss on every call.

  • Serialise deterministically. json.dumps(obj, sort_keys=True) keeps your schema bytes identical between runs; unsorted dicts silently reshuffle the prefix.

  • Keep the model fixed. Switching from deepseek-v4-flash to deepseek-v4-pro mid-pipeline is a different cache — that is fine if it is intentional, expensive if it is accidental.

  • Stream freely. Streaming does not affect prefix matching, so you do not have to choose between caching and fast first tokens.

Which providers support prompt caching

ProviderHow you enable itWhat gets cachedSavings shape
OpenAINothing — automatic and best-effortLongest matching prefix of the requestDiscounted input tokens on hits, no write fee, no control over eviction
AnthropicExplicit `cache_control` breakpoints you place yourselfOnly the blocks you mark, with lifetime optionsPremium to write the cache, much cheaper to read it back
Google GeminiImplicit mode, or explicit cached-content objects you create and deletePrefixes (implicit) or a managed cache object (explicit)Cheaper input on hits; explicit caches add a storage dimension to manage
DeepSeek via AiCreditsNothing — automatic context caching on diskRepeated prefixes across requestsCache hits billed below fresh input, and off-peak requests cheaper still
Self-hosted (vLLM, SGLang)Server flagPrefix blocks in GPU memoryFewer prefill FLOPs; you pay in VRAM, not tokens

The providers differ less in whether caching exists than in who controls it. OpenAI's automatic path is the least work and the least controllable: you cannot pin a prefix or choose a lifetime, so a prefix that has gone cold is simply recomputed at full price.

Anthropic's explicit breakpoints give you precision and a choice of lifetime, at the cost of a write premium — a block reused exactly once can end up costing more than no caching at all. Gemini offers both modes, and the explicit variant behaves like a resource you own: create it, reference it, and remember to clean it up.

DeepSeek models served through AiCredits sit in the automatic camp: context is cached on disk, there are no breakpoints or cache objects to manage, and you can pay by card or PayPal without a Chinese phone number or bank account. You still have to get the prompt layout right — automation removes the bookkeeping, not the prefix rule.

How much does prompt caching actually save?

There is no single number, and any article quoting one is describing a single provider's rate card on the day it was written. What you can reason about precisely is the shape of the saving.

Only input tokens are cached. Output is generated fresh every time, so caching does nothing for long completions. If your workload is 500 input tokens in and 2,000 out, caching is noise. If it is a 10k-token reference document in and a short answer out, caching is most of your bill.

Savings scale with prefix length × reuse count. A large prefix reused hundreds of times is where caching pays for itself. A short system prompt is not worth optimising; the pool of saved tokens simply is not big enough.

Watch the write side. Providers with explicit caching charge a premium to populate a cache. Batch jobs, one-off analyses and interactive sessions where every prompt differs will not amortise that write, and can cost more than doing nothing.

Caching is not a substitute for a smaller prompt. A trimmed prompt still beats a cached bloated one: you pay something for cached tokens, and long irrelevant context degrades answer quality whether or not it was cheap to send.

Rule of thumb: if a call's prompt is mostly the same text as the previous call's, caching should be doing the work — and you should be able to prove it from the usage object rather than assume it.

Measure the hit rate instead of trusting it

Caching fails silently. Nothing errors when your prefix drifts; the bill just quietly looks like it did before. DeepSeek models return prompt_cache_hit_tokens and prompt_cache_miss_tokens next to the usual counts, so log them alongside a fingerprint of your prefix:

import hashlib
from typing import Iterable

# Reuses `client` and `SYSTEM` from the previous snippet.

def prefix_id(text: str) -> str:
    """Short stable fingerprint of the cached prefix."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]

def run_batch(snippets: Iterable[str]) -> dict:
    hit = miss = 0
    for snippet in snippets:
        resp = client.chat.completions.create(
            model="deepseek-v4-flash",
            messages=[
                {"role": "system", "content": SYSTEM},
                {"role": "user", "content": snippet},
            ],
            temperature=0.2,
        )
        u = resp.usage
        hit += getattr(u, "prompt_cache_hit_tokens", 0) or 0
        miss += getattr(u, "prompt_cache_miss_tokens", 0) or 0
        print(prefix_id(SYSTEM), "hit:", hit, "miss:", miss)
    return {"hit": hit, "miss": miss, "prefix": prefix_id(SYSTEM)}

if __name__ == "__main__":
    run_batch(["def f(x):\n    return x + 1\n", "try:\n    go()\nexcept:\n    pass\n"])

The first call in a batch is a miss — the cache is cold. The signal you are looking for is the fingerprint holding steady while hit climbs. If the fingerprint changes between calls, something dynamic has leaked into your system prompt and the cache can never warm up.

Mistakes that quietly break the cache

  • Volatile system prompts — dates, user names, A/B flags, environment strings. Move them into the user message.

  • Non-deterministic retrieval order — concatenating five documents in whatever order the vector store returned them produces a different prefix each time. Sort by document ID before concatenating.

  • Question before context — putting the user's question at the top and the reference document underneath defeats the whole scheme.

  • Prefix too short — every provider has a minimum cacheable prefix length; below it, nothing is cached at all. Measure before assuming.

  • Assuming permanence — caches are evicted. Real traffic patterns, not guarantees, decide whether your prefix survives.

  • Too many breakpoints — on explicit-caching providers, marking every block multiplies write fees for blocks that are never reused.

FAQ

Does prompt caching change the model's output?

No. The same tokens are still consumed by the model; only the prefill computation and the billing line change. If your output shifts after you restructure a prompt for caching, it is because the prompt text itself moved, not because of the cache.

Do I need to enable caching for DeepSeek models on AiCredits?

No. Context caching is automatic when you call the API at https://api.aicreditsapi.com/v1 — there are no breakpoints or cache objects to create. Your job is limited to keeping the prefix byte-identical and logging hits versus misses.

Is caching worth it for a single long request?

Usually not on providers that charge a cache-write premium, since you pay extra to store something you never read back. On automatic providers with no write fee it is harmless but irrelevant. Caching is a repetition strategy.

Is cached context shared between users?

Caches are scoped to your account on hosted providers, so one customer's prompt does not warm another's. That said, avoid putting credentials or private data in a cached prefix as a matter of habit, and check each provider's data policy if you handle regulated content.

The practical takeaway is unglamorous: caching rewards prompt discipline. Restructure one pipeline so the stable prefix sits first, log prompt_cache_hit_tokens for a week, and compare the input side of your bill against what you saw before. If the hit count stays at zero, your prefix is drifting — find the dynamic value and move it to the end. Once it works, the same trick applies to every batch job you write from then on.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×