Token pricing and budgeting for LLM apps and coding agents

By

Tagged: AI

How input/output asymmetry, prompt caching, reasoning tokens, and O(N^2) agent loops drive API bills, with live cache traces and a Node.js budget guard.

Most developers estimate an LLM bill the same way the first time. You check the input price on a pricing page, multiply by how many words a user might type, and figure the feature will cost pennies.

Then you ship the app, or let a coding agent run for an afternoon. The invoice comes back ten times higher than your spreadsheet predicted.

Once we look at what crosses the wire on each call, the math becomes predictable. Four forces drive almost every surprise bill:

  • Output tokens cost four to five times more than input tokens.
  • System prompts and tool schemas ride along on every single request.
  • Multi-turn sessions grow quadratically instead of linearly.
  • One dynamic line at the top of a system prompt can wipe out prompt caching completely.

To show how those numbers add up in practice, I ran a live 8-turn gpt-4.1-mini test measuring how badly a single timestamp breaks caching. I also modeled a 25-turn coding agent session at Claude Sonnet rates and built a Node.js BudgetGuard class that enforces hard dollar caps before a runaway loop drains your account.

Why token bills catch developers off guard

Before we look at vendor rate cards or caching, we need to understand what the meter counts. API providers bill in tokens instead of words or characters, and the text-to-token ratio shifts sharply depending on what you send.

Input and output price asymmetry

Every major frontier API prices output tokens far higher than input tokens. On gpt-4.1-mini, input costs $0.40 per million tokens while output costs $1.60, a 4x spread.

On gpt-4.1, that ratio stays at 4x with $2.00 input and $8.00 output. Claude Sonnet 4.5 widens the gap to 5x at $3.00 input and $15.00 output, and Claude Opus sits at $5.00 input and $25.00 output, also 5x.

Why is the gap so wide? It comes straight from how GPUs run transformer models.

Reading your prompt (the prefill phase) happens in parallel across all input tokens, which keeps GPU compute units busy. Generating the reply (the decode phase) runs one token at a time.

For every single output token, the server has to load the model’s weights from GPU memory again. Memory bandwidth becomes the bottleneck, so one output token ties up hardware far longer than one input token.

If you are building an app, verbose output quietly multiplies your bill. Asking a support triage endpoint for a 700-token explanation when a 35-token JSON label would do means paying a steep tax on every request.

And if an untrusted user can steer your prompt into generating 4,000 tokens of output per call, your bill climbs much faster than your incoming prompt sizes suggest.

The tokenization tax on code, JSON, and non-English text

You have probably heard that one token equals roughly four characters of English prose. That rule of thumb works fine on plain English articles, and it falls apart as soon as you send code, JSON, server logs, or non-Latin text.

Most LLMs use byte-pair encoding (BPE) tokenizers, which merge common English words into single tokens. Words like configuration or middleware often cost just one token.

Code and structured payloads behave differently. Curly braces, quotes, colons, commas, deep indentation, UUIDs, and minified stack traces split into many small pieces.

In practice, a dense JSON payload or raw stack trace averages closer to 2.2 to 2.8 characters per token.

Non-English text pays an even heavier tax because English dominates tokenizer vocabularies and training data. Italian, Spanish, French, and German commonly take 20% to 40% more tokens than the same sentence in English.

Japanese, Korean, Arabic, and Hindi can take two to three times as many tokens per sentence. If we estimate unit costs using short English test prompts and then ship to international users, our real per-request spend jumps right away.

Images add another hidden layer. Sending a screenshot to a vision model converts it into a fixed grid of visual tokens, such as an 85-token base plus 170 tokens per 512x512 tile on high-detail OpenAI vision calls.

A desktop or browser agent that attaches a fresh full-resolution screenshot on every turn adds 1,000 to 1,500 tokens per frame. Worse, it keeps re-sending older screenshots on later turns unless the harness strips them from history.

Hidden overhead before the user types a word

Picture a normal turn inside a coding agent or SaaS assistant. You type “Fix the failing date parser test.”, which is roughly 8 tokens.

What leaves your machine is much larger. Ahead of those 8 tokens sit four big chunks of hidden input:

  • The system prompt, often 800 to 3,000 tokens of rules, safety instructions, and repo guidelines.
  • Every tool definition serialized as JSON Schema.
  • Retrieved files or search results.
  • The entire prior conversation transcript.

Tool definitions alone catch almost everyone off guard the first time we inspect raw request logs. One well-documented tool schema easily uses 150 to 450 tokens.

Connect an agent to three MCP servers exposing 40 tools, and you just bolted 8,000 to 12,000 tokens onto the front of every API call. You pay for all of them even on turns where the model only calls read_file.

In my 30-day Codex API vs subscription breakdown, my median single model call sent over 150,000 input tokens even when I typed one short sentence. If we only count what the user types, we miss almost the entire bill.

Every modern pricing lever in LLM APIs

Early LLM APIs had just two numbers on their pricing page: input and output. Today, one model comes with a whole stack of billing tiers.

When we understand each lever, we can cut costs by 50% to 85% without dropping down to a weaker model.

Here are the four published rate cards I used for the live test and simulations in this post (all prices are per 1 million tokens):

ModelInputCached inputOutputOutput/input ratioCache read discount
gpt-4.1-mini$0.40$0.10$1.604x75%
gpt-4.1$2.00$0.50$8.004x75%
Claude Sonnet 4.5$3.00$0.30$15.005x90%
Claude Opus (5/4.5 tier)$5.00$0.50$25.005x90%

On top of those base rates sit four levers that shape real bills: prompt caching, reasoning tokens, batch queues, and long-context cliffs.

Prompt cache reads, cache writes, and TTL windows

Prompt caching lets a provider reuse the computed attention state (the key-value cache) for an identical prompt prefix it saw recently. Instead of running full prefill over 30,000 tokens of system rules, tool schemas, and past turns, the server loads the saved state and only processes the new tokens at the end.

OpenAI and Anthropic bill caching differently, and mixing up their rules will break your cost tracking.

OpenAI turns on prefix caching automatically once a prompt reaches 1,024 tokens, with no write surcharge. Your first call pays the regular input price, and later calls matching that prefix get a 75% discount on gpt-4.1 and gpt-4.1-mini (up to 90% on newer coding tiers), metered in 128-token blocks.

OpenAI cache entries stay warm for 5 to 10 minutes of inactivity, lasting up to an hour during quieter periods, and supported models also offer 24-hour retention. Passing a stable prompt_cache_key (such as a hash of your workspace or system prompt) routes matching requests to the same serving pool so cache hit rates stay high under concurrency.

Anthropic splits cache writes from cache reads and lets you place explicit cache_control breakpoints alongside automatic caching. A standard 5-minute TTL (time-to-live) cache write costs 1.25x the base input rate, or $3.75 per million tokens on Sonnet 4.5.

An extended 1-hour TTL cache write costs 2x the base input rate ($6.00 per million). Every cache read costs 0.10x the base input rate ($0.30 per million, a 90% discount), and each read resets the TTL timer.

Do those write surcharges pay off? Let’s check the break-even math:

  • A 5-minute cache write pays for itself on the very first read: 1.25 + 0.10 = 1.35, compared to 2.00 for two uncached calls.
  • A 1-hour cache write breaks even on the second read: 2.00 + 0.10 + 0.10 = 2.20, compared to 3.00 for three uncached calls.

That TTL window matters a lot in interactive coding agents. We routinely pause for 8 or 12 minutes to review a diff, reply to a message, or run a manual check.

On a 5-minute TTL, the cache expires on every coffee break and forces a full re-write when you come back. On a 1-hour TTL, the prefix stays hot across those pauses and saves money over an afternoon of work.

Where you put breakpoints helps too. I place one breakpoint after static tools and system rules, another after large shared docs, and a third on the latest turn so older history stays cached.

For how prompt caching compares to transport compression and context compaction inside coding tools, see prompt caching, compression, and compaction in coding agents.

Reasoning and thinking tokens

Reasoning models introduce a cost trap because the most expensive tokens are often hidden from the final answer. When a model spends 3,200 internal thinking tokens to write a 180-token reply, you get billed for 3,380 output tokens at the full output rate.

On a frontier model priced at $15 to $25 per million output tokens, one call that burns 6,000 thinking tokens costs $0.09 to $0.15 in output alone before counting input.

If a background pipeline runs 1,000 classification jobs with high reasoning effort left on by default, thinking tokens can quietly turn a $2 batch into a $90 bill.

Thinking tokens also rarely help your prompt cache across turns. Providers typically drop previous reasoning traces from later context windows or return a compact opaque state instead.

Because of that, I always pin an explicit reasoning effort (low, medium, high) or a thinking token cap on each endpoint. A log tagger or schema extractor rarely needs deep chain-of-thought, so we can reserve high thinking budgets for root-cause debugging, tricky SQL migrations, and multi-file refactoring.

Batch API discounts for async workloads

When no live user is staring at a loading spinner, calling a synchronous endpoint throws away half your budget. OpenAI, Anthropic, and Google all offer asynchronous Batch APIs with a flat 50% discount on both input and output tokens.

In exchange, you accept a 24-hour completion SLA, though most batches finish within minutes to a couple of hours in practice.

Batch APIs fit offline engineering jobs cleanly:

  • Nightly regression evals.
  • Backfilling summaries across 20,000 archived records.
  • Classifying historical support threads.
  • Scoring prompt changes against a test dataset.

On providers that support cached prefixes inside batch jobs, the 50% batch discount stacks on top of cache read savings. Before we wire any cron job or data pipeline to a synchronous endpoint, it helps to ask one question: would waiting 30 minutes hurt anyone?

Long-context surcharge cliffs

Many flagship models advertise a 1 million token context window, yet token prices rarely stay flat all the way up. Providers frequently place a surcharge threshold around 200,000 or 272,000 input tokens, and crossing it hits a cliff instead of a marginal bracket.

Once a request passes 200K or 272K input tokens, the entire request flips into the long-context tier, commonly 2x for input and 1.5x for output. A 275,000-token request pays double on all 275,000 tokens, and its output tokens get marked up too.

That pricing reflects real GPU compute, since self-attention work grows quadratically with prompt length during prefill.

On your invoice, letting an agent session drift from 195K tokens to 210K tokens doubles per-turn input spend on the spot. If we keep active sessions below that cliff with compaction or fresh handoffs, we cut out a huge chunk of avoidable spend.

The O(N^2) arithmetic of multi-turn chat and agent loops

Single-shot API calls are easy to budget. You send 1,500 tokens, get back 300 tokens, and the meter stops.

Multi-turn chats and coding agents behave very differently because LLM HTTP endpoints are stateless. Every time an agent reads a file, runs a shell command, edits code, or gets your next reply, the harness appends the new turn and re-sends the whole conversation from token zero.

That turns linear work into quadratic token volume.

Suppose a session opens with an initial prefix of $P_0$ tokens (system prompt, tool schemas, and the opening task). Each turn adds $\Delta$ tokens of new history from the assistant reply, tool arguments, and tool output or user message.

On turn $t$, the prompt sent to the model has this size:

Input(t) = P0 + (t - 1) * Delta

When we sum that from turn 1 to turn $N$, we get a triangular sum:

TotalInput(N) = sum_{t=1..N} [ P0 + (t - 1) * Delta ]
              = N * P0 + Delta * N * (N - 1) / 2

Notice that the second term scales with $N^2$. Doubling an agent loop from 10 turns to 20 turns nearly quadruples cumulative input tokens.

Let’s plug in realistic coding-agent numbers at Claude Sonnet 4.5 rates ($3.00 input, $0.30 cached input, $15.00 output per million tokens):

  • Initial prefix $P_0 = 6,000$ tokens (system instructions, repo conventions, and tool definitions).
  • Per-turn growth $\Delta = 1,800$ tokens (a file read, diff, or test output plus assistant commentary).
  • Output per turn = 450 tokens.
  • Session length $N = 25$ turns.

Plug those numbers into the triangular sum and we get:

TotalInput(25) = 25 * 6,000 + 1,800 * (25 * 24) / 2
               = 150,000 + 1,800 * 300
               = 150,000 + 540,000
               = 690,000 input tokens

By turn 25, a single request carries 6,000 + 24 * 1,800 = 49,200 input tokens. Across all 25 turns, the agent sends 690,000 input tokens and emits 11,250 output tokens.

Now let’s compare three ways to run that 25-turn coding session:

Strategy (25 turns, $3 / $0.30 / $15 tier)Total input tokensCached input tokensOutput tokensTotal session costSavings vs uncached
Uncached (0% cache hit)690,000011,250$2.2388baseline
Stable prefix (88% cached)690,000601,92011,250$0.6136-72.6%
Cached + compact at turn 13435,200377,69611,250$0.4546-79.7%

Where do the dollars go in each row?

In the uncached run, input tokens cost $2.0700 (690,000 * $3 / 1M) and output tokens cost $0.1688 (11,250 * $15 / 1M), for a total of $2.2388. Even though output costs 5x more per token, output made up less than 8% of the bill because re-sending input history dominated everything.

With a stable append-only prefix hitting 88% cache reuse after turn 1, 601,920 input tokens drop from $3.00 to $0.30 per million ($0.1806). Add 88,080 fresh input tokens ($0.2642) and $0.1688 of output, and the bill falls to $0.6136, a 72.6% cut without dropping any context.

In the third row, compaction kicks in at turn 13 right as the working context would reach 27,600 tokens. The harness replaces raw logs from turns 1 through 12 with a 2,000-token structured handoff summary.

That resets turn 13 down to 8,000 tokens (the 6,000-token static prefix plus the 2,000-token summary), so turns 13 through 25 grow from 8,000 to 29,600 tokens instead of climbing to 49,200.

Even after paying a one-turn cache miss on the new summary, cumulative input drops from 690,000 to 435,200 tokens (with 377,696 cached). Total spend lands at $0.4546, which is 79.7% cheaper than uncached and 25.9% cheaper than caching alone.

Here is how the 8-turn live cache hit rate and the 25-turn quadratic cost curve look plotted together:

Side-by-side chart of the live 8-turn cache hit rate and the 25-turn coding agent quadratic cost model

Now see how fast that curve takes off if the session runs to 50 turns with the same parameters ($P_0 = 6,000$, $\Delta = 1,800$, 450 output tokens per turn):

TotalInput(50) = 50 * 6,000 + 1,800 * (50 * 49) / 2
               = 300,000 + 2,205,000
               = 2,505,000 input tokens

At uncached Sonnet rates, 50 turns cost $7.5150 in input plus $0.3375 in output, totaling $7.8525 for one session. Doubling the session from 25 turns ($2.2388) to 50 turns ($7.8525) multiplied the bill by 3.51x.

And if verbose test output pushes $\Delta$ from 1,800 to 4,500 tokens per turn, turn 45 crosses 200,000 tokens. That triggers the 2x long-context cliff right on top of the quadratic sum.

You can step through the three cost shapes in this diagram:

1/3Step 1 - Uncached multi-turn quadratic growth
Step 1 - Uncached multi-turn quadratic growthWithout caching, every agent turn re-sends the system prompt and prior turns at full input rate, reaching 690,000 input tokens and $2.2388 across 25 turns.Turn 1: 6,000 in(full rate)Turn 13: 27,600 in(full rate)Turn 25: 49,200 in(full rate)25-turn total:690,000 in = $2.2388
2/3Step 2 - Stable prefix with prompt caching
Step 2 - Stable prefix with prompt cachingWith an append-only prefix, 601,920 of the 690,000 input tokens hit the 90% cache discount, cutting the 25-turn bill from $2.2388 to $0.6136.Turn 1: 6,000 in(cache seed)Turns 2 to 25:append only601,920 cached at$0.30/1M + 88,080fresh25-turn total:690,000 in = $0.6136(-72.6%)
3/3Step 3 - Caching plus compaction at turn 13
Step 3 - Caching plus compaction at turn 13Compacting conversation history at turn 13 resets input from 27,600 tokens down to 8,000 tokens, lowering total input to 435,200 tokens and $0.4546.Turns 1 to 12:cached growth(190,800 in)Turn 13: compacthistory to 8,000tokensTurns 13 to 25:cached growth(244,400 in)25-turn total:435,200 in = $0.4546(-79.7%)

Scale that single-session gap to a team of ten developers each running fifteen 25-turn coding sessions a day. Uncached runs cost $335 per day, while cached-plus-compacted runs cost $68 per day.

That saves over $5,800 a month on the same model just by keeping prefixes stable and compacting mid-session.

Live experiment: how one timestamp destroys prompt caching

Seeing cache math in a table is useful, and watching one tiny line of code erase 80% of cache hits on a live API makes the bug hard to forget.

I ran two 8-turn conversations against OpenAI’s live gpt-4.1-mini API. Both used docs/blog-post-guide.md from this repository as the system prompt (~2,072 initial tokens, well above OpenAI’s 1,024-token cache threshold).

Both runs asked the same 8 questions in sequence and appended each assistant reply to the conversation history before the next turn. Only one line changed between them.

In the stable run, the system prompt stayed byte-for-byte identical across all 8 turns. In the broken run, line 1 of the system prompt prepended a live timestamp (Current time: ${new Date().toISOString()}), a pattern you see all the time in agent starter kits and chat backends.

Here are the token counts and latencies the API returned on every turn:

TurnStable inStable cachedStable msBroken inBroken cachedBroken msCompletion tokens (stable / broken)
12,07207622,097086322 / 22
22,1131,9201,4682,138073228 / 28
32,1611,9206652,186084532 / 31
42,2102,0487332,234088633 / 36
52,2582,0487352,285084927 / 29
62,3032,0487112,332066828 / 25
72,3482,1767342,374083137 / 37
82,4042,1766642,43001,76025 / 25
Total17,86914,336 (80.2%)18,0760 (0%)232 / 233

Look closely at the Stable cached column: 0, 1,920, 1,920, 2,048, 2,048, 2,048, 2,176, 2,176.

Those numbers show OpenAI’s 128-token cache block granularity right in the telemetry:

  • 1,920 = 15 * 128
  • 2,048 = 16 * 128
  • 2,176 = 17 * 128

On turn 1, the request sends 2,072 input tokens, so OpenAI caches the first 15 complete 128-token blocks (1,920 tokens). On turn 2, the prompt grows to 2,113 tokens, and all 1,920 cached tokens hit right away.

Turn 3 brings the prompt to 2,161 tokens, crossing the next 128-token boundary above 2,048. By turn 4, cached tokens step up to 2,048, and by turn 7 they step up again to 2,176.

Now compare that with the broken run. Prepending that ISO timestamp added just 25 tokens to turn 1, and only 207 extra prompt tokens across all 8 turns (1.16% more text).

Because that timestamp sat at token position 1, the prefix hash mismatched before the very first 128-token block on every call. Cached tokens collapsed from 14,336 to 0.

Latency tells a subtler story here. On small 2,000-token prompts, network jitter dominates single-turn timings (664 ms to 1,468 ms stable versus 668 ms to 1,760 ms broken).

Once prompts reach 30,000 to 150,000 tokens in real coding agents, cached prefill also cuts time-to-first-token noticeably because the GPU skips recomputing attention over the saved prefix.

Here is the terminal output from running my experiment script:

Terminal output of the live 8-turn gpt-4.1-mini prompt cache experiment and 25-turn agent cost model

Let’s price both runs on gpt-4.1-mini ($0.40 input, $0.10 cached input, $1.60 output):

  • The stable run paid $0.001413 for 3,533 uncached input tokens, $0.001434 for 14,336 cached input tokens, and $0.000371 for 232 completion tokens, totaling $0.003218.
  • The broken run paid $0.007230 for 18,076 uncached input tokens, $0.000000 for cached input, and $0.000373 for 233 completion tokens, totaling $0.007603.

That single line of code made the identical 8-turn conversation 2.36x more expensive. Priced at gpt-4.1 rates ($2.00 / $0.50 / $8.00), the same 8 turns jump from $0.01609 to $0.038016, also 2.36x.

On a longer 25-turn session with Sonnet’s 90% cache discount, breaking line 1 pushes the cost penalty past 3.6x.

Fixing the prompt ordering bug

To keep prefix caching alive, we want to structure every prompt from most static at the top to most dynamic at the bottom:

  1. System instructions and fixed tool schemas first.
  2. Long-lived reference documents second.
  3. Append-only conversation history third.
  4. Per-turn dynamic metadata inside the latest user message.

Never interpolate per-request values into the system prompt. Here is the broken pattern next to the cache-friendly version in JavaScript:

// Broken: mutating line 1 invalidates the entire prefix on every turn.
function buildBrokenMessages(guideText, history, userQuestion) {
  return [
    {
      role: 'system',
      content: `Current time: ${new Date().toISOString()}\n\n${guideText}`,
    },
    ...history,
    { role: 'user', content: userQuestion },
  ]
}

// Fixed: system prompt stays byte-for-byte identical; dynamic clock goes last.
function buildCachedMessages(guideText, history, userQuestion) {
  const now = new Date().toISOString()
  return [
    {
      role: 'system',
      content: guideText,
    },
    ...history,
    {
      role: 'user',
      content: `[timestamp: ${now}]\n${userQuestion}`,
    },
  ]
}

If the model only needs today’s calendar date rather than the exact second, a date string like 2026-11-24 stays identical for 24 hours instead of changing every turn.

Common silent cache breakers to audit in your codebase

A live timestamp is only the most obvious culprit. Whenever a multi-turn app logs a cache hit rate below 70%, I check the request builder for these five bugs:

  • Per-request IDs or counters (request_id, trace_id, turn_number, or user credit balance) interpolated near the top of the system prompt.
  • Nondeterministic tool schema serialization, where JSON object keys come out in a different order across requests or worker restarts. Sorting keys once at startup and freezing the tool array prevents this.
  • Adding or removing tools mid-conversation, such as injecting a deploy tool only after turn 5. Most APIs place tool schemas at the very start of the prompt, so changing the tool list busts the cache for every message after it.
  • Putting retrieved RAG snippets into the system prompt on every turn instead of attaching them to the user message that triggered the search.
  • Sliding-window history trimming that drops the oldest message on every turn. Shifting the front of the message array invalidates every token behind it on every call. Append messages unchanged until a planned compaction threshold, then compact in one clean step.

Pre-flight token counting vs authoritative API usage

Enforcing a hard dollar budget in code runs into an awkward timing problem. We have to decide whether to allow a request before sending it, yet we only learn the exact billed token count after the provider replies.

Many apps reach for Math.ceil(text.length / 4). That rough guess works fine for a casual character meter in a UI, and it fails badly as a financial control.

Suppose a user pastes a 40 KB minified JSON export or a block of Japanese documentation. Dividing characters by 4 predicts roughly 10,000 tokens, while the real BPE tokenizer can easily produce 18,000 to 25,000 tokens.

On top of that, chars / 4 misses tool schemas, image tiles, hidden chat-template wrapper tokens, and reasoning tokens generated during decode.

Even an exact local tokenizer only gets us halfway there. Before the model finishes generating, no local library knows how many output or hidden reasoning tokens will come back, or whether peak cluster load evicted your cached prefix early.

To handle both sides safely, production budgeting splits the job into two steps:

  1. Pessimistic pre-flight reservation: Before calling the API, estimate input tokens with a local tokenizer, the provider’s /count_tokens endpoint on huge prompts, or chars / 2.8 plus fixed schema overhead for zero native dependencies. Price that input assuming a 0% cache hit (using the uncached or cache-write rate), add max_completion_tokens at the full output rate, and lock that worst-case hold against the session and user budget.
  2. Authoritative reconciliation: As soon as the response returns, read the provider’s usage object, calculate the exact cost from your rate card, drop the temporary hold, and write the real dollar amount to your ledger.

Avoiding the cached-token double-counting bug

OpenAI and Anthropic structure their usage objects in opposite ways. If your app supports both providers, that difference can quietly corrupt your accounting.

In OpenAI’s Chat Completions API (and Responses API), prompt_tokens (or input_tokens) already includes cached_tokens:

{
  "prompt_tokens": 2210,
  "completion_tokens": 33,
  "prompt_tokens_details": {
    "cached_tokens": 2048
  },
  "completion_tokens_details": {
    "reasoning_tokens": 0
  }
}

To price that OpenAI response accurately, we subtract cached_tokens from prompt_tokens (2210 - 2048 = 162). Then we bill 162 at the uncached input rate and 2048 at the cached rate.

If you bill 2210 at full input and also add 2048 at the cached rate, you double-count the cached prefix. The same rule applies to completion_tokens, which already includes reasoning_tokens, so we bill completion_tokens once at the output rate.

Anthropic reports its input buckets the opposite way. In Anthropic’s Messages API, input_tokens counts only the uncached, non-written tokens:

{
  "input_tokens": 162,
  "cache_creation_input_tokens": 0,
  "cache_read_input_tokens": 2048,
  "output_tokens": 33
}

Here, the three input fields add up to the full prompt (162 + 0 + 2048 = 2,210). We multiply input_tokens by the base input rate, cache_creation_input_tokens by the cache write rate (1.25x for a 5-minute TTL, or 2x for a 1-hour TTL), and cache_read_input_tokens by the cache read rate (0.10x).

Running OpenAI’s subtraction formula on an Anthropic response would give you -1,886 tokens.

Normalizing every provider response into one internal shape (uncachedInput, cachedInput, cacheWriteInput, output) inside a single tested helper eliminates this bug for good.

Streaming aborts and integer microdollars

Two real-world edge cases show up as soon as a budget ledger handles live traffic.

The first is streaming interruptions. On OpenAI streaming calls, always pass stream_options: { include_usage: true } so the final Server-Sent Events (SSE) chunk includes the authoritative usage object (Anthropic emits usage across message_start and message_delta events automatically).

What happens if a client drops the connection halfway through a stream, or an HTTP timeout fires after the request reached the provider? You still get billed for prefill plus whatever tokens were generated before the abort.

If we release the entire reservation as $0, a flaky or malicious client can bypass our daily cap by closing the connection right before the final chunk.

My rule is straightforward: if the error happens before HTTP response headers arrive (DNS failure, connection refused, or a 400 validation error), release the reservation. If a stream aborts mid-body, charge a conservative fallback (such as the uncached input estimate plus any received chunk tokens) until you reconcile with provider billing exports.

The second edge case is floating-point drift. When persisting ledger totals to SQLite, Postgres, or Redis, store them as integer microdollars (1 USD = 1,000,000 microdollars, or 10,000,000 tenths of a microdollar).

Adding up 50,000 calls that each cost $0.000142 with standard IEEE-754 floating-point numbers builds up rounding noise over time. Integer math stays exact and pairs cleanly with atomic database updates like UPDATE budgets SET spent_micros = spent_micros + ? WHERE spent_micros + ? <= cap_micros.

Building hard runtime spend controls (BudgetGuard)

No single layer catches every kind of cost overrun. Prompt hygiene reduces average spend per turn, application guards enforce per-session and per-user caps, an AI gateway governs cross-service traffic, and provider account caps act as the last line of defense.

Here is how those four layers divide the work:

LayerWhat it enforcesFailure mode it catchesLimitation
Prompt and harness hygieneConcise instructions, stable prefixes, tool output truncation, scheduled compactionQuadratic transcript bloat and silent cache missesCannot stop an infinite retry loop or abusive user traffic
App-level BudgetGuardPer-request max_completion_tokens, per-session and per-user USD caps, fail-closed circuit breakerStuck agent loops, single-tenant abuse, reasoning-token spikesOnly sees requests flowing through your own application code
AI Gateway (such as Cloudflare AI Gateway)Cross-service rate limits, centralized logs, response caching, key isolationMisconfigured microservices, retry storms, leaked frontend endpointsUsually meters request or token counts rather than per-session USD business rules
Provider console limitsMonthly hard spend caps, workspace budgets, email or webhook alertsCatastrophic bug or stolen key draining your credit cardCoarse blast radius; hitting the cap halts production for every customer

Most teams configure the provider’s monthly cap and stop there. A $500 monthly ceiling prevents a $50,000 disaster, yet it still lets one stuck background agent at 3 a.m. burn all $500 and knock every paying customer offline before anyone wakes up.

An application-level BudgetGuard closes that gap. Let’s trace the full request lifecycle before looking at the code:

BudgetGuard pre-flight reservation and reconciliation flowEach LLM call checks the circuit breaker, reserves worst-case cost against session, user, and global caps before hitting the API, then reconciles actual spend from authoritative usage fields.YesNoNoYesNoYesYesNoIncoming model callCircuit breakeropen?Reject immediately(fail closed)Compute worst-casereservationWithin session,user, and globalcaps?Record rejection andcheck breakerLock reservation andenforcemax_completion_tokensCall provider APIAPI succeeded?Release or chargeabort fallbackNormalize usage andcompute exact USDReplace reservationwith actual spendSoft threshold oranomaly hit?Emit alert webhookReturn response

Three design choices make this guard hold up under real traffic.

First, atomic pre-flight reservation prevents concurrent overspend. Suppose an agent spawns four parallel tool calls in the same millisecond when only $0.10 remains in the session budget.

If we only check settled spend, all four calls start together and burn $0.40. Reserving each call’s worst-case cost synchronously before await fetch(...) ensures every parallel call sees the pending holds already in flight.

Second, we enforce max_completion_tokens on every request. Without an output ceiling, a single call to a $25/1M output model with a 64K output limit carries a $1.60 worst-case output liability.

Passing a concrete cap sized to the task keeps reservations tight and stops verbose runaways right at the provider boundary.

Third, the guard fails closed. The circuit breaker trips and blocks all further calls until an operator resets it if any of three conditions hit:

  • Code asks for an unconfigured model with no rate card.
  • Global spend inside a rolling 10-minute window crosses an anomaly ceiling.
  • A tight retry loop triggers repeated budget rejections in a row.

Here is the complete, dependency-free Node.js BudgetGuard module I built using integer microdollars internally. It handles both OpenAI and Anthropic usage shapes, long-context surcharge cliffs, soft warning alerts, and circuit breaking:

// budget-guard.mjs
// Hard runtime spend controls for LLM apps and coding agents.

const MICROS_PER_USD = 1_000_000

const toMicros = (usd) => Math.round(usd * MICROS_PER_USD)
const fromMicros = (micros) => Number((micros / MICROS_PER_USD).toFixed(6))

export const RATE_CARDS = {
  'gpt-4.1-mini': {
    provider: 'openai',
    input: 0.4,
    cachedInput: 0.1,
    cacheWriteInput: 0.4,
    output: 1.6,
    longContextThreshold: null,
    longContextInputMultiplier: 1,
    longContextOutputMultiplier: 1,
  },
  'gpt-4.1': {
    provider: 'openai',
    input: 2.0,
    cachedInput: 0.5,
    cacheWriteInput: 2.0,
    output: 8.0,
    longContextThreshold: null,
    longContextInputMultiplier: 1,
    longContextOutputMultiplier: 1,
  },
  'claude-sonnet-4-5': {
    provider: 'anthropic',
    input: 3.0,
    cachedInput: 0.3,
    cacheWriteInput: 3.75,
    output: 15.0,
    longContextThreshold: 200_000,
    longContextInputMultiplier: 2,
    longContextOutputMultiplier: 1.5,
  },
  'claude-opus-4-5': {
    provider: 'anthropic',
    input: 5.0,
    cachedInput: 0.5,
    cacheWriteInput: 6.25,
    output: 25.0,
    longContextThreshold: 200_000,
    longContextInputMultiplier: 2,
    longContextOutputMultiplier: 1.5,
  },
}

export class BudgetExceededError extends Error {
  constructor(reason, details = {}) {
    super(reason)
    this.name = 'BudgetExceededError'
    this.details = details
  }
}

export function normalizeUsage(provider, rawUsage) {
  if (!rawUsage || typeof rawUsage !== 'object') {
    throw new Error('Missing authoritative usage object from provider response')
  }

  if (provider === 'openai') {
    const promptTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? 0
    const cachedInput =
      rawUsage.prompt_tokens_details?.cached_tokens ??
      rawUsage.input_tokens_details?.cached_tokens ??
      0
    const output = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? 0
    const uncachedInput = Math.max(0, promptTokens - cachedInput)

    return {
      totalInput: promptTokens,
      uncachedInput,
      cachedInput,
      cacheWriteInput: 0,
      output,
    }
  }

  if (provider === 'anthropic') {
    const uncachedInput = rawUsage.input_tokens ?? 0
    const cacheWriteInput = rawUsage.cache_creation_input_tokens ?? 0
    const cachedInput = rawUsage.cache_read_input_tokens ?? 0
    const output = rawUsage.output_tokens ?? 0

    return {
      totalInput: uncachedInput + cacheWriteInput + cachedInput,
      uncachedInput,
      cachedInput,
      cacheWriteInput,
      output,
    }
  }

  throw new Error(`Unsupported provider for usage normalization: ${provider}`)
}

export function calculateCostMicros(model, normalizedUsage, rateCards = RATE_CARDS) {
  const card = rateCards[model]
  if (!card) {
    throw new Error(`No rate card configured for model: ${model}`)
  }

  const isLongContext =
    card.longContextThreshold !== null &&
    normalizedUsage.totalInput > card.longContextThreshold

  const inMult = isLongContext ? card.longContextInputMultiplier : 1
  const outMult = isLongContext ? card.longContextOutputMultiplier : 1

  const inputUsd =
    ((normalizedUsage.uncachedInput * card.input +
      normalizedUsage.cachedInput * card.cachedInput +
      normalizedUsage.cacheWriteInput * card.cacheWriteInput) *
      inMult) /
    1_000_000

  const outputUsd = (normalizedUsage.output * card.output * outMult) / 1_000_000

  return toMicros(inputUsd + outputUsd)
}

export class BudgetGuard {
  constructor(options = {}) {
    this.rateCards = options.rateCards ?? RATE_CARDS
    this.maxRequestMicros = toMicros(options.maxRequestUsd ?? 0.25)
    this.maxSessionMicros = toMicros(options.maxSessionUsd ?? 1.5)
    this.maxUserDailyMicros = toMicros(options.maxUserDailyUsd ?? 10.0)
    this.maxGlobalWindowMicros = toMicros(options.maxGlobalWindowUsd ?? 25.0)
    this.windowMs = options.windowMs ?? 10 * 60 * 1000
    this.defaultMaxCompletionTokens = options.defaultMaxCompletionTokens ?? 2048
    this.softAlertRatio = options.softAlertRatio ?? 0.75
    this.maxConsecutiveRejections = options.maxConsecutiveRejections ?? 5
    this.onAlert = options.onAlert ?? (() => {})

    this.sessionSpend = new Map()
    this.userSpend = new Map()
    this.activeReservations = new Map()
    this.recentEvents = []
    this.alertedSessions = new Set()
    this.consecutiveRejections = 0
    this.circuitOpen = false
    this.circuitReason = null
    this.nextReservationId = 1
  }

  estimateWorstCaseMicros(model, estimatedInputTokens, maxCompletionTokens) {
    const card = this.rateCards[model]
    if (!card) {
      throw new BudgetExceededError(`Refusing unpriced model: ${model}`, { model })
    }

    // Assume 0% cache hit and worst-case write rate for pre-flight safety.
    const worstInputRate = Math.max(card.input, card.cacheWriteInput)
    const isLong =
      card.longContextThreshold !== null &&
      estimatedInputTokens > card.longContextThreshold

    const inMult = isLong ? card.longContextInputMultiplier : 1
    const outMult = isLong ? card.longContextOutputMultiplier : 1

    const worstInputUsd = (estimatedInputTokens * worstInputRate * inMult) / 1_000_000
    const worstOutputUsd = (maxCompletionTokens * card.output * outMult) / 1_000_000

    return toMicros(worstInputUsd + worstOutputUsd)
  }

  _pendingFor(key, field) {
    let total = 0
    for (const res of this.activeReservations.values()) {
      if (res[field] === key) total += res.reservedMicros
    }
    return total
  }

  _globalWindowMicros(now = Date.now()) {
    const cutoff = now - this.windowMs
    this.recentEvents = this.recentEvents.filter((ev) => ev.ts >= cutoff)

    let total = 0
    for (const ev of this.recentEvents) total += ev.micros
    for (const res of this.activeReservations.values()) total += res.reservedMicros
    return total
  }

  _tripCircuit(reason, details) {
    this.circuitOpen = true
    this.circuitReason = reason
    this.onAlert({
      level: 'critical',
      event: 'circuit_breaker_tripped',
      reason,
      details,
    })
  }

  _reject(reason, details) {
    this.consecutiveRejections += 1
    if (this.consecutiveRejections >= this.maxConsecutiveRejections && !this.circuitOpen) {
      this._tripCircuit('Too many consecutive budget rejections', {
        lastReason: reason,
        consecutiveRejections: this.consecutiveRejections,
      })
    }
    throw new BudgetExceededError(reason, details)
  }

  reserve({
    sessionId,
    userId = 'default',
    model,
    estimatedInputTokens,
    maxCompletionTokens = this.defaultMaxCompletionTokens,
  }) {
    if (this.circuitOpen) {
      throw new BudgetExceededError(`Circuit breaker is open: ${this.circuitReason}`, {
        circuitOpen: true,
      })
    }

    if (!Number.isFinite(estimatedInputTokens) || estimatedInputTokens <= 0) {
      this._reject('Invalid estimatedInputTokens', { estimatedInputTokens })
    }

    if (!Number.isFinite(maxCompletionTokens) || maxCompletionTokens <= 0) {
      this._reject('Explicit maxCompletionTokens is required', { maxCompletionTokens })
    }

    const reservedMicros = this.estimateWorstCaseMicros(
      model,
      estimatedInputTokens,
      maxCompletionTokens
    )

    if (reservedMicros > this.maxRequestMicros) {
      this._reject('Request worst-case cost exceeds per-request cap', {
        reservedUsd: fromMicros(reservedMicros),
        maxRequestUsd: fromMicros(this.maxRequestMicros),
      })
    }

    const currentSession =
      (this.sessionSpend.get(sessionId) ?? 0) + this._pendingFor(sessionId, 'sessionId')
    if (currentSession + reservedMicros > this.maxSessionMicros) {
      this._reject('Session spend cap exceeded', {
        sessionId,
        currentSessionUsd: fromMicros(currentSession),
        reservedUsd: fromMicros(reservedMicros),
        maxSessionUsd: fromMicros(this.maxSessionMicros),
      })
    }

    const currentUser =
      (this.userSpend.get(userId) ?? 0) + this._pendingFor(userId, 'userId')
    if (currentUser + reservedMicros > this.maxUserDailyMicros) {
      this._reject('User daily spend cap exceeded', {
        userId,
        currentUserUsd: fromMicros(currentUser),
        reservedUsd: fromMicros(reservedMicros),
        maxUserDailyUsd: fromMicros(this.maxUserDailyMicros),
      })
    }

    const currentGlobal = this._globalWindowMicros()
    if (currentGlobal + reservedMicros > this.maxGlobalWindowMicros) {
      this._tripCircuit('Rolling global spend window exceeded', {
        currentGlobalUsd: fromMicros(currentGlobal),
        reservedUsd: fromMicros(reservedMicros),
        maxGlobalWindowUsd: fromMicros(this.maxGlobalWindowMicros),
      })
      throw new BudgetExceededError('Global rolling spend anomaly cap exceeded', {
        currentGlobalUsd: fromMicros(currentGlobal),
        reservedUsd: fromMicros(reservedMicros),
      })
    }

    this.consecutiveRejections = 0
    const reservationId = `res_${this.nextReservationId++}`
    this.activeReservations.set(reservationId, {
      reservationId,
      sessionId,
      userId,
      model,
      maxCompletionTokens,
      reservedMicros,
      createdAt: Date.now(),
    })

    return {
      reservationId,
      reservedUsd: fromMicros(reservedMicros),
      enforcedParams: {
        max_completion_tokens: maxCompletionTokens,
      },
    }
  }

