●2.5 ROUTE — Since 12/1, gemini-2.5-pro routes to 3.8 Flash and gemini-2.5-flash to 3.5 Flash-Lite, billed at the new model's rates●CARBON — Intro pricing for Gemini 4 Carbon and Argon has ended. Standard rates: $4.00 input, $20.00 output per 1M tokens●OMNI 1.1 — gemini-omni-1.1-flash starts routing to 1.2 Flash on 12/3, one day from now●COMPRESS — Some Gemini CLI users report auto-compression that barely shrinks the context, round after round●FALLBACK — Planning for model changes or traffic spikes? Decide your retry count and fallback model up front●LONG DOC — Feeding Gemini a long document? State your goal and the part to read first, and fewer details get dropped●2.5 ROUTE — Since 12/1, gemini-2.5-pro routes to 3.8 Flash and gemini-2.5-flash to 3.5 Flash-Lite, billed at the new model's rates●CARBON — Intro pricing for Gemini 4 Carbon and Argon has ended. Standard rates: $4.00 input, $20.00 output per 1M tokens●OMNI 1.1 — gemini-omni-1.1-flash starts routing to 1.2 Flash on 12/3, one day from now●COMPRESS — Some Gemini CLI users report auto-compression that barely shrinks the context, round after round●FALLBACK — Planning for model changes or traffic spikes? Decide your retry count and fallback model up front●LONG DOC — Feeding Gemini a long document? State your goal and the part to read first, and fewer details get dropped
Gemini API × Stripe — Production Usage-Based Billing for Indie AI SaaS
Build flat-plus-metered billing for a Gemini API SaaS with Stripe Billing Meters and webhooks: frozen batches that prevent double charges, basil-era period fields, @google/genai metering, and a troubleshooting table.
The first time I opened an invoice preview in test mode, the Pro line read "¥98,000" and I just sat there. I'd meant ¥980 a month. I had forgotten that the yen is a zero-decimal currency and had multiplied by 100 out of dollar habit. The only reason no real customer ever saw that number is that I'd pushed one subscription all the way to an invoice in test mode before going live.
When you're building a Gemini-powered SaaS on your own, billing looks like the part you can bolt on later. But usage-based billing has three moving pieces — counting, reporting, and deciding what a user is allowed to do — and if any one of them drifts, you either double-charge someone or quietly stop charging them. Both cost you trust in a single invoice.
Below is the hybrid setup I rebuilt: a flat base plan plus metered overage, using the Gemini API and Stripe Billing Meters. I've updated everything to how Stripe and the Gemini API work as of November 2026; several things in the earlier version of this article were out of date, and one was simply wrong.
The one idea I'd like you to take away: make counting, reporting, and entitlement each safe to re-run on their own. Every section below is ordered around that.
The short answer — which billing model to pick
What I'd say first is that with an LLM behind your product, usage varies so much between users that it breaks most flat pricing. If someone who calls your feature a few dozen times a month pays the same as someone who calls it hundreds of times a day, either the light users subsidize the heavy ones or you eat the difference.
Products built around occasional heavy jobs (long video summaries, say)
You need balance tracking and expiry terms
If you want both "the customer can predict the bill" and "my cost can't run away," pick the hybrid. The example tiers in this article are:
Free: up to 50,000 tokens/month (room to try the product)
Pro (¥980/month): 500,000 tokens included, then ¥150 per 100,000 tokens
Team (¥4,800/month): 5,000,000 tokens included, then ¥100 per 100,000 tokens
Treat the numbers as placeholders. I'd set your own only after running the shadow metering I describe near the end.
The flow — from one call to one invoice line
Every Gemini call writes one row to your own database with the usageMetadata breakdown.
A job runs every minute, groups unsent rows per user into a batch, and freezes that batch with an ID.
Each frozen batch goes to Stripe as a Meter Event, using the batch ID as its identifier.
At the end of the billing period, Stripe issues one invoice: base fee plus metered quantity times unit price.
Webhooks tell you something changed; you re-fetch the current subscription from Stripe and update entitlements from that.
The important part is that the Gemini call and the Stripe report are decoupled. Reporting inline adds latency and lets a Stripe hiccup break the user's response. Buffering in your own database keeps each failure local.
✦
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
✦You'll get a setup script for one Meter and two Prices, written so a zero-decimal JPY price never comes out 100× too high
✦You'll build retry-safe usage reporting with frozen batches and webhook sync that doesn't depend on delivery order
✦You'll have a symptom-to-fix troubleshooting table plus the grace-period and reconciliation design you need after launch
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.
You can click these together in the dashboard, but I'd script them so test and live are identical. The earlier version used CLI flags; flag spellings drift between CLI releases, so I've moved it to the Node SDK.
// scripts/setup-stripe.ts — run once with: npx tsx scripts/setup-stripe.tsimport Stripe from "stripe";// Omitting apiVersion uses the version pinned by your installed stripe-nodeconst stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);// 1) A Meter for tokensconst meter = await stripe.billing.meters.create({ display_name: "Gemini API Tokens", event_name: "gemini_api_tokens_used", default_aggregation: { formula: "sum" }, customer_mapping: { type: "by_id", event_payload_key: "stripe_customer_id" }, value_settings: { event_payload_key: "value" },});// 2) Product and flat base Price (JPY is zero-decimal: 980 means ¥980)const product = await stripe.products.create({ name: "Gemini SaaS Pro" });const base = await stripe.prices.create({ product: product.id, currency: "jpy", unit_amount: 980, recurring: { interval: "month" },});// 3) Metered overage Price, tied to the Meter; first 500K tokens are freeconst overage = await stripe.prices.create({ product: product.id, currency: "jpy", billing_scheme: "tiered", tiers_mode: "graduated", recurring: { interval: "month", usage_type: "metered", meter: meter.id }, tiers: [ { up_to: 500_000, unit_amount_decimal: "0" }, { up_to: "inf", unit_amount_decimal: "0.0015" }, // ¥150 per 100,000 tokens ],});console.log({ meter: meter.id, base: base.id, overage: overage.id });
Save the three IDs as environment variables and pass both base and overage as line items when you create the subscription through Checkout.
Two Prices on one subscription works because a Stripe subscription can hold several Subscription Items. The flat fee and the metered overage land on the same invoice, and moving someone from Pro to Team is just swapping Prices. Because the tiers are graduated, a month with 1,000,000 tokens adds ¥750 — only the 500,000 tokens above the allowance are billed.
Metering — recording usageMetadata with @google/genai
The previous version used @google/generative-ai. That package is officially deprecated, and Google points you to the unified @google/genai SDK instead. The call shape changed, so I rewrote the metering layer.
// src/lib/gemini.tsimport { GoogleGenAI } from "@google/genai";import { recordTokenUsage } from "./usage-store";const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }); // YOUR_API_KEY via envexport async function generateWithUsage( userId: string, prompt: string, model: string = "gemini-3.5-flash-lite"): Promise<{ text: string; totalTokens: number }> { const response = await ai.models.generateContent({ model, contents: prompt }); const u = response.usageMetadata; const totalTokens = u?.totalTokenCount ?? 0; try { await recordTokenUsage({ userId, model, promptTokens: u?.promptTokenCount ?? 0, outputTokens: u?.candidatesTokenCount ?? 0, thoughtsTokens: u?.thoughtsTokenCount ?? 0, cachedTokens: u?.cachedContentTokenCount ?? 0, totalTokens, missingUsage: u === undefined, occurredAt: new Date(), }); } catch (err) { // Don't fail the user's response over a metering write — but do alert on it console.error("[usage] record failed", { userId, err }); } return { text: response.text ?? "", totalTokens };}
Three differences from the old SDK: getGenerativeModel is gone in favor of ai.models.generateContent; the text is a response.text property rather than a response.text() method; and usageMetadata sits directly on response.
I keep the breakdown in separate columns so I can reconcile against cost later. Thinking tokens (thoughtsTokenCount) and cached tokens (cachedContentTokenCount) are priced differently depending on the model, and a single total won't explain your cost at month end. Check what the total includes for your model and version before you decide which number to bill on. I've written up the usual reasons estimates and billed tokens diverge in why count_tokens estimates and billed tokens don't match.
missingUsage flags rows where no usageMetadata came back — a stream cut off mid-response, for example. Billing those as zero leaks revenue; silently estimating them produces charges you can't explain. What worked for me was to flag them and look at the count before closing each period.
Storing usage and freezing batches (Postgres)
This is the part of the old article I most wanted to fix. It used to gather unsent rows on every run and build the identifier from the first and last row IDs. If Stripe accepted a request but the response was lost, the rows stayed "unsent," new rows joined them on the next run, and the same usage went out again under a different identifier. That is a double charge waiting to happen.
The fix is to freeze each batch in the database before sending, and use the batch ID as the identifier. A batch then arrives with the same ID no matter how many times you retry it.
CREATE TABLE token_usage ( id bigserial PRIMARY KEY, user_id text NOT NULL, model text NOT NULL, prompt_tokens integer NOT NULL, output_tokens integer NOT NULL, thoughts_tokens integer NOT NULL DEFAULT 0, cached_tokens integer NOT NULL DEFAULT 0, total_tokens integer NOT NULL, missing_usage boolean NOT NULL DEFAULT false, occurred_at timestamptz NOT NULL, batch_id uuid, reported_at timestamptz);CREATE INDEX token_usage_open ON token_usage (batch_id) WHERE reported_at IS NULL;
// src/lib/usage-store.ts (assumes postgres.js)import { sql } from "./db";export async function recordTokenUsage(r: { userId: string; model: string; promptTokens: number; outputTokens: number; thoughtsTokens: number; cachedTokens: number; totalTokens: number; missingUsage: boolean; occurredAt: Date;}): Promise<void> { await sql` INSERT INTO token_usage (user_id, model, prompt_tokens, output_tokens, thoughts_tokens, cached_tokens, total_tokens, missing_usage, occurred_at) VALUES (${r.userId}, ${r.model}, ${r.promptTokens}, ${r.outputTokens}, ${r.thoughtsTokens}, ${r.cachedTokens}, ${r.totalTokens}, ${r.missingUsage}, ${r.occurredAt}) `;}// Give unassigned rows a per-user batch ID; once assigned, a row never movesexport async function claimBatches(): Promise<void> { await sql` WITH pending AS ( SELECT DISTINCT user_id FROM token_usage WHERE reported_at IS NULL AND batch_id IS NULL ), ids AS ( SELECT user_id, gen_random_uuid() AS batch_id FROM pending ) UPDATE token_usage t SET batch_id = ids.batch_id FROM ids WHERE t.user_id = ids.user_id AND t.reported_at IS NULL AND t.batch_id IS NULL `;}export async function fetchOpenBatches(limit = 500) { return sql<{ batch_id: string; user_id: string; total: string; last_at: Date }[]>` SELECT batch_id, user_id, SUM(total_tokens) AS total, MAX(occurred_at) AS last_at FROM token_usage WHERE reported_at IS NULL AND batch_id IS NOT NULL GROUP BY batch_id, user_id ORDER BY MIN(occurred_at) LIMIT ${limit} `;}export async function markBatchReported(batchId: string): Promise<void> { await sql`UPDATE token_usage SET reported_at = NOW() WHERE batch_id = ${batchId}`;}
postgres.js returns SUM as a string, so convert and check it right before sending. This assumes a single worker runs the job; with several, take a lock (for example pg_advisory_lock) before claimBatches.
The reporting job
// src/jobs/report-usage-to-stripe.tsimport Stripe from "stripe";import { claimBatches, fetchOpenBatches, markBatchReported } from "../lib/usage-store";import { getStripeCustomerId } from "../lib/customer-store";const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);export async function reportUsageToStripe() { await claimBatches(); const batches = await fetchOpenBatches(); let sent = 0, skipped = 0, failed = 0; for (const b of batches) { const total = Number(b.total); const customerId = await getStripeCustomerId(b.user_id); if (!customerId || total <= 0) { // Free users and other batches with nobody to bill: close without sending await markBatchReported(b.batch_id); skipped++; continue; } try { await stripe.billing.meterEvents.create({ event_name: "gemini_api_tokens_used", identifier: b.batch_id, // same ID on every retry payload: { stripe_customer_id: customerId, value: String(total) }, timestamp: Math.floor(new Date(b.last_at).getTime() / 1000), }); await markBatchReported(b.batch_id); sent++; } catch (err) { // Leave it open; the next run retries with the same batch_id console.error("[stripe-meter] report failed", { batch: b.batch_id, err }); failed++; } } return { sent, skipped, failed };}
Stripe's API reference says identifier uniqueness is enforced over a rolling window of at least 24 hours, and that timestamp must fall within the past 35 calendar days or no more than 5 minutes in the future (checked against the Create Meter Event reference, November 2026). So deduplication is not forever. If the job is down for more than a day and you're left with batches whose status you can't tell, compare the Meter's totals in the dashboard with your database before resending — I'd put that step in your runbook.
I haven't confirmed whether Stripe returns success or an error when the same identifier arrives twice. Before writing a branch that treats one as "already sent," send the same batch twice in test mode and look at what comes back.
Any scheduler works — Cloudflare Workers Cron Triggers, Cloud Scheduler, whatever you already run. At one-minute intervals, users see their usage update almost immediately.
Webhooks — syncing entitlements without trusting arrival order
invoice.payment_failed — payment failed (enter the grace period)
// src/app/api/stripe/webhook/route.ts (Next.js App Router)import Stripe from "stripe";import { NextResponse } from "next/server";import { claimEvent, releaseEvent, upsertSubscription, setPastDue, clearPastDue, detectTierFromItems } from "@/lib/billing";const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;const expectLive = /^(sk|rk)_live_/.test(process.env.STRIPE_SECRET_KEY!);export async function POST(req: Request): Promise<Response> { const sig = req.headers.get("stripe-signature"); const body = await req.text(); if (!sig) return new NextResponse("missing signature", { status: 400 }); let event: Stripe.Event; try { // Use the async variant on Workers / Edge runtimes event = await stripe.webhooks.constructEventAsync(body, sig, webhookSecret); } catch (err) { console.error("[stripe-webhook] signature verify failed", err); return new NextResponse("invalid signature", { status: 400 }); } // Catch test/live mix-ups here if (event.livemode !== expectLive) { console.error("[stripe-webhook] livemode mismatch", { id: event.id, livemode: event.livemode }); return new NextResponse("mode mismatch", { status: 400 }); } // INSERT ... ON CONFLICT DO NOTHING: true only the first time we see this event.id if (!(await claimEvent(event.id))) return NextResponse.json({ received: true, duplicate: true }); try { switch (event.type) { case "customer.subscription.created": case "customer.subscription.updated": case "customer.subscription.deleted": { const { id } = event.data.object as Stripe.Subscription; // Write the current state, not the state in the event const sub = await stripe.subscriptions.retrieve(id); const periodEnd = sub.items.data[0]?.current_period_end; await upsertSubscription({ customerId: sub.customer as string, subscriptionId: sub.id, status: sub.status, tier: sub.status === "canceled" ? "free" : detectTierFromItems(sub.items.data), currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null, }); break; } case "invoice.paid": await clearPastDue((event.data.object as Stripe.Invoice).customer as string); break; case "invoice.payment_failed": { const inv = event.data.object as Stripe.Invoice; await setPastDue({ customerId: inv.customer as string, attemptCount: inv.attempt_count ?? 0 }); break; } default: // Acknowledge unknown events with 200, or Stripe keeps retrying them console.log("[stripe-webhook] unhandled", event.type); } return NextResponse.json({ received: true }); } catch (err) { console.error("[stripe-webhook] handler failed", { type: event.type, err }); // Release the claim, then return 5xx so Stripe's retry can redo the work await releaseEvent(event.id); return new NextResponse("internal error", { status: 500 }); }}
Three things changed from the earlier version.
First, don't read the period end off the subscription itself. In API version 2025-03-31.basil, Stripe removed current_period_start and current_period_end from the Subscription and moved them to Subscription Items. With a newer SDK, the old sub.current_period_end is undefined, and new Date(NaN) ends up in your database.
Second, write the state you just fetched, not the state the event carried. Webhook delivery order isn't guaranteed; deleted can arrive before updated. If you treat each event only as a nudge and call subscriptions.retrieve, ordering stops mattering.
Third, claim event.id atomically before doing the work. Writing "have we seen this?" and "mark as seen" as two separate steps lets two simultaneous deliveries both slip through. releaseEvent undoes the claim on failure so Stripe's retry can try again.
Tier-based gating
Keeping model and feature access per tier in one place makes adding tiers painless.
// src/lib/feature-gate.tstype Tier = "free" | "pro" | "team";export const FEATURES: Record<Tier, { allowedModels: string[]; monthlyTokenIncluded: number; visionEnabled: boolean; longContextEnabled: boolean;}> = { free: { allowedModels: ["gemini-3.5-flash-lite"], monthlyTokenIncluded: 50_000, visionEnabled: false, longContextEnabled: false }, pro: { allowedModels: ["gemini-3.5-flash-lite", "gemini-3.8-flash"], monthlyTokenIncluded: 500_000, visionEnabled: true, longContextEnabled: false }, team: { allowedModels: ["gemini-3.5-flash-lite", "gemini-3.8-flash"], monthlyTokenIncluded: 5_000_000, visionEnabled: true, longContextEnabled: true },};export class FeatureNotAllowedError extends Error { constructor(public readonly feature: string, public readonly currentTier: Tier, public readonly requiredTier: Tier) { super(`feature "${feature}" requires "${requiredTier}", but user is on "${currentTier}"`); }}export function ensureModelAllowed(tier: Tier, model: string): void { if (FEATURES[tier].allowedModels.includes(model)) return; const order: Tier[] = ["free", "pro", "team"]; const required = order.find((t) => FEATURES[t].allowedModels.includes(model)); if (!required) throw new Error(`unknown model: ${model}`); // reject models we don't list throw new FeatureNotAllowedError("model", tier, required);}
The old ensureModelAllowed answered "available on Team" for any model name it didn't recognize. Since the client can send any string, an unknown model should be a 400.
The model list uses gemini-3.5-flash-lite and gemini-3.8-flash, both listed on the official model pages as of November 2026. According to Google's deprecations page, from December 1 calls naming gemini-2.5-flash are routed to gemini-3.5-flash-lite and gemini-2.5-pro to gemini-3.8-flash, billed at the destination model's price. Your model column will keep the name you asked for, so any code still naming a 2.5 model will make your cost math drift without anything visibly breaking. Updating the list and letting the gate reject old names closes that gap. If you're unsure which of the two to default to, choosing the effort level on Gemini 3.8 Flash may help.
Troubleshooting table
Symptom
Likely cause
How to check
Fix
Base fee shows 100× too high
unit_amount: 98000 on a JPY Price
The amount on the Price detail page
Recreate with the plain yen amount (980) — JPY is zero-decimal
Same usage billed twice
identifier changes on every retry
Two events with the same time and value in the Meter's event list
Freeze batches in the DB and use the batch ID as identifier
Metered usage stuck at 0
usageMetadata moved after the SDK migration
missing_usage count and raw response logs
Read from response.usageMetadata
Period end is Invalid Date
Reading sub.current_period_end on basil or later
SDK version and the fetched subscription JSON
Read sub.items.data[0].current_period_end
Every webhook returns 400 (signature)
Secret from the wrong mode or the wrong endpoint
Endpoint details and mode in the dashboard
Re-copy that endpoint's signing secret
Canceled user still on Pro
deleted arrived before updated and old state overwrote it
Order of created timestamps in the event log
Write the state from retrieve, not the event payload
Last period's usage never billed
The job was down past the period close
Oldest unsent batch timestamp
Alert on job downtime and drain before the period closes
Three things people (including me) get wrong
"Test-mode webhook secrets start with whsec_test_." I wrote that in the earlier version, and it was wrong. Signing secrets start with whsec_ in both modes; you can't tell them apart by prefix. Comparing event.livemode with the mode of your secret key, as above, is the reliable guard.
"With an identifier, I can resend any time without duplicates." The uniqueness window is described as at least 24 hours, not forever. After a long outage, look at the totals before resending by hand.
"The period end lives on the subscription." It did on older API versions; from basil on it lives on the Subscription Item. Many samples online still target old versions, so check their apiVersion before copying.
Adding metering to an existing flat-rate product
If you already run a flat plan, I wouldn't start reporting to Stripe on day one.
Run shadow metering for at least one full billing period: record tokens and compute what each user would pay under the new pricing, without sending anything. Size the included allowances from that data. I'd first sized them around my own usage, and the shadow data changed how I thought about the allowances altogether.
Then give people a full period's notice, with their own numbers. "Last month you used 327,000 tokens; under the new plan you'd pay nothing extra" and "Last month you used 1,200,000 tokens; under the new plan that's an extra ¥1,050" are messages for different people. The second person should hear it from you, not from their invoice.
The upgrade prompt can be built straight from the 402. Using current_tier and required_tier to say "This is included in Pro; you're on Free" presents the feature as something within reach rather than a wall, which feels more honest to the reader.
What you'll hit next — grace periods and reconciliation
The first thing production throws at you is an expired card. Dropping someone to Free the instant a payment fails cuts off people who did nothing wrong. Stripe has past_due and unpaid states; keeping features on during past_due while you ask for a new card is the gentler path, and that's what setPastDue drives in the UI.
The second is drift from missed webhooks. A monthly job that lists active subscriptions from Stripe and compares them with the tier in your database catches mismatches before they pile up. For protecting the Gemini side as traffic grows, see Gemini API rate limiting and quota management.
On my dashboard I keep three numbers at minimum: open batch count and oldest timestamp, Meter Event success rate over the last hour, and the missing_usage count. With alerts on those, you rarely find out about a problem from an invoice.
What I got wrong, and the line I hold now
Besides the ¥98,000 moment, metering tripped me up more than once. When I moved from the old SDK to @google/genai, I didn't notice the response shape had changed, and for a while all I was collecting was missing_usage rows. I caught it within days only because the count was on a dashboard; without it, I'd have found out at month end.
The other was thinking about retries in terms of "whatever rows are unsent." That a lost response could deliver the same usage twice under two names — I honestly couldn't picture it until I deliberately cut the network in test mode.
The line I drew from both: counting, reporting, and entitlement each have to give the same result no matter how many times they run. I put that ahead of speed or tidy-looking code.
If you do one thing first, ship only generateWithUsage to production and watch a week of token counts accumulate in your database before building any billing UI. Your allowances are much easier to set calmly from that data.
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.