2027 planning guide · Evidence checked 20 November 2026

Prompt caching for developers: how prefix reuse works

Prompt caching reuses the model's computed key-value state for an identical prompt prefix, so repeated context is cheaper and faster to process. This guide explains the mechanics, the layout rules that produce hits, the limits that make caching a poor fit for some workloads, and what Plugsky's public API does and does not document today.

Short answer. Prompt caching reuses the model's computed key-value state for an identical prompt prefix, so repeated context is cheaper and faster to process. Plugsky's public API reference does not document a cache-control parameter or a cached-token billing field, and Builder and Scale do not bill per token, so treat caching as an upstream efficiency and latency topic rather than a line-item discount. The prompt-layout rules below still apply.

Availability note. This page explains prompt caching as an inference technique and how to design requests for it. It does not claim that Plugsky exposes a cache-control parameter, a cache-write charge or a cached-token discount. Check the current chat completions reference and confirm with support before you put a caching assumption into a production design or a contract.

What prompt caching actually stores

Prompt caching does not store your text and it does not store a previous answer. It stores the model's key-value (KV) state for a prefix: the intermediate tensors the model computed while reading those tokens. On a later request with the same prefix, the model can reuse that state instead of recomputing it from the first token.

That distinction explains the failure modes. A cache is not a semantic index, so a paraphrased system prompt is a miss. It is not a response cache, so a different question after the same context is still a new generation. And it is not shared across organisations or regions, so a hit is partly a routing outcome rather than a property of your text.

How a cache write and a cache read work

The first request performs a full prefill: the model reads the prefix and computes KV state for every token. If the provider caches that prefix, the state is written with a time to live. A later request with a matching prefix can read the state and skip the repeated prefill, then process only the new suffix.

Three things follow. First, caching helps input processing, not output generation, so a long answer still costs the same output tokens. Second, the benefit grows with prefix length and reuse count, because the write cost is paid once. Third, a cache hit is never guaranteed: eviction, routing and expiry can all turn a hit into a miss.

Cache writes, reads and misses: what each state costs and when it applies
StateWhat happensRelative input costTypical trigger
WriteThe provider stores KV state for a new prefixUsually higher than an ordinary input tokenFirst request with a long stable prefix
ReadThe provider reuses stored state and skips prefillUsually lower than an ordinary input tokenA later request with the same prefix inside the TTL
MissThe request is processed as if no cache existedOrdinary input costChanged prefix, expired entry, different model or region
No cacheNothing is written or readOrdinary input costPrefix below the minimum, or caching unsupported

Write pricing matters more than it first appears. If a prefix is written once and reused once, the write premium can cancel the read discount. Caching pays when the same prefix is reused several times inside its lifetime, which is why agent loops and fixed evaluation rubrics benefit more than one-shot requests.

What breaks a cache hit

A hit requires the entire rendered prefix to match. A change anywhere before the cache boundary invalidates everything after it. The table lists the usual causes and the fix that keeps the prefix stable.

Common causes of a cache miss, and how to restructure the request
ChangeWhy it missesFix
Timestamp or user name in the system promptThe first block differs on every requestMove dynamic values to the final user message
Reordered tool definitionsThe tool block is part of the rendered prefixKeep a stable order; disable tools with tool_choice instead of removing them
Model switchDifferent weights and cache behaviourPin one model per workload; route deliberately, not per request
Re-encoded or resized imageImage tokens differ even when the picture looks the sameNormalise dimensions and encoding before sending
Rewritten historySummarising or truncating changes earlier tokensAppend turns; compact at a deliberate boundary, not on every call
Different region or organisationCaches are not shared across those boundariesPin the region and keep related traffic on one key
Expired entryThe TTL elapsed before the next reusePrewarm, shorten the gap, or accept the full prefill
Prefix below the minimumThe provider does not cache short prefixesOnly lengthen it with useful stable content; do not pad

The layout rule: stable first, variable last