  reconcile(reservationId, rawUsage) {
    const res = this.activeReservations.get(reservationId)
    if (!res) {
      throw new Error(`Unknown or already settled reservation: ${reservationId}`)
    }
    this.activeReservations.delete(reservationId)

    const card = this.rateCards[res.model]
    const normalized = normalizeUsage(card.provider, rawUsage)
    const actualMicros = calculateCostMicros(res.model, normalized, this.rateCards)

    const nextSession = (this.sessionSpend.get(res.sessionId) ?? 0) + actualMicros
    const nextUser = (this.userSpend.get(res.userId) ?? 0) + actualMicros

    this.sessionSpend.set(res.sessionId, nextSession)
    this.userSpend.set(res.userId, nextUser)
    this.recentEvents.push({ ts: Date.now(), micros: actualMicros, sessionId: res.sessionId })

    if (
      !this.alertedSessions.has(res.sessionId) &&
      nextSession >= Math.floor(this.maxSessionMicros * this.softAlertRatio)
    ) {
      this.alertedSessions.add(res.sessionId)
      this.onAlert({
        level: 'warning',
        event: 'session_soft_threshold',
        sessionId: res.sessionId,
        spentUsd: fromMicros(nextSession),
        capUsd: fromMicros(this.maxSessionMicros),
      })
    }

    return {
      reservationId,
      reservedUsd: fromMicros(res.reservedMicros),
      actualUsd: fromMicros(actualMicros),
      sessionTotalUsd: fromMicros(nextSession),
      usage: normalized,
    }
  }

  release(reservationId, { chargeAbortFallback = false } = {}) {
    const res = this.activeReservations.get(reservationId)
    if (!res) return false
    this.activeReservations.delete(reservationId)

    if (chargeAbortFallback) {
      const nextSession = (this.sessionSpend.get(res.sessionId) ?? 0) + res.reservedMicros
      const nextUser = (this.userSpend.get(res.userId) ?? 0) + res.reservedMicros
      this.sessionSpend.set(res.sessionId, nextSession)
      this.userSpend.set(res.userId, nextUser)
      this.recentEvents.push({
        ts: Date.now(),
        micros: res.reservedMicros,
        sessionId: res.sessionId,
      })
    }

    return true
  }

  resetCircuit() {
    this.circuitOpen = false
    this.circuitReason = null
    this.consecutiveRejections = 0
  }
}

Next, we wrap our provider SDK call so every request reserves budget first, enforces max_completion_tokens, reconciles exact usage on success, and releases or charges the abort fallback on failure:

// guarded-call.mjs
import { BudgetGuard } from './budget-guard.mjs'

const guard = new BudgetGuard({
  maxRequestUsd: 0.15,
  maxSessionUsd: 0.5,
  maxUserDailyUsd: 5.0,
  maxGlobalWindowUsd: 20.0,
  softAlertRatio: 0.75,
  onAlert: (alert) => {
    console.warn('[BUDGET ALERT]', JSON.stringify(alert))
  },
})

export async function runGuardedCompletion({
  sessionId,
  userId,
  model,
  messages,
  maxCompletionTokens = 1024,
  callProvider,
}) {
  // Conservative pre-flight estimate when no local tokenizer is loaded:
  // JSON.stringify accounts for role keys, array brackets, and punctuation.
  const serialized = JSON.stringify(messages)
  const estimatedInputTokens = Math.ceil(serialized.length / 2.8) + 256

  const reservation = guard.reserve({
    sessionId,
    userId,
    model,
    estimatedInputTokens,
    maxCompletionTokens,
  })

  let headersReceived = false
  try {
    const response = await callProvider({
      model,
      messages,
      ...reservation.enforcedParams,
      onHeaders: () => {
        headersReceived = true
      },
    })

    const settlement = guard.reconcile(reservation.reservationId, response.usage)
    return { response, settlement }
  } catch (err) {
    // If the stream dropped after headers arrived, keep the pessimistic charge
    // instead of letting aborted streams bypass the daily cap.
    guard.release(reservation.reservationId, {
      chargeAbortFallback: headersReceived,
    })
    throw err
  }
}

Let’s trace BudgetGuard across a three-turn Sonnet session with maxSessionUsd: 0.09 to see how pessimistic reservation and exact reconciliation work together:

  1. Turn 1 (estimatedInputTokens = 8,000, maxCompletionTokens = 1,000): reserve() locks a worst-case $0.0450 (8,000 * $3.75 / 1M + 1,000 * $15 / 1M). The call returns with 7,500 cache-write tokens and 400 output tokens, so reconcile() replaces the $0.0450 hold with the exact $0.034125 spend.
  2. Turn 2 (estimatedInputTokens = 10,000, maxCompletionTokens = 1,000): reserve() checks $0.034125 + $0.0525 = $0.086625 <= $0.09 and permits the call. Since 7,500 tokens hit the cache read rate ($0.30/1M), real spend comes back at $0.01575, bringing settled session spend to $0.049875.
  3. Turn 3 (estimatedInputTokens = 12,000, maxCompletionTokens = 1,000): reserve() computes a worst-case $0.0600. Because $0.049875 + $0.0600 = $0.109875 > $0.09, BudgetGuard throws BudgetExceededError before touching the network, letting your agent harness hand back the partial result cleanly.

If you run across multiple Node.js instances or serverless workers behind a load balancer, keep this reserve / reconcile / release interface and move the maps into Redis or Postgres. Adding a short reservation_expires_at timestamp (say 120 seconds) ensures a crashed worker never leaks locked budget.

