Prompt caching, compression, and compaction in coding agents

By

Updated

Tagged: AI

Learn how prompt caching, transport compression, and context compaction affect coding agent costs, speed, memory, and usage, with practical examples.

If you just want a quick definition, check prompt caching in the AI glossary.

When a coding agent fixes a single bug, it sends our project instructions over and over. Every time a tool finishes running, the agent makes a fresh request and packs in enough conversation history to pick up where it left off.

We have three main ways to make those loops cheaper or faster. Each one targets a different part of the stack, and mixing them up makes release notes confusing fast.

TechniqueWhat changesWhat it saves
Prompt cachingReuses model processing for a matching prefixRepeated input processing
Transport compressionSends fewer bytes that expand back to the same requestNetwork transfer
CompactionReplaces earlier conversation with a shorter versionContext space and future input processing, at the risk of losing detail

Knowing which one is which saves me a lot of confusion the next time a session burns through usage faster than expected.

Prompt Cost Diff

Compare two prompt variants: token delta and dollar savings per model, per call and per month.

Prompt cost diffInteractive · runs in your browser

Variant A

Variant B

Calls per month

Shareable in the URL. Prompt text stays local — never synced.

Token delta

Cost comparison

Input tokens only ( pricing). Sorted by biggest monthly savings first.

ModelCost ACost BPer callPer month

Prompt text never leaves your browser. Costs assume every call sends the full prompt as input — no caching, no output tokens.

Why a short instruction can use a lot of tokens

I type “fix the validation”, which is only a few words. Behind the scenes, the request sent to the model also carries project instructions, tool definitions, any files the agent opened, and earlier messages.

Then the agent runs a test. Running the command in the terminal uses zero tokens, yet the model still has to decide what to run and read the output, so the next request sends the test result plus all earlier history.

Do that ten times in a row and total input adds up way past the few words we typed. Your context window is the limit for one request, while total usage is the sum across all ten (see tokens and usage limits for how Claude Code, Codex, Cursor, and Grok show that total).

Caching lowers the cost of reprocessing that repeated history on every turn, though the history still sits inside the context window.

Start with the repeated prefix

Every prompt starts with a prefix: our instructions, tool definitions, reference files, and conversation so far. When the next request begins with the same prefix and adds new messages at the end, the provider reuses the saved model state from earlier, as explained in OpenAI’s prompt caching documentation.

To get a cache hit, the prefix content and request settings have to match, and the cached entry still has to be warm on the server.

Say we have a coding task with stable project rules at the top and a changing request at the bottom:

Project rules: use the existing validation helper.
Reference: the form submits to /api/contacts.
Task: fix the missing email validation.

On the next turn, we keep those earlier messages untouched and append the test result at the end. Slip a fresh timestamp into the rules at the top, and you break the prefix for everything after it.

The cache checks exact input, not meaning. “Use the existing validation helper” and “Reuse our validation helper” say the same thing to us, yet the model sees two different prompts. Change a single line near the top and everything after it gets reprocessed from scratch.

Real providers also require a minimum token length before caching kicks in and have specific rules on where cache boundaries land. Put timestamps or other changing values after the stable prefix so the agent still sees them without busting the cache.

Fig 1 · 1/4Three different optimizations
A request travels to the model

A cache hit still produces a new answer

Prompt caching only reuses the work the model did reading our input. It still reads whatever new content we added and generates a fresh reply from scratch.

So a cached prefix isn’t the same thing as a cached answer. You can ask the same question twice, get a cache hit both times, and still get two different replies.

If you’re using Claude, Anthropic’s caching guide covers automatic caching and explicit cache breakpoints. By default a cache stays alive for five minutes (with a one-hour option), and each cache read resets the timer.

When I build my own agent harness, I pull those settings straight from the provider’s docs for that model. In an existing coding CLI or editor, check which knobs it exposes instead of assuming every API flag maps to an env var:

A cache hit still needs a new responseEach request checks for an eligible matching prefix with an available cache entry. A hit reuses processing for that prefix, while a miss requires fresh processing. Both paths process new input and generate a new response.YesNoNext model requestEligible matchingprefixand cache entryavailable?Reuse processingfor that prefixProcess theprefix afreshProcess new inputGenerate a newresponse

Cache reads and cache writes have different costs

Before later requests can read from a cache, the first request has to fill it. Some providers charge extra for that initial cache write compared to normal input, then give you a steep discount on every read after that. Because of the upfront write cost, long sessions with lots of reuse save far more than quick one-off tasks.

Take a rough example with made-up prices just to see the math. Say your reusable prefix is 20,000 tokens, normal input costs $1 per million tokens, cache writes cost $1.25, and cache reads cost $0.10.

Processing that prefixCalculationCost
One ordinary input20,000 × $1 / 1,000,000$0.020
One cache write20,000 × $1.25 / 1,000,000$0.025
One cache read20,000 × $0.10 / 1,000,000$0.002
Ten ordinary inputs10 × $0.020$0.200
One write, then nine reads$0.025 + 9 × $0.002$0.043

That $0.043 only covers the repeated prefix when all nine follow-up turns hit the cache. Your real bill also includes new messages, generated output, and any extra cache writes as the conversation grows.

To calculate real numbers, pull the usage fields from your provider’s API and match them against your model’s rate card. In OpenAI’s Responses API, usage.input_tokens_details.cached_tokens tells you how many input tokens came from cache, and models that bill cache writes separately also return cache_write_tokens with a lifetime breakdown. Check OpenAI’s calculation guidance so you don’t accidentally count those writes twice.

Compression changes the journey to the server

If both your client and the API endpoint support gzip, you can compress a request so it travels as fewer bytes over the network. Once it reaches the server, it unpacks into the same JSON.

It’s like emailing a huge text file inside a ZIP archive. Unzipping it gives the recipient the same file, so we saved bandwidth during upload while the document itself stayed just as long.

Agent requests work the same way. Transport compression speeds up slow uploads, while prompt-cache hits and input token counts stay untouched.

Whenever we read a performance claim, check what was measured. Upload duration, request size, model input tokens, and time to first response are four different numbers.

Be careful with how product announcements use the word “compression” too. Some tools mean trimming context or summarizing tool output, which changes what the model sees. The quick test is whether unpacking restores the original request or threw information away.

Compaction changes what the model receives

Long sessions pile up old logs and dead ends. Compaction swaps earlier history for a shorter version so future requests carry less (see compaction for commands in Claude Code, Codex, Cursor, and Grok Build).

Compaction hooks can run scripts around that summary. In Claude Code, a PreCompact hook can tell the summarizer which details to keep.

Some agents write a plain-text summary you can edit, while OpenAI’s compaction API can return an encrypted state blob carrying prior context and reasoning.

Because compaction rewrites the start of the chat, it changes the prefix and drops cache reuse right afterward (as OpenAI’s cache guide notes). Look at total input cost instead of hit rate alone, since sending way fewer tokens can still come out cheaper.

Compaction can also drop details we still need, so give the agent files to re-read.

Say we’re debugging a reset-token bug after pages of failed test logs. A good handoff keeps the requirement, root cause, changed files, latest test result, and key decisions like “keep the existing session policy”. A vague note like “working on authentication” drops everything useful.

I put lasting project rules in AGENTS.md and task-specific decisions in a short repo note, leaving code and tests on disk where the agent can read them. Deciding what the next session sees is context engineering.

I skip compacting just to make a usage bar look tidy. I run it when a thread gets expensive or sluggish, then check that the next turn still has what it needs.

A lower cache hit rate can still mean a cheaper session

Say a request has 100,000 input tokens and 90,000 come from cache (a 90% hit rate).

Now compact the thread, and the next request drops to 15,000 tokens with zero cache hits. The hit-rate meter looks terrible, yet the model is reading a fraction of the input.

Give it a few turns before judging the numbers. Once that shorter history starts hitting cache on follow-up turns, the one-time compaction cost often pays for itself.

Look at usage before changing settings

Before I tweak any setting, I check what the tools report. In Claude Code, /usage shows prompt-cache hits, misses, and rebuilds (see the cost documentation), tracking the main chat while subagents appear separately.

When calling the API from my own app, I log input tokens, cached tokens, output tokens, and latency together (plus cache writes when exposed). Compare similar tasks with identical model settings, because a quick one-shot run behaves very differently from a long cached session.

Keep API billing and subscription limits separate too. Cached tokens still count toward OpenAI’s API tokens-per-minute limits, while coding subscriptions track weekly allowances under their own rules.

What I check when usage jumps

I start with one task and check what changed between requests. A huge log read, a model swap, and a new subagent each leave a different footprint.

What you noticeWhat to check
Input grows on every turnLarge file reads, repeated logs, and piled-up tool results
Cache reuse drops after an idle gapThe provider’s cache lifetime and the cache state the app reports
Cache reuse drops while you’re workingChanged instructions, tool definitions, model settings, or compaction
Cache reuse stays high, but total usage risesMore requests, a bigger reusable prefix, generated output, and background work
Requests upload faster, but token usage stays similarWhether the change only compressed network traffic
The agent loses a requirement after compactionThe task state it kept and the project files it can reread

You can hit a high cache rate and still run up a big bill. Reusing a huge prefix hundreds of times adds up, and every reply still pays output rates.

I keep terminal output focused on the next decision. Ask for the failing test and error instead of dumping a full build log into context, and start a fresh chat whenever you switch to an unrelated task.

AI Agent Cost Visualizer

See how multi-step agent runs get expensive as context grows each step, with a per-step cost table and monthly totals.

AI agent step-cost visualizerInteractive · runs in your browser

Assumptions

Totals

Per run

Per day

Per month (30d)

Input tokens / run

Cost per step

Input billed = initial context + (step − 1) × tokens added. Each row is one LLM call in the agent loop.

StepInput tokensOutput tokensStep costCumulativeRelative

Prices verified December 2, 2026 against vendor pricing pages. Steps whose context crosses a model's long-context threshold use the higher rate. No prompt caching modeled — real agents with cache hits pay less on repeated prefix tokens.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: