Skip to main content

33 - What a Claude Session Costs: Measure It Before the Invoice

A Claude Code session's cost breaks down into four token items: how to measure it with a status line and JSON, and limit it with a cap and a gate.

What do you think about this article?

33 - What a Claude Session Costs: Measure It Before the Invoice
Claudefedericocalo.dev

At a Glance

A Claude Code session's cost breaks down into four token items: how to measure it with a status line and JSON, and limit it with a cap and a gate.

The problem: the monthly bill is higher than you had planned

You have been working with Claude Code for a few weeks, the bill is going up, and you do not know which session to blame. The cause is rarely the list price: it is that every request consumes tokens of four categories with very different prices, and the category that weighs most on your work is often the one you do not look at, that is the context reread at every turn. That is why the short answer is a practice more than a figure: you measure the spend while you work (the status line of the session), you measure the spend of the automatic jobs (the JSON of claude -p), and you put a cap on what runs without you (--max-budget-usd) with a gate you can trigger on purpose.

You will not find a "Claude costs X a month" here: that number depends on your workload and I did not measure it. You will find the tools to measure yours, with a warning that holds for the whole article: the figures Claude Code shows are estimates computed by the client at list price, not your invoice. Which model to use for which role (a sub-agent, a check) is the subject of Cost optimization Claude Code: Opus / Sonnet / Haiku + sub-agent worktree; here we measure and limit. The effort level, the other lever, is in Claude Effort and Adaptive Thinking.

Four categories of tokens, four prices

A request to the API has a bill you get by adding four items, and each has its own price per million tokens:

  • input_tokens: the input tokens not served from the cache, at full price;
  • cache_creation_input_tokens: the tokens written to the cache the first time, at a higher price (according to the pricing page, 1.25 times the input for the five-minute cache);
  • cache_read_input_tokens: the tokens reread from the cache, at a fraction of the input price;
  • output_tokens: the tokens the model produces, the highest price of the four items.

The point that moves the bill is the third line. In a Claude Code session the context (the instructions, the files read, the conversation) is sent again at every turn, and if the cache works almost all of that context is "cache read". If the cache does not work, the same context is "input" at full price, and the same session costs a multiple. The four names are the ones the status line exposes in context_window.current_usage, and they are also the ones in the listing that follows.

The calculation nobody redoes by hand: a cost from tokens and a table

The costo_usd function takes the four counters and a price table passed as a parameter, with no prices written in the body: list prices change, and a constant inside the function becomes a silent error the day it changes. The scenario in the example is didactic, not a measurement of mine: twenty requests that reread a 100,000-token context, once without cache and once with the cache that writes at the first request and reads on the other nineteen. I copied the Sonnet 5.5 prices from the Pricing page (accessed 2026-11-14), and they must be reread before trusting them.

costo.py - run with python3 -I; didactic scenario, prices to be reread
"""Costo di una richiesta dai token, con la tabella dei prezzi passata come parametro."""
MTOK = 1_000_000


def costo_usd(uso, prezzi):
    """uso: i quattro contatori di current_usage; prezzi: USD per milione di token, uno per categoria."""
    return (uso.get("input_tokens", 0) * prezzi["input"]
            + uso.get("output_tokens", 0) * prezzi["output"]
            + uso.get("cache_creation_input_tokens", 0) * prezzi["cache_write"]
            + uso.get("cache_read_input_tokens", 0) * prezzi["cache_read"]) / MTOK


def sessione(richieste, prezzi):
    return sum(costo_usd(r, prezzi) for r in richieste)


if __name__ == "__main__":
    # Prezzi per milione di token copiati dalla pagina Pricing (consultata il 2026-11-14): RILEGGILA prima di fidarti.
    prezzi = {"input": 2.0, "output": 10.0, "cache_write": 2.5, "cache_read": 0.10}
    contesto = 100_000  # un contesto da 100K token, riletto a ogni richiesta
    senza_cache = [{"input_tokens": contesto, "output_tokens": 800} for _ in range(20)]
    con_cache = ([{"cache_creation_input_tokens": contesto, "output_tokens": 800}]
                 + [{"cache_read_input_tokens": contesto, "output_tokens": 800} for _ in range(19)])
    a, b = sessione(senza_cache, prezzi), sessione(con_cache, prezzi)
    print(f"20 richieste senza cache: {a:.4f} USD")
    print(f"20 richieste con cache:   {b:.4f} USD")
    print(f"rapporto: {b / a:.3f}")

# Output:
# 20 richieste senza cache: 4.1600 USD
# 20 richieste con cache:   0.6000 USD
# rapporto: 0.144

The two sums can be checked by hand, and it is good to do so once: without cache, twenty times 100,000 tokens at 2 USD per million make 4.00 USD, plus 0.16 USD of output; with the cache, 0.25 USD for the initial write, nineteen reads at 0.01 USD and the same output. The ratio of 0.144 is that of this scenario and of these prices: if the context is smaller, if the cache expires between one turn and the next (the five-minute write is valid for five minutes, according to the page) or if the read multiplier is different, it changes. And the multiplier is different from model to model: that is why the table has a dedicated column, and you do not multiply by a "universal" 0.1.

Measuring while you work: the status line

Claude Code passes to a script of your choice, on standard input, a JSON with the state of the session. The fields you need are cost.total_cost_usd (a client-side estimate, reset by /clear) and context_window.used_percentage. The script that follows prints model, cost and how full the context is; the // 0 suffix of jq is a fallback value, because the documentation warns that some fields are missing or null at the start of the session, and a script that breaks at that point switches off the status line exactly when it is needed.

statusline.sh - run with jq 1.8 on two JSONs written by me, with the field names from the documentation
#!/bin/sh
# Riga di stato: modello, costo stimato dalla sessione, contesto usato. Legge il JSON dallo stdin.
input=$(cat)
echo "$input" | jq -r '"[\(.model.display_name // "?")] $\(.cost.total_cost_usd // 0 | . * 10000 | round / 10000) | contesto \(.context_window.used_percentage // 0)%"'

# Output:
# $ echo '{"model":{"display_name":"Sonnet"},"cost":{"total_cost_usd":0.01234},"context_window":{"used_percentage":8}}' | ./statusline.sh
# [Sonnet] $0.0123 | contesto 8%
# $ echo '{"model":{"display_name":"Sonnet"}}' | ./statusline.sh
# [Sonnet] $0 | contesto 0%

The run shows the two paths: with the complete JSON the output is [Sonnet] $0.0123 | contesto 8%, with the poor JSON the script prints zeros instead of failing. The cost is rounded to four decimals with . * 10000 | round / 10000, because on a small session the third digit is the only informative one. To connect the script to Claude Code the "Status line" page explains the configuration key: I do not quote it from memory, open it. The test JSON I wrote myself following the field names of the page; it is not the output of a real session.

Measuring what runs without you: the CI gate

For jobs in non-interactive mode the JSON of claude -p --output-format json contains total_cost_usd, with the same caveats as an estimate. The gate below reads that JSON from standard input and returns three distinct exit codes: 0 if the spend is within the cap, 1 if it exceeds it, 2 if the data is not there. Telling the second from the third is deliberate: "I could not read the cost" and "the cost is high" are two different problems, and a gate that merges them lets the job through or stops it for the wrong reason.

cancello.py - run with python3 -I on three test JSONs
"""Cancello di CI: legge il JSON di `claude -p --output-format json` e boccia la prova se supera il tetto."""
import json
import sys


def verifica(testo, tetto_usd):
    try:
        costo = float(json.loads(testo)["total_cost_usd"])
    except (json.JSONDecodeError, KeyError, TypeError, ValueError) as errore:
        return 2, f"JSON senza total_cost_usd leggibile: {errore!r}"
    if costo > tetto_usd:
        return 1, f"costo stimato {costo:.4f} USD sopra il tetto {tetto_usd:.2f}"
    return 0, f"costo stimato {costo:.4f} USD entro il tetto {tetto_usd:.2f}"


if __name__ == "__main__":
    codice, messaggio = verifica(sys.stdin.read(), float(sys.argv[1]))
    print(messaggio)
    sys.exit(codice)

# Output:
# $ echo '{"total_cost_usd":0.031}' | python3 -I cancello.py 0.50
# costo stimato 0.0310 USD entro il tetto 0.50
# exit=0
# $ echo '{"total_cost_usd":0.62}' | python3 -I cancello.py 0.50
# costo stimato 0.6200 USD sopra il tetto 0.50
# exit=1
# $ echo '{"result":"ok"}' | python3 -I cancello.py 0.50
# JSON senza total_cost_usd leggibile: KeyError('total_cost_usd')
# exit=2