Model routing tradeoffs: when cheaper models cost more

After seeing a big API bill, model routing is usually the first optimization developers try. You send simple work to a $0.40/1M model like gpt-4.1-mini and save the $3.00/1M or $5.00/1M frontier model for hard reasoning.

Used in the right places, routing cuts bills by 70% to 85%. Used carelessly inside a live multi-turn conversation, it can cost more than staying on the expensive model.

Everything depends on whether the routed call shares a warm prefix cache with the main session.

Where model routing saves real money

Routing pays off right away on stateless tasks and context-isolated subagents where the cheaper model does not need a 40,000-token transcript:

  • Triaging incoming webhooks, emails, or support tickets into a small enum before deciding whether to invoke an expensive agent.
  • Generating conversation titles, pull-request summaries, or changelog tags from a standalone diff.
  • Running a read-only research subagent that greps a repository, reads six candidate files, and hands back a 300-token summary. Because it runs in a disposable context window, it keeps 25,000 tokens of raw search output out of the frontier model’s quadratic loop.
  • Extracting structured JSON fields from a single document where gpt-4.1-mini matches gpt-4.1 accuracy at one-fifth the token price.

In all of these cases, the smaller model works on a self-contained input. Our frontier model keeps its warm cache untouched, and its own transcript stays shorter too.

Where mid-session routing backfires

Now let’s trace what happens when a harness swaps models mid-stream inside an active coding conversation.

Suppose we are at turn 14 on Claude Sonnet 4.5 ($3.00 input, $0.30 cached input, $15.00 output) with a warm 32,000-token prefix. Turn 15 looks like an easy follow-up adding 1,500 tokens of tool output and expecting 300 output tokens.

Compare staying on warm Sonnet against bouncing turn 15 to gpt-4.1-mini and returning to Sonnet on turn 16:

  • Stay on warm Sonnet: turn 15 costs $0.0096 for 32,000 cached tokens, $0.0045 for 1,500 fresh input tokens, and $0.0045 for 300 output tokens, totaling $0.0186.
  • Route turn 15 to gpt-4.1-mini: sending the full 33,500-token transcript to a cold cache at $0.40/1M costs $0.0134 in input plus $0.0005 in output, totaling $0.0139. We saved $0.0047, less than half a cent.
  • Return to Sonnet on turn 16: if Sonnet’s 5-minute TTL expired, or if slightly different tool-call formatting shifted the prefix, turn 16 pays a cold cache write on 35,000 tokens ($0.1313 instead of $0.0105). Chasing $0.0047 just triggered a $0.1208 cache penalty.

Even if the cache stayed warm, one shaky tool call from the smaller model on turn 15 forces a corrective turn on the frontier model on turn 16. That single retry wipes out the savings of ten routed turns.

Here is a decision tree to check whether routing pays off for a given step:

Decision tree for model routing vs warm prefix cachingRoute to a cheaper model for stateless tasks, isolated subagents, or session start triage; stay on the warm frontier model inside an active multi-turn transcript.No (isolated input)YesNoYes (mid-session turn)YesNo (fresh or compacted)YesNoPick model for nextstepNeeds full activetranscript?Can small model hittarget accuracy?Route to cheap modelUse frontier modelIs frontier prefixcache warm?Stay on warmfrontier modelSimple triage beforemain work?

Route across task boundaries and isolated subagents, not between adjacent turns of a warm conversation.

How I budget LLM spend

My own LLM spend falls into two completely separate buckets with different threat models: public apps serving untrusted user traffic, and personal coding-agent workflows.

Apps with untrusted user traffic

When anyone on the internet can hit an endpoint backed by your API key, average user behavior stops being the main risk. A bug or a bot pasting a 100 KB log dump twenty times matters far more.

Before I launch a user-facing app, I put four guardrails in place:

  • I set an explicit max_completion_tokens on every route sized to the UI slot. A route that renders a short summary card gets a 300 or 500 token cap, never an open-ended default.
  • I enforce per-user daily dollar limits through a BudgetGuard-style ledger, plus a hard raw-byte check on user input before JSON serialization so nobody can push a megabyte of text into a chat handler.
  • I proxy calls through Cloudflare AI Gateway so rate limits, request telemetry, and an emergency kill switch live outside application deploys.
  • I cap the provider account itself with a hard monthly ceiling low enough that a worst-case bug hurts nobody, with alerts at 50% and 80%.

During the first week of live traffic, I also check the real cached_tokens / prompt_tokens ratio in logs. If multi-turn flows sit below 60% cache hits, something in the prefix is mutating, and I fix that before scaling up users.

Personal coding-agent sessions

For daily coding inside an interactive agent, subscription pricing wins by a wide margin. As I measured in my Codex API vs subscription breakdown and my look at desktop AI costs, a $100 to $200 monthly plan covers $700+ of API-equivalent usage when you code with an agent every day.

The flat plan absorbs the $195 heavy days without throwing surprise invoices.

Where I still use API keys directly is bursty automation: headless CI scripts, offline evals, and custom CLI tools. For those workflows, I stick to four habits:

  • I scope each agent session to one task. Opening a fresh session with a short written handoff beats dragging a 250K-token transcript across unrelated features and triggering long-context surcharges.
  • I compact proactively around turn 12 to 15 on heavy tool loops instead of waiting until the window nears 90% full. As our 25-turn simulation showed, compacting at turn 13 cut cumulative input by 37% and shaved another 26% off total cost beyond prompt caching.
  • I route offline evals and archive backfills through the Batch API for the automatic 50% discount whenever waiting an hour changes nothing.
  • I pass an explicit dollar cap (like --max-budget-usd or a BudgetGuard wrapper) to every unattended script, so an agent stuck on a flaky test stops cleanly at $1.00 instead of burning credits until morning.

When heavy budgeting machinery is overkill

Not every project needs a distributed Redis microdollar ledger, model routing, and custom tokenizers.

If you run a tiny internal script five times a day on gpt-4.1-mini for $3 a month, spending an afternoon building dynamic routing and reservation tables slows you down for pennies. In that case, I’d create a dedicated API key with a $20 monthly cap, set max_completion_tokens, keep the system prompt static so automatic caching works out of the box, and move on.

The full BudgetGuard circuit breaker earns its keep when:

  • External users can trigger model calls.
  • An autonomous agent loop runs without a human watching each turn.
  • A single bad session on a frontier model can blow past $5 to $10.

Once any of those apply, a hundred lines of pessimistic reservation and authoritative reconciliation code pays for itself the very first night a loop gets stuck.

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

Related posts about ai: