I checked one month of my cloud inference bill across five production AI services. 78% of the money paid for waste. I sent the same System prompt Fixed instructions at the start of every request. They tell the model its role and its rules. again on every call. I kept old conversation history that the model did not need. I sent simple classification tasks to Frontier model The largest, most capable and most expensive tier of models. I keep it for the hardest reasoning. reasoning models, the most expensive kind. Developer guides teach caching and short prompts. Those habits lower my cost while I build. They cannot save me from financial ruin when live production traffic spikes. For that, my live apps need defense in code that acts the same way every time.
In 11 Principles of AI Tokenomics, Alex Astrum and Luke Schlangen set the baseline for how a developer saves Token A small piece of text, often part of a word. Models read, write and bill text by the token.. My apps grow to thousands of users at the same time. At that scale, prompt discipline alone fails. It cannot stop runaway loops, bot scraping, or bursts from clients that nobody meters. My live runtimes need hardware Attestation Proof, signed by the device or platform, that a request comes from my real app and not from a script., atomic Token bucket A per user allowance that refills at a steady rate. Each request spends from it, and an empty bucket refuses. and hard Circuit breaker Code that stops further calls once a limit is crossed, until a person or a timer resets it. in the app.
Developer discipline: Where prompt tokenomics excels
The original eleven principles are good at one job. They cut waste while I write prompts and call models:
Model sizing and prompt caching
I use light models for simple, frequent work: classification, pulling structured JSON out of text, and checking tool calls. I keep heavy reasoning models for the final answer. My large prompt templates use context caching on Gemini Enterprise Agent Platform (formerly Vertex AI). That cuts my input token cost by up to 90%.
Subagent delegation and session brevity
I hand repetitive, token-heavy data work to specialized Subagent A helper agent that a main agent starts to do one part of a job, often in parallel with others.. I also prune conversation history hard. I do not pass the whole multi-turn chat to every later model call in my system.
I pay for every token of dead history I resend. The model's Attention The step where a model compares each token with the tokens before it to decide what matters. work grows even faster. Each new token looks back at every token before it, so the attention grid grows with tokens times tokens. Four tokens make a 4 × 4 grid of 16 cells. Eight tokens make an 8 × 8 grid of 64 cells. The lab below starts from a clean context of 2,048 tokens. One button adds an unpruned tool trace of 8,192 dead tokens, 10,240 in all. That is 5 times the tokens and 25 times the grid. The pruner drops the dead branch, and the grid shrinks back. Its timer measures a real, scaled-down attention pass on the CPU of the device you read this on.
Each token looks back at every earlier one
Twice the tokens, four times the grid
A dead tool trace grows the grid 25×
Prune it, and the grid shrinks back
Add an unpruned 8,192-token tool trace or a retry loop to a 2,048-token context, watch the causal attention grid grow with tokens times tokens, then prune it back.
Interactive simulator: The 80/20 tier-routing principle
In production, I never send 100% of traffic to expensive frontier models. A smart gateway sends 80% of routine traffic to Gemini 3.6 Flash and 20% of complex turns to Gemini 3.1 Pro. That cuts my cost by 50%, with the same reasoning quality.
Here are the numbers behind the 50%. My gateway benchmark sends 250,000 requests a month, at about 1,500 input tokens each. That is 375M tokens. On the frontier tier at $2.00 per 1M, the month costs $750. If I route 80% to the fast serverless tier, at its $0.75 promotional input rate, the blended rate drops to $1.00 per 1M. The month then costs $375.00.
A context cache goes further. Say 1,000 of the 1,500 tokens are the shared system prompt, and every request hits the cache. That prefix then bills at the cached rate: $0.075 on the fast tier and $0.20 on the frontier tier. The blend falls to $0.40 per 1M, and the month costs $150.00 before cache storage fees.
80/20 tier-routing blend vs. 100% frontier model
Get the next essay by email
One email per new essay: a production failure, taken apart, and the code that fixed it. Reply to any of them to unsubscribe.
Runtime defense: Why code-level guardrails are mandatory
The circuit breaker below uses small numbers on purpose. My budget is $2.00. One call without the cache costs $0.10. At a 50% cache hit rate, the call costs $0.05. The agent must reconcile 500 invoices through a vendor API. The API keeps returning 500 errors. With discipline only, the agent retries 120 times. It spends $6.00, three times the budget, and reconciles zero invoices. Caching halved the price of each call. It did nothing about the number of calls. With the guard on, the idempotency key for invoice 4417 repeats on call 25. The breaker rejects that call before the model runs. Spend stops at $1.20, after 24 billed calls.
Discipline alone cannot stop an autonomous loop: fire unbounded tool retries at a budget and watch the idempotency guard trip before the bill does.
A failing API, a $2.00 budget
No guard: 120 retries spend $6.00
The guard stops the loop at $1.20
- Prompt discipline and model selection. Trims my prompt tokens, uses context caching, hands tasks to subagents, and keeps conversation sessions short.
- Deterministic request protection. Guards every inference call with a per-user idempotency key in Cloud Firestore. When a failed key repeats, it opens the breaker before the LLM runs.
- Native service spend cap. A Google Cloud spend cap on the Gemini API in this one project pauses that service if the rate limiters and app quotas in front of it fail. It is not a hard limit: it trips minutes late, and the overage is still billed.
Production idempotency guard in TypeScript
A network retry can call the LLM twice for one request, and I pay for the tokens twice. To stop that, I claim each user's idempotency key in a Cloud Firestore transaction before the model runs. The pattern follows the IETF Idempotency-Key HTTP Header draft:
// Claim the key in a short Firestore transaction, then bill the model call once per claim
import { getApps, initializeApp } from "firebase-admin/app";
import { getFirestore, Timestamp } from "firebase-admin/firestore";
import { createHash, randomUUID } from "node:crypto";
const LEASE_MS = 120_000; // longer than the model call's own timeout, or a retry after it bills twice
const sha256 = (s: string) => createHash("sha256").update(s).digest("hex");
export class GuardRejection extends Error {}
export async function executeIdempotentInference(
uid: string, // from the verified ID token, never from the request body
idempotencyKey: string,
requestBody: string,
inferenceFn: () => Promise<string>
): Promise<string> {
if (!getApps().length) initializeApp(); // here, not at import, so the entry file can initialize first
const db = getFirestore();
const claim = randomUUID(); // fences this call's late writes
const ref = db.collection("inference_idempotency").doc(sha256(`${uid}:${idempotencyKey}`));
const requestHash = sha256(requestBody);
// Firestore may re-run this callback, so it only reads and writes documents
const cached = await db.runTransaction(async (tx) => {
const prior = (await tx.get(ref)).data();
if (prior) {
if (prior.requestHash !== requestHash) throw new GuardRejection("Key reused with a different body"); // 422
if (prior.status === "done") return prior.result as string;
if (prior.status === "failed") throw new GuardRejection("Failed key repeated: breaker open");
if (prior.leaseUntil.toMillis() > Date.now()) throw new GuardRejection("Request in flight"); // 409
}
tx.set(ref, {
requestHash,
claim,
status: "pending",
leaseUntil: Timestamp.fromMillis(Date.now() + LEASE_MS),
expireAt: Timestamp.fromMillis(Date.now() + 86_400_000), // TTL policy field
});
return null;
});
if (cached !== null) return cached;
// Fenced write: a call that outlived its lease must not overwrite a newer claim
const settle = (fields: { status: string; result?: string }) =>
db.runTransaction(async (tx) => {
if ((await tx.get(ref)).get("claim") === claim) tx.update(ref, fields);
});
let result: string;
try {
result = await inferenceFn(); // outside the transaction: one bill per claim
} catch (err) {
await settle({ status: "failed" }); // the next call with this key opens the breaker
throw err;
}
await settle({ status: "done", result }); // outside the try: a billed result is never marked failed
return result;
}The guard costs one document read per request. A key seen for the first time adds a second read and two writes. The first write is the claim. The second is the result, and it lands only if the claim token still matches. That cost is fixed per request and does not grow with prompt size. The duplicate frontier call it prevents does grow: it bills 1,500 tokens every time a client retries.
Industry validation and benchmarks
- Same Request, Different Answer: Quantization Amplifies Cache-Induced Divergence in LLM Serving (Sep 2026): Confirms the exact KV-cache reuse mechanics and token cost reductions achieved by prefix context caching in production serving pipelines.
- Beyond Code Generation: Reliability, Verification, and Cost Economics in the Agentic Software Development Lifecycle (Sep 2026): Establishes empirical unit-economic models for balancing frontier reasoning tokens against deterministic verification passes.
- IETF HTTP Working Group: The Idempotency-Key HTTP Header Field Specification
- Alex Astrum and Luke Schlangen: 11 Principles of AI Tokenomics (Google Cloud)
- Gemini Enterprise Agent Platform (formerly Vertex AI): Context Caching Architecture and TTL Management
- Cloud Firestore Transactions and Concurrency Control