Prompt Caching for Multi-Turn Coding Agents: Why Append-Only Transcripts Cut Your Token Bill
Coding agents resend the whole transcript on every turn. Keeping it append-only, pinning conversations to one server, and replaying reasoning keep prompt-cache hits high.
Disclosure: I build Grokified, an independent OpenAI-compatible gateway for Grok models. I use it below as one example of a provider that sets cache routing for you. It is not affiliated with xAI. Everything else here applies to the xAI API directly, and the same ideas apply to any provider that caches prompt prefixes.
Coding agents are expensive for a structural reason: they resend everything. Every step of a Claude Code, Cline, Aider, or opencode loop sends the system prompt, tool definitions, files read, every tool call and output, and every earlier reply, then adds one more message.
By turn 30 of a debugging session, almost all of each request is text the model has already seen. Prompt caching is how providers stop charging full price for that repetition. It is also easy to defeat by accident. Below: how prefix caching works on the xAI API, what breaks it, how to verify hits, and how to estimate savings from published prices.
How Prefix Caching Works
xAI's documentation describes the mechanism plainly: "The cache works from the start of your messages array. When a request arrives, the system checks how many messages at the beginning match a previous request exactly — that matching portion is the 'prefix' and gets served from cache" (xAI: How It Works).
There are two practical results. Cached messages skip recomputation, so time-to-first-token falls. Cached tokens are also "billed at a reduced rate" (xAI: Prompt Caching).
This fits the shape of an agent loop very well. Grokified's documentation says it directly: "Agent loops that replay the growing transcript on every call are the biggest beneficiary: turn 1 caches nothing, turn 2 caches everything through turn 1, and so on" (Grokified: Prompt caching).
Rule 1: The Transcript Is Append-Only
Matching is exact and runs from the start, so any change to an earlier message ends the match at that point. xAI's best-practices page puts it this way: "Never modify earlier messages — Only append new ones. Any edit, removal, or reorder breaks the cache" (xAI: Best Practices & FAQ).
That conflicts with several things agent frameworks like to do:
- Rewriting the system prompt every turn, for example with a timestamp, the current working directory, or a "files changed so far" summary. If that dynamic block sits at the top, every request misses from message zero. Put stable content first and append dynamic state as a new message.
- Trimming or summarising old tool output in place. Shortening a 4,000-line log from turn 3 saves tokens on paper, but it breaks the prefix from turn 3 onward. Compaction can still be worth doing. Do it rarely and on purpose, not on every turn.
- Reordering tool definitions or building them from an unordered map. If the serialized order changes between calls, the prefix changes too.
xAI's advice to "front-load static content", meaning system prompts, few-shot examples, and reference documents, amounts to the same discipline. The stable parts go at the top and never change.
Rule 2: Pin the Conversation to One Server
Caches are local. In xAI's words: "Prompt caching is not 100% guaranteed. Cache entries can be evicted due to memory pressure, and requests may be routed to different servers." The fix is a routing hint. On xAI's Chat Completions API, it is the x-grok-conv-id header, which "routes requests with the same conversation ID to the same server. Since cache entries are stored per-server, this maximizes your cache hit rate." On the Responses API, the equivalent is prompt_cache_key (xAI: Maximizing Cache Hits).
xAI suggests "a UUID or your application's session ID". Generating a new ID per request spreads one conversation across servers and wastes the cache.
Gateways can do this for you. On Grokified, the header is x-conversation-id for /chat/completions and /completions, and prompt_cache_key in the body for /responses. If you send neither, the docs say Grokified "sets prompt_cache_key for you", deriving "a stable key from your account plus the conversation". If you set your own, "yours wins, and Grokified never overrides it."
Here is the cold-then-warm pattern from Grokified's docs. The same calls work against api.x.ai if you swap the header name.
# Turn 1: a new conversation id has nothing cached, so cached_tokens comes back 0
curl https://api.grokified.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $GROKIFIED_API_KEY" \
-H "x-conversation-id: conv_abc123" \
-d '{
"model": "grok-4.6",
"messages": [
{ "role": "system", "content": "You are a helpful assistant." },
{ "role": "user", "content": "What is prompt caching?" }
]
}'
On turn 2, append the assistant's reply and the next user message and send them on the same x-conversation-id. The system prompt, first user turn, and first reply now match the earlier prefix, so they are served from cache.
Rule 3: Send the Reasoning Back
Reasoning models add a trap. Grokified's docs warn: "For reasoning models, you must also send back reasoning_content from the previous response, or use previous_response_id on /responses to continue statefully. Omitting reasoning content is the top cause of an otherwise correct prefix still missing the cache."
The server's record of the previous turn includes the reasoning. If your client strips it before replaying the assistant message, the "unchanged" history no longer matches what was cached.
See xAI's reasoning guide for how reasoning output is returned.
Measure It: Read cached_tokens
Don't assume caching is working. Check it. Both APIs report it in the usage block (xAI: Usage & Pricing):
- Chat Completions:
usage.prompt_tokens_details.cached_tokens - Responses:
usage.input_tokens_details.cached_tokens
A value of 0 is a miss, which is expected on the first turn or after an eviction. Any positive value is a partial hit. A value equal to prompt_tokens is a full hit. xAI's documented example of a healthy conversation shows cached_tokens rising each turn: 0, then 50, then 120, as each turn's prompt becomes the next turn's cached prefix. The same page adds: "If cached_tokens is consistently 0 across multiple requests in the same conversation, verify that you're setting x-grok-conv-id (or prompt_cache_key)" and that earlier messages are unchanged.
Log both numbers for every agent step. A hit ratio that drops to zero mid-session usually means something rewrote history.
What It's Worth: Arithmetic, Not a Benchmark
I won't give a measured "X% saved" figure, because the result depends on your transcript shape. You can still work out the range from published prices. xAI's pricing page lists grok-4.7 at $2.00 per 1M input tokens, $0.50 per 1M cached input tokens, and $6.00 per 1M output tokens for prompts under 200K tokens. Cached input therefore costs a quarter of fresh input. For grok-4.3 the figures are $1.25 input and $0.20 cached, so cached costs 16% of fresh.
Take a purely illustrative agent step on grok-4.7: a 100,000-token prompt where everything except the last 5,000 tokens repeats the previous turn.
- No cache hit: 100,000 × $2.00 / 1M = $0.200 of input
- Prefix hit: 95,000 × $0.50 / 1M + 5,000 × $2.00 / 1M = $0.0475 + $0.010 = $0.0575 of input
That is about 71% less input cost for that step, using list prices only. Output tokens cost the same either way. The longer the session runs, the more of each prompt is repeated as prefix, and the closer you get to the cached-rate floor.
There is one more pricing detail that matters for agents. xAI bills the long-context rate "for all tokens in a request once its prompt reaches the model's long context threshold". For grok-4.7, that threshold is 200K tokens, and the rates double to $4.00 input, $1.00 cached, and $12.00 output. Unbounded transcripts pay twice: once for size, again at the higher tier.
For comparison, the Grokified example: its pricing page lists grok-4.7 at $1.00 input and $3.00 output per 1M, and says the 50% rate "applies to every token type a model bills for, including cached input and reasoning tokens". Grokified's own headline claim is that "repeat calls use more than 80% fewer tokens than direct API calls". That is the vendor's statement, not something I've measured independently here. Check it with cached_tokens on your own workload.
A Checklist for Agent Builders
- Keep the system prompt and tool schemas byte-identical across turns, with deterministic serialization.
- Only append. Put dynamic state in new messages, not at the top.
- Send a stable conversation ID (
x-grok-conv-id/prompt_cache_keyon xAI), or use a gateway that sets one for you. - Replay
reasoning_content, or chain turns withprevious_response_id. - Log
cached_tokensevery step and alert when it drops to zero. - Compact rarely and deliberately, ideally before crossing a long-context threshold.
- Design for misses. xAI states that "your application should work without caching."
Prompt caching rewards one discipline: treat the transcript as an append-only log. Coding agents already have that shape; most of the work is not breaking it.
Sources: xAI Prompt Caching docs (overview, How It Works, Maximizing Cache Hits, Usage & Pricing, Best Practices), xAI Pricing, and Grokified Prompt caching docs and Pricing. All accessed 18 October 2026. Prices change, so check the linked pages before relying on the figures above.
Opinions expressed by DZone contributors are their own.