AiCredits
API Caching

How to Cache DeepSeek API Responses and Cut Latency

Caching DeepSeek API responses in Python with real code: exact-match and near-match keys, single-flight dedupe, streaming replay, and honest latency tradeoffs.

Published 2026-09-29 Updated 2026-09-29 7 min

Most DeepSeek API latency isn't the model thinking. It's the same prompt being sent again and again by different users, different workers, or the same retry loop. Production traffic is heavy-tailed but extremely repetitive at the head: one shared system prompt, one classification rubric, one RAG context block, and a handful of phrasings of the same question.

Every one of those repeats pays the full round trip twice — once in wall-clock time and once in tokens. Caching attacks both at the same time. Below are four cache layers you can build today, using the OpenAI SDK against AiCredits' OpenAI-compatible endpoint with deepseek-v4-flash as the default model.

The four caches that actually matter

LayerWhere it livesWhat it savesMain risk
Exact-matchYour process or RedisThe whole round trip on repeated promptsStale answers if the TTL is too long
Single-flightYour process, one lock per keyDuplicate concurrent calls on identical promptsLock contention if keys are too coarse
Near-matchYour process plus a similarity checkRound trips on paraphrasesA false hit returns the wrong answer
Prefix cacheThe provider side, driven by prompt orderRecomputation of a stable prompt prefixOne timestamp at the top invalidates everything after it

Notice that the provider-side prefix cache is the only one you don't build. You influence it purely through prompt structure, and cache hits are billed more cheaply than fresh input, so ordering is worth real attention. We'll come back to it.

Step 1: An exact-match cache you can ship today

The cache key must contain everything that can change the output: model, messages, temperature, and any options you pass such as response_format or tools. If two requests can produce different answers, they need different keys.

Normalize before hashing — collapse whitespace, serialize with sorted keys, and version the key so old entries can't leak into new prompt behavior.

import hashlib
import json
import threading
import time

from openai import OpenAI

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

CACHE = {}          # key -> (expiry_epoch, text)
LOCK = threading.Lock()
TTL_SECONDS = 900


def cache_key(messages, model, temperature, options=None):
    payload = {
        "v": 1,
        "model": model,
        "temperature": temperature,
        "messages": [
            {"role": m["role"], "content": " ".join(m["content"].split())}
            for m in messages
        ],
    }
    if options:
        payload["options"] = options
    blob = json.dumps(payload, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def chat_cached(messages, model="deepseek-v4-flash", temperature=0.0, options=None):
    key = cache_key(messages, model, temperature, options)
    now = time.time()

    with LOCK:
        hit = CACHE.get(key)
        if hit and hit[0] > now:
            return hit[1], True

    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        **(options or {}),
    )
    text = response.choices[0].message.content

    with LOCK:
        CACHE[key] = (time.time() + TTL_SECONDS, text)
    return text, False


text, was_cached = chat_cached([{"role": "user", "content": "Name three uses for a write-ahead log."}])
print(was_cached)

Step 2: Design keys that hit more often

  • Strip trailing whitespace and collapse blank lines in every message before hashing.

  • Keep timestamps, request IDs, and "today's date" out of the prompt body, or place them after the cached prefix.

  • Lowercase only where case provably doesn't matter — never for code, JSON payloads, or identifiers.

  • Serialize with sort_keys=True so dict iteration order never changes the hash.

  • Version the key (the "v" field above) and bump it whenever you edit a prompt template.

  • Pin temperature=0 for prompts whose cached answers you intend to reuse; a cached sample from temperature=1 is still just one sample.

Step 3: Single-flight, so ten identical requests cost one call

A cache only helps after the first response is stored. On a cold key, ten workers hitting the same prompt at once produce ten identical calls — the classic cache stampede. One lock per key fixes it: the first caller does the work, the rest wait and then read the cache instead of calling again.

from collections import defaultdict

_inflight = defaultdict(threading.Lock)


def chat_single_flight(messages, model="deepseek-v4-flash", temperature=0.0, options=None):
    key = cache_key(messages, model, temperature, options)

    with _inflight[key]:
        # Re-check inside the lock: another thread may have filled it while we waited.
        with LOCK:
            hit = CACHE.get(key)
            if hit and hit[0] > time.time():
                return hit[1], True

        response = client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
            **(options or {}),
        )
        text = response.choices[0].message.content

        with LOCK:
            CACHE[key] = (time.time() + TTL_SECONDS, text)
        return text, False

Step 4: Cache streamed answers without breaking the stream

Streaming improves perceived latency but makes caching awkward: you can't read the final text until the last chunk arrives. Accumulate as you forward, then store the joined result and replay it in slices on the next hit. Callers keep the same interface either way.

def stream_cached(messages, model="deepseek-v4-flash", temperature=0.0,
                  options=None, chunk_size=32):
    key = cache_key(messages, model, temperature, options)

    with LOCK:
        hit = CACHE.get(key)

    if hit and hit[0] > time.time():
        text = hit[1]
        for i in range(0, len(text), chunk_size):
            yield text[i:i + chunk_size]
        return

    parts = []
    stream = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=temperature,
        stream=True,
        **(options or {}),
    )
    for event in stream:
        delta = event.choices[0].delta.content or ""
        if delta:
            parts.append(delta)
            yield delta

    with LOCK:
        CACHE[key] = (time.time() + TTL_SECONDS, "".join(parts))