The practical rule is to order the request by change frequency. Put the system instruction, policy, tool definitions, few-shot examples and reference documents first and keep them byte-identical. Put the timestamp, user profile, retrieved snippet that changes per turn, and the question last.

# Before: the first block changes on every request, so nothing after it can match.
messages = [
    {"role": "system", "content": f"You are a support agent. Today is {now}."},
    {"role": "user", "content": policy_document},
    {"role": "user", "content": question},
]

# After: the stable prefix stays identical; the variable part moves to the end.
messages = [
    {"role": "system", "content": "You are a support agent. Answer only from the policy."},
    {"role": "user", "content": policy_document},
    {"role": "user", "content": f"Current time: {now}\nQuestion: {question}"},
]

The same rule applies to tool use. Tool names, descriptions, schemas and order are part of the prefix. If a workflow needs a different tool set, keep the full list stable and restrict what is callable, rather than rebuilding the list per request. That is also better for evaluation, because the model sees a consistent interface.

A cache-friendly request on the Plugsky API

The example below uses the OpenAI Python SDK against the Plugsky base URL. It does not send a cache parameter, because the public reference does not document one. It only arranges the prompt so that a provider-side cache has a stable prefix to match.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["PLUGSKY_API_KEY"],
    base_url="https://api.plugsky.com/v1",  # docs also show https://plugsky.com/v1
)

resp = client.chat.completions.create(
    model="plugsky-pro",
    messages=[
        {"role": "system", "content": SYSTEM_POLICY},      # stable
        {"role": "user", "content": PRODUCT_REFERENCE},    # stable
        {"role": "user", "content": f"Ticket: {ticket}\nDraft a reply."},
    ],
    temperature=0.2,
    max_tokens=600,
)

print(resp.usage.prompt_tokens, resp.usage.completion_tokens)

Keep the API host consistent inside one codebase. The approved brief uses https://api.plugsky.com/v1, while some public docs examples show https://plugsky.com/v1. Pick one per client and do not mix them without a note, because a host change can move traffic to a different cache and routing path.

How to measure a cache hit

Usage fields are the first place to look. Plugsky returns usage.prompt_tokens, usage.completion_tokens and usage.total_tokens in the response. It does not publish a cached-token field, so you cannot compute a hit rate from the response alone today.

Measure what you can observe: time to first token, total latency, prompt tokens per request, upstream retry counts and the ratio of prompt tokens to output tokens. If a provider later returns a cached-token count, log it with the prefix hash and the model so you can separate a real hit from a faster route.

import hashlib, time

prefix_hash = hashlib.sha256((SYSTEM_POLICY + PRODUCT_REFERENCE).encode()).hexdigest()[:12]
started = time.perf_counter()
resp = client.chat.completions.create(model="plugsky-pro", messages=messages)
elapsed_ms = (time.perf_counter() - started) * 1000

log.info("completion", extra={
    "prefix": prefix_hash,
    "prompt_tokens": resp.usage.prompt_tokens,
    "completion_tokens": resp.usage.completion_tokens,
    "latency_ms": round(elapsed_ms, 1),
})

Do not infer a cache hit from a flat invoice. On Builder and Scale the monthly price does not move with input tokens, so a lower bill is not evidence of anything. On Hobby and Starter, daily token caps apply, but whether cached tokens count toward those caps is not published.

Limits and trade-offs

  • Minimum length. Providers publish different minimum cacheable prefix lengths. Below the minimum, nothing is written, so a short prompt cannot benefit no matter how often it repeats.
  • Short lifetime. Cache entries typically last minutes, sometimes up to a day, but they are not durable storage. A workload that runs once a day may never hit.
  • Write premium. A cache write can cost more than an ordinary input token. Low reuse makes caching more expensive, not less.
  • Output unchanged. Caching reduces prefill work. It does not shorten the answer, reduce output tokens or make generation deterministic.
  • Retention. Cached KV state is data. Check the provider's retention terms, the DPA and the region before caching regulated content.
  • No portability. A cache belongs to a model, a machine and usually a region. It does not move with your prompt when you switch providers.

