Skip to content

Lesson 22 of 40Quality loops

Working on a Token Budget

Cut token use in AI coding tools and in your own AI apps, and calculate what a workflow really costs before you run it.

14 min read0/5 questions

Every word an AI model reads or writes is measured in tokens, and tokens are what you pay for, what you wait for, and what fills the model's limited attention. Two developers can do the same task with the same tool and use ten times different amounts. The difference is almost never the model. It is habits: how long the session runs, what gets pasted in, what gets read twice. This lesson gives you those habits for coding tools like Claude Code, then the matching techniques for apps you build on the API, with runnable calculators so you can see the numbers.

Why tokens matter

A token is a chunk of text, often part of a word, and the unit models count in. Tokens and Context covered the basics, so this is a short recap. Here is why they matter in practice:

  • Cost. API pricing is per million input tokens and per million output tokens. On a subscription, heavy use hits your usage limits sooner.
  • Speed. More input takes longer to process, and more output takes longer to generate.
  • Quality. This is the one people miss. As the context window (everything the model sees this turn) fills with old logs, stale file contents and abandoned attempts, answers get worse. This is called context rot. A lean context is not only cheaper, it is smarter.

The key fact behind every habit below: models are stateless. The tool resends the whole conversation on every turn. A 30,000-token log you pasted in turn 2 is paid for again in turn 3, turn 4, and every turn after, until you clear it.

Predict the outputPython

What does this print?

total = 0
context = 1000
for turn in range(3):
  total += context
  context += 500
print(total)
Need a nudge? Hints walk you through it.

Where the tokens go

In a Claude Code session, each request is built from layers. Some you control directly.

What fills a coding session's context
  1. System prompt + toolsfixed by the tool; MCP servers add more
  2. CLAUDE.mdloaded every session, every turn
  3. Conversation historyyour messages and the replies
  4. File readswhole files the agent opened
  5. Tool outputtest runs, logs, command output

The system prompt and tool definitions come with the tool. Every MCP server you connect adds its tool descriptions here, so disconnect servers you do not use.

1/4

Run /context in Claude Code to see this breakdown for your current session, and /usage (alias /cost) to see cost and usage. Look before you optimise.

Habits for coding tools

Start fresh per task. When you finish one task and start an unrelated one, run /clear. The old history is pure cost and noise for the new task. claude -c lets you continue a session later if you do need it.

Keep project memory lean. Your CLAUDE.md should hold commands, conventions and gotchas, not a copy of your docs. Use @path/to/file.md imports only for files that are needed in most sessions. A 9,000-token memory file costs 9,000 tokens on every turn of every session.

Point, do not paste. Instead of pasting a file into the prompt, name it: "the bug is in src/cart/total.ts, in applyCoupon". The agent reads what it needs, often just the relevant part. Instead of pasting a 2,000-line log, filter it first, for example npm test 2>&1 | tail -50, or pipe it to a headless run: cat logs.txt | claude -p "explain these errors".

Do not re-read huge files. If the agent keeps opening the same giant file, tell it the function and line range to look at, or split the file.

Compact long sessions. When one task genuinely needs a long session, /compact summarises the history to free space. Give it a focus, such as /compact keep the failing test names and the plan, so the summary keeps what matters.

Use subagents for exploration. A subagent has its own context window. Ask it to search the codebase or read a long log, and only its short summary comes back to your main session. The thousands of tokens it read stay out of your main context. The built-in Explore subagent is made for read-only searching.

Match the model and effort to the job. Renaming a variable does not need the most capable model at maximum effort. /model switches models and /effort sets how much the model thinks. Lower effort means fewer tokens and faster answers; keep higher effort for hard debugging and design.

Match the pairs0/4 matched

Match each command to the problem it solves.

Choose an item, then its match on the other side.

Comparing two workflows

Here is the same three tasks done two ways, with made-up but realistic numbers. Workflow A runs one long session with a bloated memory file, pastes full logs and reads whole files. Workflow B clears between tasks, keeps memory small, and uses targeted reads and subagent summaries. Prices are the Sonnet 5.5 snapshot from the course model table, which will change over time.

Python
INPUT_PRICE = 2.00 # dollars per million input tokens (Sonnet 5.5 snapshot)OUTPUT_PRICE = 10.00 # dollars per million output tokens def run_session(name, base, turns_per_task, tasks, added_per_turn, clear_between_tasks): total_in = total_out = 0 history = 0 for task in range(tasks): if clear_between_tasks: history = 0 for turn in range(turns_per_task): total_in += base + history # the whole context is resent every turn total_out += 800 # the reply history += added_per_turn + 800 cost = total_in / 1e6 * INPUT_PRICE + total_out / 1e6 * OUTPUT_PRICE print(f"{name}: {total_in:,} input tokens, {total_out:,} output, ${cost:.2f}") return cost # A: one long session, 9k-token CLAUDE.md, whole files and full logs pasted in.a = run_session("A one long session ", base=20_000 + 9_000, turns_per_task=8, tasks=3, added_per_turn=6_000, clear_between_tasks=False) # B: /clear per task, 1k-token CLAUDE.md, targeted reads, subagent summaries.b = run_session("B fresh per task ", base=20_000 + 1_000, turns_per_task=8, tasks=3, added_per_turn=1_500, clear_between_tasks=True) print(f"B costs {b / a:.0%} of A")
Output
Press Run (⌘ Enter) to see what happens.