# for chunk in stream_cached([{"role": "user", "content": "Explain WAL in one paragraph."}]):
#     print(chunk, end="", flush=True)

Step 5: Near-match caching without hallucinating hits

Exact hashing misses paraphrases, and paraphrases are most of real traffic. Lexical similarity is the cheapest upgrade: tokenize the prompt, compare token sets, and reuse a cached answer only above a high threshold. It's deterministic and dependency-free, but it is not semantic — "reset my password" and "I forgot my credentials" share almost no tokens.

Keep the threshold high and restrict near-match reuse to idempotent, low-stakes prompts: classification, extraction, and FAQ answers. For anything riskier, spend a cheap call on a verifier: ask deepseek-v4-flash whether the new prompt is equivalent to the cached one before reusing it. When the judgment itself is the hard part, deepseek-v4-pro is the stronger verifier, though it costs more than flash.

import re
from collections import deque

NEAR_CACHE = deque(maxlen=500)   # (expiry_epoch, tokens, text)
NEAR_THRESHOLD = 0.9             # a false hit is worse than a miss


def tokens_of(text):
    return re.findall(r"[a-z0-9]+", text.lower())


def jaccard(a, b):
    sa, sb = set(a), set(b)
    union = sa | sb
    return len(sa & sb) / len(union) if union else 0.0


def chat_near_match(messages, model="deepseek-v4-flash", temperature=0.0, options=None):
    prompt = "\n".join(m["content"] for m in messages)
    tokens = tokens_of(prompt)
    now = time.time()

    for expiry, cached_tokens, text in NEAR_CACHE:
        if expiry > now and jaccard(tokens, cached_tokens) >= NEAR_THRESHOLD:
            return text, True

    text, _ = chat_cached(messages, model=model, temperature=temperature, options=options)
    NEAR_CACHE.append((now + TTL_SECONDS, tokens, text))
    return text, False

Prompt order is a cache you don't have to build

  • Put stable content first: system prompt, instructions, tool definitions, then long reference documents. Put the variable user turn last.

  • Never prepend a timestamp, session ID, or greeting to the system prompt — it invalidates everything that follows it.

  • Keep message order and wording byte-identical across requests that should share a prefix.

  • Cache hits are billed differently from fresh input and output, so check aicreditsapi.com/pricing for how prefix reuse and off-peak timing affect your spend.

When caching is the wrong answer

  • Per-user or personalised data, unless keys are namespaced by tenant and near-match is disabled across users.

  • Anything where "now" matters: prices, inventory, live status, account balances.

  • Prompts that are nearly unique every time, such as summarising a newly uploaded document — you pay lookup cost and get misses.

  • High-temperature creative work, where a repeated answer is a bug rather than a saving.

  • Long TTLs on facts that change frequently. Choose TTL from how often the source changes, not from how large the cache is.

Measure hit rate, not vibes

Log two booleans and a duration per call: cache hit or miss, and elapsed time. Split your latency reporting by that flag so a slow model and a broken cache never look the same. Track fresh input and output tokens separately from reused prefix tokens, and watch what happens to your hit rate the day you edit a prompt template — a small wording change can silently reset an entire cache tier.

For multi-worker deployments, move the dictionary into Redis with a TTL and keep the near-match index per instance. An in-process cache warms only one container; in a rolling deploy that means every new pod starts cold.

FAQ: caching DeepSeek responses in practice

Does caching reduce cost as well as latency?

Yes. A cache hit skips the generation entirely, and provider-side prefix hits are billed more cheaply than fresh input, so both fresh-input and output tokens drop on repeat traffic. Current rates are on aicreditsapi.com/pricing.

Can I cache deepseek-v4-pro the same way?

The key scheme is identical. Because pro costs more than flash, each hit saves more — but pro is usually chosen for prompts where near-match reuse is riskier, so keep exact-match keys and a short TTL.

Where should the cache live in production?

A single process dictionary is fine for one worker. For several containers, use Redis with a TTL so all workers share entries; otherwise every replica pays for its own cold start.

How do I avoid serving stale or wrong answers?

Namespace keys by user or tenant, set TTLs from how volatile the underlying content is, keep near-match thresholds high, and only enable near-match for idempotent prompts.

Ship the cache, then check the bill

Start with exact-match plus single-flight — that pair is a few dozen lines and removes the most wasteful calls immediately. Add streaming replay when you stream, and near-match only after you can measure false hits. Then look at prompt ordering, which is free latency you're leaving on the table.

AiCredits serves deepseek-v4-flash and deepseek-v4-pro through an OpenAI-compatible endpoint at api.aicreditsapi.com/v1, payable by card or PayPal with no Chinese phone number or bank account required — so you can point the code above at it by changing the base_url. Keep flash as the default and reserve pro for the prompts that genuinely need it, then check aicreditsapi.com/pricing for how prefix hits and off-peak timing land on your invoice.

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 ×