RIKKY ROY KOGANTIAtlas of curiosityKyrodigm

Notebook / Building apps

Controlling LLM API costs

Measure and cap AI spending across providers, with worked examples for Gemini tokens, caching, grounding, and Batch.

Five checks for keeping AI costs in bounds

Total spend ÷ usable results

Include failed attempts, retries, and paid tools. With 1,200 billable attempts for 1,000 usable results, you pay for 1.2 attempts per result on average.

Generate fewer output tokens
Ask the model for the fields you actually need and build the rest in code. Check that quality holds on real requests.
Cap spend before dispatch
Reserve budget before sending a call. Parallel workers and retries should draw from the same allowance.
Keep completed work
Save valid results and retry only the missing pieces. Set a retry limit and a fallback for when it runs out.
Count searches separately
One Gemini request with Search can generate several queries. Measure both the typical request and the expensive ones.
Try the worked example

$160to$68/ month

600 input + 200 output tokens per summary. Output includes billed thinking. One billable attempt per successful summary.

Gemini 3.5 Flash-Lite · Standard token charges · rates checked

Uses the article’s illustrative workload and dated rates, not live pricing. Excludes search, caches, taxes, other services, and retries. Compare quality before choosing a shorter request. Read the worked example and Batch comparison.

Scope. These practices apply to metered LLM APIs in mobile and web apps. The Gemini prices below are in US dollars and were verified November 21, 2026. Check the exact model, endpoint, pricing tier, and tool terms you use.

Browse Backend systems

What to check before shipping an AI feature

  • For any LLM API
    • Price a completed task. Count input, output, reasoning where billed, cache and tool charges, and every billable attempt. Include retries and fallback calls. What to measure.
    • Make the model return less. Use compact keys when they save measured tokens, ask for the minimum fields, and build the rest in code. Compare model and reasoning settings on real tasks. Output optimizations · Models and caching.
    • Enforce limits on the backend. Keep paid credentials on your server. Reserve an estimate before starting work, deduplicate retries, and set user and global limits. Verify what the app does when it runs out. Usage controls.
    • Save progress before retrying. Keep validated results, retry the missing pieces within a budget, and pick a fallback for exhausted retries. Retry and resume.
  • When using Gemini or Google Cloud

Cost controls across LLM providers

Measure cost per successful taskOne tap can trigger several billable calls. Track what the user gets for the total spent.
  • Use the provider’s units. Separate uncached input, cached input, visible output, and any billable reasoning. Include tool calls, media, cache writes or storage, and other paid work where applicable. Check rates by provider, exact model, and service tier. API usage and a coding-tool subscription can have different pricing and limits. OpenAI API pricing · Claude API pricing · DeepSeek API pricing.
  • Record every attempt under one user action. On the backend, record the feature, requested and served model where available, rate version, task ID, counts, tool usage, outcome, latency, and estimated charge. Track attempts that timed out, were cancelled, or returned invalid results, and reconcile unknown charges later. Keep raw prompts, responses, and personal data out of cost logs.
  • Compare cost and quality together. Divide estimated spend across all attempts by usable results delivered. Track successes, retries, slow requests, and the share of spend from your most expensive tasks. Reconcile your estimates with provider usage and billing by project and charge type. Recheck whenever you change a model, prompt, tool, or output schema.
  • Gemini example. In the generateContent API, promptTokenCount includes cached prompt tokens. Subtract cachedContentTokenCount before pricing the uncached portion. Track candidatesTokenCount, thoughtsTokenCount, and toolUsePromptTokenCount separately and apply the pricing rules for the chosen model and tools. A single total token count mixes units with different rates. The Interactions API uses different usage fields. GenerateContent usage metadata · Gemini token accounting.
Reduce output tokens and build the rest in codeShort keys, stable IDs, and app-side rendering can cut the number of tokens the model needs to generate.
  • Send only what the task needs. Pull the relevant notes, recent turns, or fields first. Trim repeated instructions and bulky tool results. Count input using the chosen model’s tokenizer or provider endpoint. Text length, compressed network bytes, and token count measure different things. In Gemini, use countTokens to estimate the input and compare it with actual usage after generation. Gemini token counting.
  • Try one- or two-character keys in repeated objects. The model could return {"s":"Book the train by Friday.","t":["travel"]}. Define s and t in the schema, then decode them into summary and tags in the app. Keep the mapping versioned and validate it. A short key may still tokenize to the same count as a longer one. Check billed output and any added schema input on the actual model, especially on responses with many repeated rows. Gemini structured output.
  • Have code fill in everything it can. Ask the model for the smallest new piece of information, such as a category ID, a few extracted values, or an edit to an existing record. Use code to look up labels, join source records, calculate totals, and render a full screen or report. For example, return the IDs of the notes to include and a short summary. The app can supply each note’s title, date, and source link.
  • Stop regenerating unchanged fields. Ask for a list of changed fields or missing item IDs. Use a bounded list of categories or reason codes when a long explanation adds little. Keep user-facing explanations where they matter and skip repeating the question, a preamble, or formatting the app will apply anyway.
  • Set a useful output limit. Compare concise text with JSON when either format will work. Try a word, item, or field limit in the instructions and a per-request output token limit. Check if the model returns incomplete text or JSON. Include reasoning tokens in the evaluation where they’re billed. Compare typical and high-end output size, valid results, and cost with retries included. Gemini token accounting · Recover incomplete output.