When prompt caching pays

Caching is a good fit when a long prefix repeats many times inside a short window. Common examples are a fixed system policy with a changing question, a RAG workflow over a stable document set, an agent loop that appends tool results, a coding assistant that resends repository context, and an evaluation harness that applies one rubric to hundreds of cases.

It is a poor fit for one-shot requests, prompts assembled from per-request data, prefixes shorter than the provider minimum, and workloads with strict no-retention requirements. It is also a poor fit when the question changes the whole prompt, because there is no shared prefix left to reuse.

Idempotency is not prompt caching

Plugsky supports an Idempotency-Key header on POST requests. Re-sending the same key returns the stored result for 24 hours, which makes retries safe and prevents duplicate writes. That is a response replay, not a prefix cache: it does not help a different question, and it does not reduce prefill for new work.

Use both for different reasons. Idempotency protects a write from a network retry. Prompt layout protects a repeated prefix from being recomputed. Neither one substitutes for the other.

What we did not verify

  • We did not verify that the upstream engine caches any prefix automatically, or that it honours cache markers sent inside message content.
  • We did not measure hit rate, time-to-first-token improvement or cost change on Plugsky, because the public API does not expose the fields needed to separate a hit from routing variance.
  • We did not test whether a cache_control field is accepted, ignored or rejected by the gateway. The public reference does not document it.
  • We did not verify whether cached tokens, if they exist upstream, count toward Hobby or Starter daily token caps.
  • We did not review a cache-retention schedule or a data-processing addendum specific to cached state.

Frequently asked questions

Does Plugsky support prompt caching?

Plugsky's public API reference does not document a prompt-caching parameter or a cached-token field as of 20 November 2026, and the model catalogue has no caching flag. Builder and Scale do not bill per token, so a cache discount would not change the invoice. Confirm current behaviour with support before designing around it.

What is a prompt prefix?

The prefix is the rendered content before the part that changes: system instructions, tool definitions, few-shot examples, retrieved documents and earlier conversation turns. A provider can only reuse a cached prefix when the whole rendered prefix matches, including ordering and formatting.

Why does editing the system prompt break the cache?

The system prompt is usually the first block in the rendered context. One changed token there changes every token after it, so the new request has no matching prefix. Move timestamps, user names and per-request instructions to the final user message instead.

Does prompt caching change the answer?

No. A cache hit reuses the model's computed key-value state for the same prefix. It does not change the weights or the sampling, so output quality should be unchanged. It only removes repeated prefill work and, on metered plans, reduces the input-token charge.

Is idempotency the same as prompt caching?

No. An Idempotency-Key replays a stored response for the same key and body, which prevents duplicate writes on retry. Prompt caching reuses computation for a shared prefix across different requests. The two solve different problems and can be used together.

How do I measure cache hits?

Log the usage object, time to first token and total latency per request. If the provider returns a cached-token field, divide cached input tokens by total input tokens. Plugsky returns prompt, completion and total tokens but does not publish a cached-token field, so latency and upstream retries are the observable signals.

Related pages

Build for predictable latency

Start free, measure time to first token on your own prompts, then choose the plan that matches your concurrency.

Start Free → See pricing

Sources

Each source was checked on 20 November 2026. Cache behaviour, minimum lengths and retention rules differ by provider and change over time.

Official documentation used for this feature page
SourcePage checkedChecked
OpenAIplatform.openai.com/docs/guides/prompt-caching20 Nov 2026
Anthropicdocs.anthropic.com/en/docs/build-with-claude/prompt-caching20 Nov 2026
Googleai.google.dev/gemini-api/docs/caching20 Nov 2026
Plugskyplugsky.com/docs and /docs/chat-completions20 Nov 2026

Last checked 20 November 2026. Plugsky's canonical plan numbers live at /pricing; this page explains a technique and does not promise a caching feature.