---
title: "Prompt Caching for LLM APIs: Math, Keys, and Code | Inference.net"
description: "Cut multi-turn LLM API spend by 44%+ with prompt caching. Compare 40-turn cache math on DeepSeek V4.1, Kimi K3.1 Pro, and GLM-5.3 with SDK code."
url: "https://inference.net/guides/prompt-caching-llm-api-guide/"
---

Guide Published December 06, 2026 8 min read

# Prompt Caching for LLM APIs: Math, Keys, and Code

Cut multi-turn LLM API spend by 44%+ with prompt caching. Compare 40-turn cache math on DeepSeek V4.1, Kimi K3.1 Pro, and GLM-5.3 with SDK code.

[**Inference.net**](https://inference.net/company/)

## Model Your Cache Savings

Plug your prefix size, turn count, and hit rate into the Prompt Cache Savings Calculator or start calling cached 1M-context models.

## Direct answer: how prompt caching cuts LLM API bills

Prompt caching reuses the computed KV cache for byte-identical leading tokens (system prompts, tool schemas, repository context, and earlier conversation turns) so multi-turn agents pay a deeply discounted cached-read rate instead of full input pricing on every turn. On Inference.net, cached input reads drop up to **91.3%** on [`deepseek-v4.1-flash-1017`](https://inference.net/models/deepseek-v4-1-flash-1017/) (`$0.007` vs `$0.08/1M`), **89.0%** on [`moonshotai/kimi-k3.1-pro`](https://inference.net/models/kimi-k3-1-pro/) (`$0.198` vs `$1.80/1M`), and **70.0%** on [`glm-5.3-flash`](https://inference.net/models/glm-5-3-flash/) (`$0.03` vs `$0.10/1M`). In a realistic 40-turn coding-agent session with a 12K shared prefix at an 85% hit rate plus 2K fresh user tokens per turn, caching trims total session spend by **44.0% to 49.4%** on DeepSeek V4.1 Flash and Kimi K3.1 Pro, bringing DeepSeek V4.1 Flash 1017 down to **`$0.0379` per session**.

Estimate your exact workload in the [Prompt Cache Savings Calculator](https://inference.net/tools/prompt-cache-calculator/).

## 40-turn coding-agent prompt-cache math

Coding agents (Claude Code, Cursor, Cline, Roo Code, OpenCode, and custom tool loops) resend the same system instructions, tool declarations, and opened files across dozens of turns. Using the same token-split formula as our [Prompt Cache Savings Calculator](https://inference.net/tools/prompt-cache-calculator/):

- **Turns per session:** 40 turns
- **Shared cacheable prefix:** 12,000 tokens/turn (`480,000` prefix tokens/session) at an **85% hit rate** = `408,000` cached reads + `72,000` missed prefix writes
- **Fresh per-turn user input:** 2,000 tokens/turn (`80,000` fresh tokens/session, billed at the standard input rate on every model)
- **Output volume:** 900 tokens/turn (`36,000` total output tokens/session)
- **Monthly scale:** 750,000 requests/month (`18,750` sessions)

Automatic-cache models (`deepseek-v4.1-flash-*`, `glm-5.3*`, `moonshotai/kimi-k3*`) bill missed prefix tokens at the standard fresh input rate. Explicit Anthropic `cache_control` routes bill missed prefix writes at the cache-write rate (`$3.75/1M` for 5-minute TTL and `$6.00/1M` for 1-hour TTL on `claude-sonnet-4-6`; the table below uses the 5-minute write tier). The **Session without cache** column represents standard requests with caching disabled (all 560K input tokens billed at the standard input rate with no cache-write fee, matching the uncached baseline in `/tools/prompt-cache-calculator/`).

Every rate below was verified against `GET https://api.inference.net/v1/models` on **2026-12-06**:

| Model ID | Family hub | Fresh input ($/1M) | Cache write 5m ($/1M) | Cached read ($/1M) | Output ($/1M) | 40-turn cached session | Session without cache | Savings | Monthly (750K reqs) |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `deepseek-v4.1-flash-1017` | [DeepSeek](https://inference.net/models/deepseek/) | `$0.08` | `$0.08` | `$0.007` | `$0.635` | **`$0.0379`** | `$0.0677` | 44.0% | `$710.17` |
| `deepseek-v4.1-flash` | [DeepSeek](https://inference.net/models/deepseek/) | `$0.103` | `$0.103` | `$0.007` | `$0.60` | **`$0.0401`** | `$0.0793` | 49.4% | `$752.10` |
| `glm-5.3-flash` | [GLM](https://inference.net/models/glm/) | `$0.10` | `$0.10` | `$0.03` | `$0.35` | **`$0.0400`** | `$0.0686` | 41.6% | `$750.75` |
| `glm-5.3` | [GLM](https://inference.net/models/glm/) | `$0.084` | `$0.084` | `$0.079` | `$3.00` | **`$0.1530`** | `$0.1550` | 1.3% | `$2,868.75` |
| `moonshotai/kimi-k3.1-pro` | [Kimi](https://inference.net/models/kimi/) | `$1.80` | `$1.80` | `$0.198` | `$9.00` | **`$0.6784`** | `$1.3320` | 49.1% | `$12,719.70` |
| `moonshotai/kimi-k3` | [Kimi](https://inference.net/models/kimi/) | `$0.245` | `$0.245` | `$0.224` | `$15.00` | **`$0.6686`** | `$0.6772` | 1.3% | `$12,536.85` |
| `claude-sonnet-4-6` | [Catalog](https://inference.net/models/) | `$3.00` | `$3.75` | `$0.30` | `$15.00` | **`$1.1724`** | `$2.2200` | 47.2% | `$21,982.50` |

### Key takeaways from the math

1. **Cached-read rate decides high-turn agent cost:** On `deepseek-v4.1-flash-1017`, `408K` cached input tokens cost just `$0.0029`, so output tokens (`$0.0229`) become the largest share of the `$0.0379` session bill.
2. **Cache write charges widen the gap on explicit-cache models:** Including Anthropic's `$3.75/1M` 5-minute cache-write fee adds `$0.2700` per session on `claude-sonnet-4-6` (`$1.1724` total, `31.0x` higher than `deepseek-v4.1-flash-1017`). Using 1-hour cache writes (`$6.00/1M`) raises that write component further.
3. **Kimi K3.1 Pro nearly halves its bill once caching kicks in:** Even though `moonshotai/kimi-k3.1-pro` lists `$1.80/1M` fresh input, `$0.198/1M` cached reads cut session cost by **49.1%** (`$0.6784` vs `$1.3320`), matching `moonshotai/kimi-k3` (`$0.6686`) at 85% hits and undercutting it whenever cache hit rates exceed 87% or output volume rises (`$9.00` vs `$15.00/1M` output).
4. **Output pricing governs `glm-5.3`:** Because `glm-5.3` already prices fresh input near its cached rate (`$0.084` vs `$0.079/1M`), `$0.1080` of its `$0.1530` session cost comes from output generation. Passing `prompt_cache_key` still improves prefill reuse and time to first token.

## Per-family prompt caching rules (`prompt_cache_key` vs implicit vs `cache_control`)

Prompt caching is not configured identically across every model family on Inference.net. Sending the wrong field can either miss the cache or return a `400` validation error. Match your request payload to the exact contract for your target model:

| Model family / IDs | Caching mode | Extra request parameter | What to keep stable |
| --- | --- | --- | --- |
| `glm-5.3`, `glm-5.3-flash`, `glm-5.2`, `glm-5.2-fast`, `gpt-5.4`, `gpt-4.1`, `gpt-5-mini` | `prompt_cache_key` routing affinity | Pass stable `prompt_cache_key` string | Byte-identical leading messages + stable `prompt_cache_key` |
| `deepseek-v4.1-flash-1017`, `deepseek-v4.1-flash`, `deepseek-v4-pro`, `deepseek-v4-pro-0813` | Implicit prefix caching (no key) | **Do not send `prompt_cache_key`** | Byte-identical leading messages only |
| `moonshotai/kimi-k3.1-pro`, `moonshotai/kimi-k3`, `moonshotai/kimi-k3-fast`, `qwen3.7-plus` | Implicit prefix caching | None required | Byte-identical leading messages only |
| `claude-sonnet-4-6`, `claude-opus-4-6`, `claude-haiku-4-5` | Explicit `cache_control` breakpoints | `cache_control: { "type": "ephemeral" }` on stable blocks | Byte-identical marked system/tool blocks |
| `glm-5` | Session + cache key | Pass both `session_id` and `prompt_cache_key` | Byte-identical prefix + both stable IDs |
| `grok-4.5`, `grok-4.6` | Conversation header | Pass `x-grok-conv-id` header | Byte-identical prefix + stable conversation header |

**Important: omit prompt_cache_key on DeepSeek V4.1 Flash**

`prompt_cache_key` is a routing-affinity hint for GLM-5.3, GLM-5.3 Flash, and OpenAI routes. It does not name or store cached content on its own, and `deepseek-v4.1-flash-1017`, `deepseek-v4.1-flash`, and DeepSeek V4 Pro routes do not accept it and may reject requests that include it. If you route across multiple families through LiteLLM Proxy, add `additional_drop_params: ["prompt_cache_key"]` on DeepSeek deployments.

## OpenAI SDK example: `prompt_cache_key` on GLM-5.3 and implicit caching on DeepSeek / Kimi

Keep static instructions, tool schemas, and reference files at the start of `messages`, append dynamic user input at the end, and inspect `usage.prompt_tokens_details.cached_tokens` on every turn to verify hits.

### Python (OpenAI SDK)

python

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://us.api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
)

SYSTEM_PREFIX = (
    "You are a senior backend engineer reviewing TypeScript services. "
    "Return concise diffs and cite exact file paths.\n\n"
    + ("# Repository conventions and API schemas...\n" * 120)
)

def ask_cached(model: str, question: str, cache_key: str = "repo-backend-v1") -> str:
    extra_body: dict[str, object] = {}
    # Send prompt_cache_key for GLM-5.3 / GLM-5.3 Flash; omit on DeepSeek V4.1 and Kimi K3.
    if model.startswith("glm-5.3") or model.startswith("glm-5.2"):
        extra_body["prompt_cache_key"] = cache_key

    response = client.chat.completions.create(
        model=model,
        extra_body=extra_body or None,
        messages=[
            {"role": "system", "content": SYSTEM_PREFIX},
            {"role": "user", "content": question},
        ],
    )

    usage = response.usage
    cached = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0
    print(f"[{model}] prompt={usage.prompt_tokens} cached={cached} out={usage.completion_tokens}")
    return response.choices[0].message.content or ""

# Turn 1 warms the prefix cache; Turn 2 reads cached tokens.
ask_cached("deepseek-v4.1-flash-1017", "Audit auth middleware for race conditions.")
ask_cached("deepseek-v4.1-flash-1017", "Now write unit tests for token expiry.")
ask_cached("glm-5.3", "Summarize the schema migration impact.")
```

### TypeScript (OpenAI SDK)

typescript

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://us.api.inference.net/v1",
  apiKey: process.env.INFERENCE_API_KEY,
});

const systemPrefix =
  "You are a TypeScript code reviewer. Keep answers terse.\n" +
  "Follow strict repository conventions.\n".repeat(200);

async function runTurn(model: string, userPrompt: string) {
  const isGlm = model.startsWith("glm-5.3") || model.startsWith("glm-5.2");
  const requestBody: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming =
    {
      model,
      messages: [
        { role: "system", content: systemPrefix },
        { role: "user", content: userPrompt },
      ],
      ...(isGlm ? { prompt_cache_key: "repo-backend-v1" } : {}),
    };

  const response = await client.chat.completions.create(requestBody);

  const cached = response.usage?.prompt_tokens_details?.cached_tokens ?? 0;
  console.log({
    model,
    promptTokens: response.usage?.prompt_tokens,
    cachedTokens: cached,
    completionTokens: response.usage?.completion_tokens,
  });
}

await runTurn("moonshotai/kimi-k3.1-pro", "List risky queries in this module.");
await runTurn("moonshotai/kimi-k3.1-pro", "Propose indexed rewrites for each.");
```

## Anthropic SDK example: prompt caching over `/v1/messages`

Inference.net natively serves the Anthropic Messages API at `POST https://api.inference.net/v1/messages` (and `https://us.api.inference.net/v1/messages` for US-hosted open-weight models). Pass `cache_control: { "type": "ephemeral" }` on stable system blocks for Claude routes, or call hosted open-weight models like `deepseek-v4.1-flash-1017` and `moonshotai/kimi-k3.1-pro` directly through the same SDK:

python

```python
import os
from anthropic import Anthropic

client = Anthropic(
    base_url="https://api.inference.net",
    auth_token=os.environ["INFERENCE_API_KEY"],
)

stable_context = "Repository architecture notes...\n" * 300

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": stable_context,
            "cache_control": {"type": "ephemeral"},
        }
    ],
    messages=[{"role": "user", "content": "Identify N+1 database queries."}],
)

print(message.usage)
```

For Inference.net-hosted models (`deepseek-v4.1-flash-1017`, `moonshotai/kimi-k3.1-pro`, `glm-5.2`), you can point `base_url` to `https://us.api.inference.net` for US residency and default [Zero Data Retention](https://inference.net/zero-data-retention/). Externally routed models such as `claude-sonnet-4-6` and base `deepseek-v4.1-flash` run on `https://api.inference.net` and follow upstream provider retention terms.

## Five mistakes that silently destroy prompt cache hit rates

1. **Injecting timestamps or request UUIDs into the system prompt:** Putting `Current time: 2026-12-06T08:12:34Z` on line 2 invalidates every byte after it. Move volatile fields into the final user message.
2. **Re-sorting tool schemas or JSON keys between turns:** Prefix matching is byte-exact. Sort tool definitions and dictionary keys deterministically before serializing requests.
3. **Mutating earlier conversation messages:** Summarizing or editing turn 3 breaks cache reuse for turns 4 through 40. Append new messages at the end and compact only when context approaches your ceiling.
4. **Rotating `prompt_cache_key` on every turn for GLM or OpenAI models:** Scope `prompt_cache_key` to the conversation, repository, or tenant prefix rather than generating a new UUID per HTTP request.
5. **Forgetting to verify `cached_tokens` in production telemetry:** Always log `usage.prompt_tokens_details.cached_tokens` (and include `stream_options: { "include_usage": true }` on streamed calls) so cache regressions show up immediately.

## Frequently asked questions

### Does prompt caching store my prompts on disk or break Zero Data Retention?

No. On eligible Inference.net-hosted, non-ad models (such as `deepseek-v4.1-flash-1017`, `moonshotai/kimi-k3.1-pro`, and `glm-5.2`), [Zero Data Retention](https://inference.net/zero-data-retention/) applies by default under SOC 2 Type II controls, and prompt text is not retained long-term or used for training. Externally routed models (such as `claude-sonnet-4-6`, `gpt-5.4`, or base `deepseek-v4.1-flash`) and `-with-ads` routes follow their respective upstream or ad-partner terms.

### How do I confirm prompt caching is actually working?

Inspect `usage.prompt_tokens_details.cached_tokens` in the OpenAI-compatible JSON response (or the final usage chunk when streaming with `stream_options: {"include_usage": true}`). On turn 2 and later with an identical prefix, `cached_tokens` rises above zero and those tokens bill at the cached-read rate.

### Which 1M-context model has the lowest cached input rate on Inference.net?

Among 1M-context non-ad models with supported prompt caching on **2026-12-06**, the lowest cached-input rates are `deepseek-v4-pro` (`$0.003625/1M`) and `minimax-m3.1-flash` (`$0.005/1M`). For Inference.net-hosted US DeepSeek V4.1 Flash with default ZDR, [`deepseek-v4.1-flash-1017`](https://inference.net/models/deepseek-v4-1-flash-1017/) charges `$0.007` per 1M cached input tokens (a 91.3% discount off fresh input) with zero extra request parameters required (externally routed `deepseek-v4.1-flash` also bills `$0.007/1M` cached input).

### Should I use prompt caching or the Batch API for bulk document jobs?

Use **prompt caching** for interactive multi-turn agents, chat, and repeated system-prefix queries that need low latency. Use the [Batch API](https://inference.net/docs/api/async/batch/) (`https://batch.inference.net/v1`) for offline jobs up to 1,000,000 requests per file that can finish within 24 hours at 25%+ below standard pricing (note that Batch and Files endpoints require disabling team ZDR and using a credit-billing API key).

## Related resources

- **Calculators:** [Prompt Cache Savings Calculator](https://inference.net/tools/prompt-cache-calculator/) · [LLM Pricing Calculator](https://inference.net/tools/llm-pricing-calculator/?preset=coding-agent)
- **Model family hubs:** [DeepSeek API](https://inference.net/models/deepseek/) · [Kimi API](https://inference.net/models/kimi/) · [GLM API](https://inference.net/models/glm/) · [Full Model Catalog](https://inference.net/models/)
- **Coding guides:** [DeepSeek V4.1 vs Kimi K3 vs GLM-5.3 for Coding Agents](https://inference.net/guides/deepseek-vs-kimi-vs-glm-coding-agents/) · [DeepSeek V4.1 Flash vs Claude Sonnet for Coding](https://inference.net/guides/deepseek-v4-1-flash-vs-claude-sonnet-coding/) · [OpenAI-Compatible LLM API Migration](https://inference.net/guides/openai-compatible-llm-api-migration/)
- **Integrations:** [Claude Code](https://inference.net/docs/integrations/claude-code/) · [LiteLLM Proxy](https://inference.net/docs/integrations/litellm/) · [OpenCode](https://inference.net/docs/integrations/opencode/) · [Anthropic SDK](https://inference.net/docs/api/anthropic-sdk/)

### Cut multi-turn token spend with automatic prompt caching

Run DeepSeek V4.1 Flash ($0.007/1M cached), GLM-5.3, and Kimi K3.1 Pro on one OpenAI and Anthropic-compatible API with US Zero Data Retention.

[Create API key](https://inference.net/register/?model=deepseek-v4.1-flash-1017)

Estimate Your Inference Bill

## Calculate your monthly LLM API & prompt-cache spend

Compare live input, cached-read, and output token pricing across every open-weight and frontier model on Inference.net with 0% markup.

[Open pricing calculator](https://inference.net/tools/llm-pricing-calculator/) [Explore model catalog](https://inference.net/models/)

## Related reading & models

[Back to all guides](https://inference.net/guides/)

[Guide December 05, 2026 **DeepSeek API Pricing: Live Rates, Caching Math, and Models** Live DeepSeek API pricing per 1M tokens for V4.1 Flash, V4 Pro, Cyber, and V3.2 on Inference.net, with prompt caching math and copy-paste code snippets. Read more](https://inference.net/guides/deepseek-api-pricing/) [Guide December 06, 2026 **Cheapest LLM API in 2026: Verified Per-1M Rates & Cache Math** Compare the cheapest LLM API models per 1M fresh, cached, and output tokens on Inference.net with 40-turn coding-agent and extraction cost math. Read more](https://inference.net/guides/cheapest-llm-api/) [Guide December 06, 2026 **OpenAI-Compatible LLM API Migration in 3 Lines of Code** Migrate OpenAI Python, Node, Anthropic SDK, LiteLLM, and curl to Inference.net in 3 lines. Compare live model pricing, 1M context, and US ZDR. Read more](https://inference.net/guides/openai-compatible-llm-api-migration/) [Article February 21, 2026 **LLM API Pricing Comparison 2026: Live Rates** Compare 2026 LLM API pricing across DeepSeek V4.1 Flash ($0.103/$0.60), Kimi K3.1 Pro, GLM-5.3, GPT, and Claude, plus $0.007/1M prompt cache savings. Read more](https://inference.net/content/llm-api-pricing-comparison/)

[**Explore serverless models** Compare open-weight and frontier models, context windows, and per-token pricing.](https://inference.net/models/) [**Inference Pass plans** Predictable monthly access for coding agents and high-volume OpenAI-compatible API workloads.](https://inference.net/subscription/)