The three runs cover the three branches. Note float(...) inside the try: a field that is present but not numeric falls into code 2 instead of blowing up the script with an unhandled exception. The three JSONs are built by me to test the script: the costs 0.031 and 0.62 are not the spend of any real run.

Putting a cap: --max-budget-usd, and what I do not know

The --max-budget-usd option stops the run when the estimated spend reaches the amount, and it only works in -p mode. Two details of the documentation make it more useful than it seems: the spend of the sub-agents counts toward the cap, and the check is made on the client-side estimate. The same page warns that the spend can exceed the cap, so leave a margin: the amount is a brake, not an exact limit. The scheme below launches a job with a low cap and then passes the result to the gate; it is a template to adapt, I did not run it because it requires a key.

launch with a cap - template to adapt, not executed (it requires a key)
cd "$(git rev-parse --show-toplevel)"
claude -p "Migra i test da unittest a pytest in tutto il repository" \
  --model sonnet \
  --max-budget-usd 0.50 \
  --output-format json > risultato.json
echo "exit=$?"
python3 -I cancello.py 0.50 < risultato.json

To trigger the cap on purpose, as the plan of the series provides, pick a task too big for the amount and check three things: the exit code of claude, the content of risultato.json and the state of the working copy. Here I have to admit what I do not know: I did not read what shape the output has when the cap kicks in, so I do not write "the JSON will contain" nor "the exit will be". The concrete risk you know anyway: a halt midway leaves changes midway. That is why it is better to launch jobs with a cap in an isolated copy, as explained in Letting Claude Code Work Alone.

The trade-offs, summed up: a low cap protects you from the bill but interrupts the work, a high cap lets you finish but moves the risk onto the task; the cache reduces the spend a lot but the initial write costs more than normal input, so for isolated requests that do not repeat the context you gain nothing; and the client's estimates ignore contractual rates, unless the administrator sets the modelPricing table provided by the documentation.

Status as of 2026-11-14: prices per million tokens

Values reread on the official Pricing page on 2026-11-14. Prices change with every generation: the table serves to show that the cache-read column is not a fixed multiple of the input.

ModelInputOutputCache read
Fable 5.28 USD40 USD0.20 USD
Opus 5.54 USD20 USD0.20 USD
Sonnet 5.52 USD10 USD0.10 USD
Haiku 5.5 (prompt up to 100,000 tokens)0.10 USD0.50 USD0.01 USD

For Haiku 5.5 the page declares higher rates for requests with a prompt above 100,000 tokens, cache included: if your context exceeds it, the scenario above does not hold for that model.

What stays true with the next generation

What stays true is the breakdown into four items, the fact that the cache is the biggest lever on long sessions, the estimate nature of the client's figures, and the distinction between measuring (status line, JSON) and limiting (cap, gate). Prices, multipliers and perhaps field names will change: that is why costo_usd receives the table as a parameter and the status-line script has fallback values.

What I did not verify

I ran no session and no job with a cap: no key. The exact format of the halt at the cap, the behaviour of the cache in a real session and the correspondence between estimate and invoice I did not measure. The prices are those of the Pricing page of 2026-11-14.

Frequently asked questions

Is the cost shown by Claude Code the one on the invoice?

No: it is an estimate computed by the client at list price, which can differ from the invoice. If your organisation has contractual rates, an administrator can set a price table so that the estimate follows them.

Does --max-budget-usd work in interactive mode?

According to the documentation of the option it only works in -p (print) mode. For the interactive session the measure is the status line, and you set the limit yourself by stopping.

Why does the same job cost more in one session and less in another?

The most frequent reason is the cache: if the context is read from the cache it costs a fraction, if it is reprocessed it costs the full price. Check the four counters of current_usage in the two sessions.

What you can do now

You can break down the cost of a request into its four items and compute it with a table you update in one place. You can set up a status line that shows you the spend and how full the context is while you work, a CI gate that tells "too expensive" from "missing data", and you know where the --max-budget-usd cap goes and which questions to bring to a real test: what it prints, what it leaves half done.

In this series. Previous article: A 1M Context Is Not Memory: Compaction and What Gets Lost. Next article: Changing Model Generation Without Surprises: the Compatibility Matrix.

Sources

The scripts costo.py, statusline.sh and cancello.py were run on 2026-11-14 (Python 3, jq 1.8) on test data written by me; the launch with a cap was not run (no key). Prices and fields were compared with the official pages on 2026-11-14. The code listings and the program outputs are reproduced exactly as in the Italian original, so identifiers, messages and comments inside them are in Italian.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects