GEMINI LABJP
SPARK — Gemini Spark, Google's agentic assistant, arrives in the Gemini app for macOS and works on tasks on your behalfBRIEF — Daily Brief, powered by Personal Intelligence, distills priorities from Gmail and Calendar with suggested next stepsMODEL — Gemini 3.5 Flash reaches GA, offering faster, lower-cost AI with a 1M-token context windowGROWTH — The Gemini app has passed 900 million monthly active users, up from 400 million a year earlierAPPS — Spark now connects to Google Tasks and Google Keep and stays up to date on topics in real timeENTERPRISE — Gemini 3.5 Flash is generally available across the Global, US, and EU regions on Gemini EnterpriseSPARK — Gemini Spark, Google's agentic assistant, arrives in the Gemini app for macOS and works on tasks on your behalfBRIEF — Daily Brief, powered by Personal Intelligence, distills priorities from Gmail and Calendar with suggested next stepsMODEL — Gemini 3.5 Flash reaches GA, offering faster, lower-cost AI with a 1M-token context windowGROWTH — The Gemini app has passed 900 million monthly active users, up from 400 million a year earlierAPPS — Spark now connects to Google Tasks and Google Keep and stays up to date on topics in real timeENTERPRISE — Gemini 3.5 Flash is generally available across the Global, US, and EU regions on Gemini Enterprise
Articles/API / SDK
API / SDK/2026-07-08Intermediate

When My Paid Gemini Chat Bill Came in at Double the Estimate — Field Notes on Per-Request Token Accounting to Plug the Cost Leaks

From a real overrun where my paid Gemini chat SaaS bill nearly doubled the estimate, here is how I logged token usage per request, traced where cost was leaking, and plugged three specific gaps. Recording usage_metadata and reconciling it against the invoice is the starting point.

Gemini 2.5 Pro17Gemini API173cost management2usage_metadata2SaaS operations

Premium Article

I opened the Gemini invoice on the first of the month and just stared at it for a while. My estimate had put it around $60. The actual number was $128. Nearly double.

Usage had grown exactly as expected. I checked the price table several times. Still it did not add up.

The culprit was not the unit price. It was that I had trusted my paper assumption of "what one request costs" instead of measuring it. When you run a small paid chat service as an indie developer, that gap quietly eats your margin.

This is a record of making that gap visible through per-request token accounting, finding three places where cost was leaking, and plugging them.

Face the gap with numbers, not feelings

The first thing I did was stop reasoning by intuition.

Every Gemini API response includes usageMetadata, carrying promptTokenCount (input), candidatesTokenCount (output), and cachedContentTokenCount (the cache-hit portion). I now save all of it, on every request, without exception.

// A thin wrapper that accounts for tokens on every chat response
async function generateWithAccounting({ model, contents, systemInstruction, userId, requestId }) {
  const res = await model.generateContent({ contents, systemInstruction });
  const u = res.response.usageMetadata ?? {};
 
  // Rates are USD per 1M tokens (Gemini 2.5 Pro as of July 2026)
  const RATE = { input: 1.5, output: 6.0, cacheHit: 0.375, cacheWrite: 2.25 };
  const cached = u.cachedContentTokenCount ?? 0;
  const inputBillable = (u.promptTokenCount ?? 0) - cached;
  const costUsd =
    (inputBillable / 1e6) * RATE.input +
    (cached / 1e6) * RATE.cacheHit +
    ((u.candidatesTokenCount ?? 0) / 1e6) * RATE.output;
 
  await db.insert('token_ledger', {
    request_id: requestId,
    user_id: userId,
    prompt_tokens: u.promptTokenCount ?? 0,
    cached_tokens: cached,
    output_tokens: u.candidatesTokenCount ?? 0,
    est_cost_usd: costUsd,
    created_at: new Date(),
  });
  return res;
}

The important detail is subtracting cachedContentTokenCount from input before computing the billable amount. If you count the cache-hit portion at the full input rate, you swing the other way and overstate your cost.

I let this token_ledger accumulate for a week and reconciled it against the pro-rated monthly invoice. In my environment the ledger total and the invoice differed by under 3%. So the ledger was trustworthy. That is where the real work began.

Bet that the culprit is one of three lanes

Once I knew the ledger was trustworthy, I made a bet from my own experience as an indie developer. When the estimate and the invoice diverge, the cause almost always collapses into three lanes outside the unit price: input-token bloat, cache misses, and retry double-billing.

From here I verify each of the three in the ledger, in order. Rather than suspecting everything by feel, narrowing to measurable hypotheses before touching code was the shortest way to avoid a detour.

The design of recording usage_metadata itself is covered in Tracking cost with Gemini API usage metadata in production. This piece is the sequel that turns that ledger into a hunt for the leak.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
A token_ledger design that records usage_metadata per request and reconciles it against the monthly invoice to the cent
A procedure that splits the gap from the estimate into three lanes: conversation-history bloat, cache writes that never get read, and retry double-billing
How to protect margin using effective cost per request rather than the unit price table, after each leak is plugged
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

API / SDK2026-07-06
When Context Caching Didn't Lower My Gemini Bill — Field Notes on Measuring the Real Hit Rate
When Context Caching is enabled but the Gemini API bill barely drops, this field note measures the real hit rate from usage_metadata, separates TTL churn from fragmentation, and walks through a staged recovery.
API / SDK2026-03-12
Reading Gemini API Logs by What Survived — Field Notes on Logging & Datasets
Use the Gemini API logging and datasets tool from a results-first angle — not token counts or latency, but whether each output actually survived to publication. Includes tying log review to spend caps and API key hygiene.
API / SDK2026-07-05
Designing Batch Image Costs with Nano Banana 2 Lite: Decide by Measuring
How to fold the fastest, cheapest image model, Nano Banana 2 Lite, into high-volume generation: measuring per-image cost, a two-tier setup with a quality model, and retry handling grounded in real numbers.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →