How I Keep the AI Bill Down & the Output Sharp

Managing context window size, prompt cache hits, and sub-agent delegation in Claude Code.

EssayJanuary 20268 min read

People often assume keeping your AI token bill low and keeping code quality high pull in opposite directions. In practice, the same discipline fixes both: controlling what enters the context window on every turn.

Why larger context degrades reasoning quality

A language model reasons over every token currently mounted in its context window. As input length grows, reasoning accuracy degrades well before the context limit is reached—a pattern Chroma documented across 18 frontier models in their Context Rot benchmark. Because every additional input token also increases per-turn cost, curating what enters the window solves both problems at once.

Benchmark chart showing model accuracy declining as input token count increases across frontier models
Reasoning accuracy vs. input token length

Instead of treating the context window as a storage bucket to fill, treat it as the active working memory of the current turn. Loading 100,000 tokens of loosely related files produces slow, hedged output; loading the exact 8,000 tokens required for the task produces accurate code on the first pass at a twelfth of the cost.

Monitoring context and cache hits in the status line

Claude Code status line showing project, git branch, model, effort level, session cost, turn cost, context window utilization, and cache hit rate
Custom Claude Code status line

My terminal status line surfaces the metrics that govern session cost and quality: the left side displays the repository, branch, active model, effort setting, cumulative session cost, and last-turn cost; the right side displays context window fullness (CONTX) and prompt cache hit rate (CACHE). (The statusline script is available in this GitHub Gist.)

Every practice below is designed to keep CONTX low and CACHE high.

Unlike a human developer, an LLM cannot set irrelevant context aside. Every file, failed attempt, and outdated tool output in the window competes for attention weights on every subsequent turn. The most damaging context bloat is not random noise—it is plausible-looking adjacent context: rules from a neighboring domain module, an approach you abandoned twenty minutes ago, or three failed debugging attempts still sitting in the scrollback.

1. Load only the domain slice the task requires

On enterprise projects, I convert the product requirements into a structured JSON contract stored in the repository—the intent model—containing actors, entities, user journeys, business rules, constraints, and open questions:

{
  "rule": "unverified_users_can_draft_but_not_send",
  "applies_to": ["compose", "outbox"],
  "on_violation": "show_verify_prompt"
}

Storing requirements as typed JSON rather than prose serves two purposes: first, a schema forces unambiguous decisions before the coding agent reads the file; second, as Anthropic noted in their work on harnesses for long-running agents, models are much less likely to overwrite or “reword” a structured JSON file unprompted than a Markdown document.

On a multi-domain application, we partition the intent model by domain around a small shared core:

intent/
├─ shared.json        loaded every session
├─ auth.json
├─ compose.json
├─ calendar.json
└─ patterns.json      cross-cutting interaction patterns

# Building the sign-up screen loads : shared.json + auth.json + patterns.json
# It omits                          : compose.json, calendar.json

Omitting compose.json and calendar.json when working on authentication keeps rules that almost apply out of the attention window. Better still, rather than pre-loading files manually, let the agent query only the domain slices it needs via grep or file-read tools.

2. Put durable project context in startup files

Use a strict split to decide where instructions live:

Re-explaining the tech stack, directory layout, and naming conventions in chat every morning wastes tokens on every turn. Instead, keep three small files at the repository root:

CLAUDE.md      stack, conventions, directory structure, and core commands
PROGRESS.md    current milestone state (one short paragraph, updated at checkpoints)
DECISIONS.md   architectural decisions (one-liners so settled questions stay settled)

Workflows that are only needed occasionally—such as generating a slide deck or running a database migration—belong in on-demand Skills so their instructions consume zero tokens until invoked.

As Lazar Jovanovic noted on Lenny’s Podcast, without persistent project files, an agent spends roughly 80% of its token budget reading the codebase just to orient itself, leaving only 20% for implementation. Paying for that context once at the stable front of the session is far cheaper than rediscovering it in chat.

3. Keep the prefix stable to maximize prompt cache hits

Status line showing a 96% prompt cache hit rate
96% prompt cache hit rate

Cached input tokens cost roughly 10% of the price of uncached input tokens. Because prompt caching operates on the stable prefix of the conversation—everything from the system prompt and CLAUDE.md down to the last unchanged turn—keeping CLAUDE.md and your core reference files stable at the start of the session lets every subsequent turn read them at a 90% discount. Editing CLAUDE.md mid-session invalidates the prefix cache and forces the next turn to re-process the entire prompt at full price.

One important mechanic of the 5-minute default cache TTL: the 5-minute timer resets on every cache hit, not from when the cache was initially created. As long as you send turns within five minutes of each other, the cached prefix stays warm indefinitely. The cache only expires when you pause for more than five minutes between turns, forcing the next prompt to pay the full cache-write price again. Working in focused, continuous blocks directly reduces your per-turn bill.

4. Move style and architecture rules into linters

Never spend context tokens reminding an LLM not to hardcode hex colors, skip translation wrappers, or call raw fetch(). Encode deterministic rules as blocking ESLint or AST checks wired into your pre-commit hook:

$ git commit
› running verify...

  ✖  raw hex color, use a design token          no-hardcoded-color
  ✖  untranslated string literal                i18n/no-raw-string
  ✖  direct fetch(), use the api client         no-raw-fetch

  3 errors. commit blocked.

A rule enforced by the linter consumes zero prompt tokens and cannot be forgotten when the context window fills up. As Fiona Fung (who leads the Claude Code and Cowork engineering teams at Anthropic) noted recently, automated verification is the primary bottleneck when engineers ship 8× more code: deterministic tooling has to catch structural violations before a human ever reviews the diff.

5. Flush state to disk and disable unused MCP servers

Long sessions degrade because the context window accumulates the entire history of the task: dead-end file reads, stack traces, intermediate diffs, and tool outputs. None of that history helps the next turn, and all of it is billed and attended to on every message.

Flush state to disk continuously:

List of MCP servers with unused integrations switched off
Disabling unused MCP servers before startup
Token breakdown showing 30 available tools consuming zero startup tokens until invoked
Zero startup token overhead for deferred tools

6. Checkpoint and reset at ~30% context capacity

When the context indicator (CONTX) reaches roughly 30% and the feature is not yet complete, pause and checkpoint:

CONTX  ▓▓▓▓▓▓░░░░░░░░░░░░░░  30% full
             ↑
       Update PROGRESS.md, run verification checks,
       commit a clean WIP snapshot, and /clear.

Why reset at 30% rather than waiting until 80%? Because wrapping up a clean checkpoint—running tests, updating PROGRESS.md, and writing a clear commit—requires reasoning capacity too. Waiting until the window is already degraded produces a sloppy summary.

A recent benchmark of coding agent harnesses across SWE-Bench Verified and Terminal-Bench showed that disciplined context management improved task pass rates by 35.7 percentage points on 32k windows and 2.7 points on 128k windows. While built-in /compact commands can summarize a long session automatically, a summary generated by a cluttered session often carries forward the exact confusion that caused the bloat. Updating PROGRESS.md and resetting takes 30 seconds and starts the next turn with a clean, high-cache-hit window.

When I analyzed my own Claude Code session logs across the year, sessions checkpointed around 30% consistently cost less per completed task than marathon sessions pushed past 60%:

Scatter and bar analysis of session logs showing lower cost per unit of completed work when checkpointing early
Session cost per unit of completed work vs. context length

7. Delegate search and mechanical edits to cheaper sub-agents

Not every step in a workflow requires a frontier reasoning model:

Use a simple heuristic to decide whether a task belongs on a cheaper model: Can you verify the output faster than you could write it yourself, and can the task be written as a deterministic checklist?

8. Two specifics for UI and front-end engineering

  1. Send token specs instead of screenshots whenever possible: Image inputs consume thousands of tokens per turn. Before pasting a screenshot, check whether a concise text specification ("4pt grid, 390×844 viewport, surfaceSunken background, 16pt horizontal inset") communicates the requirement. Save screenshots for genuine visual rendering bugs and final layout verification.
  2. Maintain a compact component registry index: When composing screens, point the agent at a lightweight registry index (component names, prop signatures, and one-line usage rules) rather than reading twelve full component source files into context.

Open problem: scaling the shared core

As a multi-domain repository grows, shared.json in the intent model gradually expands until the shared core itself becomes a noticeable context cost on every session. Splitting shared.json into shared-lite.json (always loaded) and shared-full.json (loaded on demand) simply shifts the guessing game from “which domain module do I need?” to “does this task need a rule hidden in shared-full?” I have not found a clean automated boundary for partitioning the shared core yet.

Directory tree of a partitioned intent model showing shared.json alongside domain-specific modules
Partitioned intent model directory

When to apply these rules

Do not set up this entire harness on day one of a prototype. Every rule above was built in response to a specific failure mode on long-running production repositories. If you constrain context too aggressively during early exploratory prototyping, you choke off the loose, divergent iteration required to figure out what the product should be. As Boris Cherny (head of Claude Code at Anthropic) pointed out, you optimize the token cost of a workflow after the workflow works.

Summary checklist

  1. Load only the active domain slice (shared.json + the current domain module).
  2. Keep durable project context at the front (CLAUDE.md, PROGRESS.md, DECISIONS.md) so it stays warm in the 5-minute rolling prompt cache.
  3. Move deterministic code rules into ESLint and pre-commit hooks so they cost zero prompt tokens.
  4. Disable unused MCP servers and skills before launch so their schemas do not bloat the system prompt.
  5. Checkpoint to disk (PROGRESS.md + git commit) and /clear at ~30% context fullness.
  6. Delegate codebase search and mechanical edits to lightweight sub-agents while keeping architectural reasoning on the frontier model.
All notes