Output tokens are identical, yet B costs about a third of A. All the waste is input: old history and big pastes, resent turn after turn. Try setting only clear_between_tasks=True for A and see how much one habit is worth. Real tools also cache repeated context, which softens these numbers, but the shape holds, and so does the quality cost of a cluttered context.

Quick checkPick all that apply
Which habits reduce token use in a coding session? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

Saving tokens in your own apps

When you build on the Claude API, the same ideas apply, plus some tools that only exist there.

Prompt caching. Many apps send the same big block on every request: a system prompt, tool definitions, a product manual. Prompt caching stores that prefix so repeat requests read it at about a tenth of the normal input price. Writing to the cache costs a bit more than normal input, and the default cache lifetime is 5 minutes. Caching is a prefix match: put stable content first and changing content last, because any change in the prefix invalidates everything after it.

import anthropic
 
client = anthropic.Anthropic()
response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    cache_control={"type": "ephemeral"},
    system=PRODUCT_MANUAL,  # large and identical on every request: first
    messages=[{"role": "user", "content": question}],  # changes: last
)
print(response.usage.cache_read_input_tokens)  # above zero on repeat requests

A classic bug: putting the current time in the system prompt. The prefix changes every request, so the cache never hits, silently. Check cache_read_input_tokens to confirm caching works.

A cache-friendly request
Tools: same every requestToolssame every requestSystem prompt: same every requestSystem promptsame every requestBig document: same every requestBig documentsame every requestCache: about 1/10 priceCacheabout 1/10 priceUser question: changes each timeUser questionchanges each timeModel: reads it allModelreads it allprefix storedcheap readfull price

Order the request from most stable to least stable. Tools, system prompt and large documents go first.

1/4

Here is what that saves for 1,000 requests with a 10,000-token stable prefix:

Python
INPUT_PRICE = 2.00 / 1e6 # dollars per input token (Sonnet 5.5 snapshot)CACHE_READ = 0.1 # cached reads cost about a tenth of normal inputCACHE_WRITE = 1.25 # writing costs a bit more; 1.25x is an assumption here requests = 1_000prefix = 10_000 # system prompt + tool definitions + product docs: never changessuffix = 500 # the user's question: changes every time no_cache = requests * (prefix + suffix) * INPUT_PRICEwith_cache = (prefix * CACHE_WRITE # first request writes the cache + (requests - 1) * prefix * CACHE_READ # the rest read it + requests * suffix) * INPUT_PRICE # the changing part is never cached print(f"no caching: ${no_cache:.2f}")print(f"with caching: ${with_cache:.2f}")print(f"saved: {1 - with_cache / no_cache:.0%}")
Output
Press Run (⌘ Enter) to see what happens.

This assumes requests arrive often enough to keep the cache warm. Check the official docs for the current cache pricing and lifetime options.

Other levers in apps:

  • Pick the smallest model that holds quality. In the dated snapshot, Haiku 5.5 is $0.10 / $0.50 per million tokens against $2 / $10 for Sonnet 5.5: a classifier that works on Haiku costs a twentieth as much.
  • Lower effort with output_config={"effort": "low"} for simple tasks.
  • Cap output with a sensible max_tokens, and ask for short formats.
  • Batch offline work. The Message Batches API processes requests asynchronously at 50% of the price, with results within 24 hours. Good for nightly reports, bulk tagging and evals.
  • Measure. client.messages.count_tokens(...) tells you a request's input size before you send it, and response.usage tells you what you paid for after.
Put it in order5 steps

Order the parts of a request for the best cache hits, from first to last.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Your app sets prompt caching, but cache_read_input_tokens is always 0. The system prompt starts with Current time: 14:03:22. Why?
Need a nudge? A hint rules out a wrong answer.
Key terms
token budget
The amount of input and output tokens you are willing to spend on a task or request.
context rot
Answer quality dropping as the context fills with old, irrelevant material.
/compact
A Claude Code command that replaces long history with a summary to free context space.
prompt caching
Storing a stable request prefix so repeat requests read it at a fraction of the input price.
prefix match
Caching only reuses the request up to the first part that changed.
Message Batches API
Asynchronous processing of many requests at half price, with results within 24 hours.
effort
A setting that controls how much a model thinks; lower means fewer tokens and faster replies.