Gemini example. At Flash-Lite’s $2.50 Standard output rate per million tokens, saving 40 billed output tokens per call over 100,000 calls saves $10 in output charges. Check how much extra input the schema needs and whether retry frequency changes before counting the net savings. Flash-Lite pricing.

Match the model, reasoning, and cache to the taskUse the lowest-cost combination that still gives users a result they can use.
  • Evaluate on the same inputs. Run common, difficult, and unusually long requests through cheaper and more capable models. Score correctness, required details, latency, completion rate, and cost per usable result. Start with the cheaper model if it meets the target. Escalate only for a defined failure or task class, and include both calls in the cost. On Gemini, compare Flash-Lite at minimal with higher thinking levels or a Flash model. Gemini model and thinking controls.
  • Reuse stable context. Many providers discount cached input. Put identical shared instructions or reference material first and changing user content later where the provider matches a prefix. Check cache minimums, expiry, any write or storage charges, and actual cached tokens. When caching the finished answer yourself is appropriate, scope private results to the right user and invalidate them when inputs, permissions, or model settings change. Check provider terms before reusing tool results. Claude prompt caching · DeepSeek context caching · Gemini cache example.
Stop runaway spending before dispatchUse backend limits for the requests you control, including queues and retries.
  1. Set limits at each level. Keep credentials on the server and restrict them to the services they need. Separate production and test projects. Require an eligible account for private or paid actions. Set input, output, tool, and retry limits per task, plus limits per account, per feature, and across the service. Bound concurrent work and queue length so a spike cannot start everything at once.
  2. Reserve before sending. Give each user action a stable ID and save its pending or completed state. Reserve a conservative estimate for new work against a shared budget before making the provider call. Make the check and reservation together so parallel workers cannot spend the same remaining balance. Charge actual usage when it arrives. Hold capacity for requests with unknown outcomes until you can reconcile them or account for the possible charge.
  3. Test failures and the limit. Try double taps, simultaneous requests, a timeout after dispatch, retries, and a full queue. Confirm that the limit stops new work and that pending work is accounted for. Provide a feature pause and a clear message or cheaper fallback that stays within the remaining allowance. Keep an alert for high spend or rapid growth and leave a buffer for calls already running or charges reported later.
Save valid output and retry only what’s missingGive expensive jobs durable progress, a retry budget, and a way to finish if the model remains unavailable.
  1. Give each task and output item a stable ID. Divide a long job into independently usable items or stages. Save completed, validated items and the remaining IDs in backend storage. Record the input or its version, schema version, and attempt state so a restarted worker can find the right result. Save generated content only where retention is permitted and necessary. Restrict access and set a deletion period. Gemini terms for tool results.
  2. Salvage what you can verify. If the stream breaks or Gemini reports MAX_TOKENS, keep complete items that pass schema and meaning checks. Repair formatting locally only when the intended values are unambiguous. If a value or record is incomplete, keep it pending. Treat safety-blocked output as unusable. For example, if a five-item task produced three validated records, save those three and retry only the other two IDs. Include the necessary source context, use a schema for the missing items or fields, and merge by ID so a late attempt cannot overwrite an accepted result. Gemini finish reasons · Gemini structured output.
  3. Match the retry to the failure. For a transient 429 or 503, wait and use bounded exponential backoff with jitter. Respect Retry-After when present. If a quota or credit limit is exhausted, wait for reset or use the fallback. Fix malformed requests and access errors before attempting them again. For truncated output, try a smaller set of requested items or adjust the output limit within budget. Check what the SDK already retries so your own retry loop does not multiply attempts. Gemini retry guidance · HTTP Retry-After.
  4. Give the whole job a limit and an exit. Set a shared limit for attempts, elapsed time, and expected spend across all workers and fallback calls. Keep the reservation for an ambiguous timeout until you can account for the possible charge. When attempts run out, return the validated progress or an app-generated result from known data where useful. A local model or another provider is an option if it can meet the quality, privacy, and spend limits. Test a worker restart mid-job, a broken stream, and a successful late response. Usage controls.

Gemini API and Google Cloud specifics

Work through Gemini token costsAt these rates, the example falls from $160 to $68 with shorter requests and responses, or $34 in Batch.

Use Gemini 3.5 Flash-Lite on the paid Gemini Developer API, with illustrative counts for 100,000 text summaries. Standard rates are $0.30 per million input tokens and $2.50 per million output tokens, including billed thinking. Batch rates are $0.15 and $1.25 respectively. The example assumes one billable attempt per successful summary. It excludes search, caches, taxes, and other services. Gemini 3.5 Flash-Lite pricing, November 21, 2026.

100,000 summaries Input per attempt Output including thinking Input + output charges
Original, Standard 2,000 400 $60 + $100 = $160
Shorter, Standard 600 200 $18 + $50 = $68
Same shorter work, Batch 600 200 $9 + $25 = $34

The shorter Standard workload saves $92 at the same number of successful results. With one extra equally expensive attempt for every ten summaries, it costs $74.80. Try the shorter format on the same cases and record how many results users can actually use. Model comparison.

Choose a Gemini model and thinking levelCheck the level your model supports and compare total billed output, including thinking.
Model Thinking levels and default Paid Standard text rates per million tokens
Gemini 3.5 Flash-Lite minimal, low, medium, high. Default minimal. $0.30 input / $2.50 output. Start here for simple extraction, tagging, or summaries if it meets your quality target.
Gemini 3.6 Flash minimal, low, medium, high. Default medium. $0.75 / $3.75 through December 31, 2026. $1.50 / $7.50 from January 1, 2027.
Gemini 3.8 Flash low, medium, high. Default medium. $0.75 / $3.75 through December 31, 2026. $1.50 / $7.50 from January 1, 2027.

These are selected models, and all listed output rates include billed thinking. Compare the result and actual billed tokens with the level you intend to use. Watch for incomplete output when lowering the token limit. Thinking levels · 3.5 Flash-Lite pricing · 3.6 Flash pricing · 3.8 Flash pricing.

Watch model migrations. Google says requests to the deprecated gemini-2.5-flash ID will route to Gemini 3.5 Flash-Lite at replacement rates from December 1, 2026. Recheck the served model, behaviour, and billed cost even if the app still sends the same ID. Gemini deprecation schedule.

Calculate when Gemini context caching pays offTrack reused input tokens and compare the savings with any storage costs.
  • Begin with implicit caching. Keep shared context stable and place it early. Verify actual hits in usage metadata. Explicit caches are available with generateContent on supported models. The Interactions API only supports implicit caching. Check the model’s minimum size, cache lifetime, and support first. Gemini cache modes · Explicit caching.
  • Check the break-even point. At Flash-Lite Standard rates, a hit for 20,000 tokens costs $0.0006 instead of $0.006, saving $0.0054. Keeping an explicit cache of that size for one hour costs $0.02 in storage at the listed rate. Four hits in that hour cover storage alone. Count misses, any other charges, and how long you keep the cache before assuming a saving. Flash-Lite cache pricing.
Control what Google Search grounding costsBudget for individual Search queries, since a single answer can use several.
  • Apply the right allowance. On the paid Gemini Developer API, Google lists 5,000 free Search queries per month shared across Gemini 3 and newer models, then $14 per 1,000 queries. The published default daily cap is 1,500 queries per project. The allowance covers the Search tool. Model token usage has its own rates. Older models can use per-grounded-prompt billing. Check your actual service and model. Google Search grounding pricing · Tool pricing and limits.
  • Measure queries per prompt. Gemini can run several searches during one model call. Count search queries from the grounding metadata exposed by your endpoint, and reconcile that estimate with billed tool usage. For example, 4,000 grounded answers averaging two billed queries use 8,000 queries. If the full allowance was unused and the work stayed within daily limits, the Search charge is $42 for the 3,000 excess queries. Google Search grounding metadata and pricing.
  • Tune prompts against the same questions. Compare “Research this store” with “Find today’s opening hours for this address. Prefer the store’s own site. Stop once you have hours for that location and date.” Track query totals and the mean for cost, the median for typical behaviour, and the 90th percentile to see how many queries the expensive prompts use. Check whether answers are still current and accurate. A prompt can influence how much the model searches. Cap how many grounded requests you start and leave room for several queries per request. Search grounding pricing.
  • Compare fetching a known source yourself. If you already know the authoritative source, compare using an official API, licensed feed, or other permitted access and sending only the relevant facts to an ungrounded request. Include fetch fees, extra input tokens, freshness checks, and upkeep in the estimate. Check the site or API terms, copyright and licence, privacy, and permission to access, store, and send the material to the model. Check the applicable rules even for a personal project. For Google’s own grounding, follow its display and attribution rules and verify limits on caching and reuse. US fair use · Canadian fair dealing · Gemini Developer API terms.
Limit Gemini requests, input tokens, and burstsUse a shared scheduler so parallel calls stay within the same rate limits.
  1. Check your project, model, and service. Start with your active Gemini Developer API limits in AI Studio. Google measures requests per minute (RPM), input tokens per minute (TPM), and requests per day where applicable. Limits vary by model and usage tier and apply per project across its API keys. Google also documents rolling spend-rate limits for paid tiers. Actual capacity can vary. On Agent Platform, check your model and capacity setup in Google Cloud. Gemini rate limits · Google Cloud capacity and 429s.
  2. Reserve both a request and its estimated input tokens. Count the assembled prompt, including instructions and relevant context. Use the model’s token counter where appropriate. In a shared queue, check both minute allowances together before dispatch. One long prompt consumes the same request slot as a short one and more of the token allowance. For example, at an app limit of 60 RPM and 30,000 input TPM, 60 prompts averaging 500 tokens would use both allowances. Queue or reject work that exceeds either one. Apply the same checks to retries and background jobs. Gemini token counting.
  3. Smooth the start times of parallel calls. Set a short-window burst limit or minimum spacing across all workers that share the quota. A 100 ms gap permits up to about ten request starts a second. The minute and token limits still apply. Treat 100 ms as an example and tune it from observed results. Cap concurrent requests separately, because a slow response may leave many calls in flight. Keep deadlines on queued work and reserve room for interactive requests.
  4. Measure a practical operating limit. Use a controlled, cost-capped test with representative short and long prompts. Increase dispatch gradually while staying below published limits. Watch 429s, actual tokens per minute, queue waits, and end-to-end latency. Use the observed results to leave headroom for the model and tier you tested. A successful test measures available capacity at that time. Recheck after model or tier changes and slow dispatch when capacity falls. Google’s active limit and capacity guidance · Retry and resume.
Use Gemini Batch for work that can waitQueue jobs like tagging imported records or preparing content overnight.
  • Pick work without an immediate response. The Gemini Developer API documents Batch for generateContent, with a 24-hour target turnaround. Check the chosen model’s Batch rates and supported features. The Flash-Lite example uses half-price token rates. Check tools and cache storage separately. Gemini Batch API.
  • Count a submission once. Save your job ID before dispatch and record Google’s batch ID when it arrives. Google documents that submitting the same creation request twice creates two jobs. If you lose the response, check whether the job exists before sending another batch. Track results per item and retry only failed items when appropriate. Keep batches small enough to stay within your budget and recover without reprocessing everything.
Set Google billing safeguards and check their limitsUse provider controls as a second layer behind your backend’s usage limits.
  • Know which Gemini service you’re billing. The token examples use Gemini Developer API prices from Google AI Studio. If you call Gemini through Google Cloud’s Agent Platform, formerly Vertex AI, use that service’s pricing, quotas, and billing reports. Separate test and production projects so you can see what each one costs. Developer API billing · Google Cloud model pricing.
  • Check AI Studio caps and Prepay. Where available, set a monthly project spend cap. Google describes project caps as experimental and says billing can take around ten minutes to enforce them. Prepay can also overrun during that delay, especially for work already running. If you use auto-reload, check its separate monthly reload limit and test what users see when credits run out. AI Studio spend caps · Prepay and auto-reload.
  • Distinguish Cloud Billing alerts from spend caps. An alerts-only budget emails or notifies someone. A Cloud Billing spend cap budget can pause new usage for one eligible service in one project. Google lists the Gemini API and Agent Platform as eligible. Enforcement takes time, in-flight work can finish, and charges outside the cap’s scope can continue. Check which controls are available to your account and keep an application limit with headroom. Google Cloud budget alerts · Cloud Billing spend cap budgets.
  • Reconcile billable usage without storing prompts. Compare your totals with AI Studio Usage and Spend and Cloud Billing reports by project and SKU. Review data-use and retention terms for the chosen service and tier before sending user content. Keep only the diagnostic metadata you need. Gemini API billing reports · Gemini Developer API terms.