●2.5 ROUTE — From today, 12/1, calls to gemini-2.5-pro and 2.5-flash are rerouted to newer models automatically●CLI 0.71.1 — Gemini CLI stable is still v0.71.1, with a 0.73 nightly published on 11/30●INTRO END — Introductory pricing for 3.8, 3.7 and 3.6 Flash ends on 12/31. 30 days left●VERTEX — Developers are asking how to run Gemini CLI with Vertex AI credentials●NEON — Gemini 4 Neon became generally available on 11/18 (paid tier only)●IMAGE TEXT — A new test shows text inside an image can sway Gemini's answer●2.5 ROUTE — From today, 12/1, calls to gemini-2.5-pro and 2.5-flash are rerouted to newer models automatically●CLI 0.71.1 — Gemini CLI stable is still v0.71.1, with a 0.73 nightly published on 11/30●INTRO END — Introductory pricing for 3.8, 3.7 and 3.6 Flash ends on 12/31. 30 days left●VERTEX — Developers are asking how to run Gemini CLI with Vertex AI credentials●NEON — Gemini 4 Neon became generally available on 11/18 (paid tier only)●IMAGE TEXT — A new test shows text inside an image can sway Gemini's answer
Gemini API Production Performance Tuning — Removing Latency, Throughput, and Cost Bottlenecks One at a Time
A rewritten guide to lowering Gemini API latency, throughput limits, and cost together, updated for the December 1 automatic reroute of the 2.5 models (3.5 Flash-Lite, 3.8 Flash, 4 Argon). Covers streaming retries that never duplicate output, choosing Standard, Flex, Priority, or Batch, break-even-based Context Caching, three-lane model routing, 429-aware flow control, and thinking_level, with runnable code and a symptom triage table.
I was reading the morning report for an overnight tagging run on my wallpaper app when all three problems showed up on the same screen: responses were slower, the bill was higher, and the log was full of 429s. I tried to fix everything at once. The day I added retries to the streaming path, I shipped a new bug — the same paragraph appeared twice on screen. The retry itself wasn't the problem. I was restarting the stream from the top without remembering what I had already sent.
This page is a rewrite of how I handle latency, throughput, and cost together, with runnable code and a triage table. Because the Gemini API starts automatically rerouting the 2.5 models on December 1, 2026, I've also updated every model name and price to what's current.
The one thing I'd like you to take away up front: you don't pick two of the three. You measure first, then remove one bottleneck at a time. The order below is measurement → perceived speed → pricing tiers → caching → model routing → flow control → thinking depth.
The Ground Rules as of November 2026 — The December 1 Reroute and the Model Table
The previous version of this article assumed gemini-2.5-flash and gemini-2.5-pro. According to the official deprecations page, starting December 1, 2026, gemini-2.5-pro is automatically routed to gemini-3.8-flash and gemini-2.5-flash to gemini-3.5-flash-lite, billed at the destination model's price. Your code keeps working, which is exactly why your measurements and invoice change without anyone noticing.
No explicit caching; temperature and friends are ignored
These are the values listed on the official Pricing page as of November 2026. Because two introductory-price deadlines fall a month apart, the gap between Argon and 3.8 Flash is widest in December. I keep my estimates split by month for that reason.
Every snippet in this article pulls model names from one module, so a reroute means editing one file.
# models.py — model names and prices live here only (as of 2026-11; check official Pricing)from datetime import dateLITE = "gemini-3.5-flash-lite" # classification, tagging, short summariesFLASH = "gemini-3.8-flash" # default: chat and most generationHEAVY = "gemini-4-argon" # long multi-step work and hard reasoning only# (date this price starts applying in my calculations, input, output) USD per 1M tokens, newest firstPRICES = { LITE: [(date(2026, 1, 1), 0.30, 2.50)], FLASH: [(date(2027, 1, 1), 1.50, 7.50), (date(2026, 9, 2), 0.75, 3.75)], HEAVY: [(date(2026, 12, 1), 4.00, 20.00), (date(2026, 1, 1), 2.00, 10.00)],}def price_on(model: str, day: date) -> tuple[float, float]: """Return the (input, output) price valid on that day. Unknown models raise.""" for start, inp, out in PRICES[model]: if day >= start: return inp, out raise KeyError(f"{model}: no price registered for {day}")
The KeyError is deliberate. An estimate that silently computes an unknown model at zero dollars is how an unnoticed loss begins.
Measure First — Break "Slow" Into Parts
"Slow" is never one thing. It splits into time to first token (TTFT), generation time, and time lost to retries. The old profiler counted stream chunks and called them tokens, which understated generation speed. The fixed version reads the real output token count from the final chunk's usage_metadata.
# profile.py — TTFT, total time, and output tokens/sec for one requestimport timefrom google import genaifrom models import LITE, FLASHclient = genai.Client() # reads GEMINI_API_KEY from the environmentdef profile_request(model: str, prompt: str) -> dict: t0 = time.perf_counter() ttft = None usage = None served = None for chunk in client.models.generate_content_stream(model=model, contents=prompt): if ttft is None and chunk.text: ttft = time.perf_counter() - t0 if chunk.usage_metadata: # totals arrive on the last chunk usage = chunk.usage_metadata served = getattr(chunk, "model_version", None) or served total = time.perf_counter() - t0 out_tokens = (usage.candidates_token_count or 0) if usage else 0 thoughts = (getattr(usage, "thoughts_token_count", 0) or 0) if usage else 0 gen = total - (ttft or total) return { "requested": model, "served": served, "ttft_s": round(ttft or -1, 3), "total_s": round(total, 3), "out_tokens": out_tokens, "thought_tokens": thoughts, "out_tok_per_s": round(out_tokens / gen, 1) if gen > 0 else None, }if __name__ == "__main__": for m in (LITE, FLASH): print(profile_request(m, "Write a Python binary search and explain its complexity in three lines."))
The output has this shape (the numbers vary a lot by environment and time of day, so I'm only showing the structure):
The point of this function is logging requested and served side by side. From December 1, any row that asked for gemini-2.5-flash will show a different served name, and the log itself tells you the day your baseline changed underneath you.
✦
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
✦The 12/1 reroute (2.5 Pro to 3.8 Flash, 2.5 Flash to 3.5 Flash-Lite), month-by-month prices, and a single models.py for every model name
✦Streaming retries that never resend delivered text, and batch calls that go back through the rate limiter on every retry
✦A seven-row triage table (symptom, cause, check, fix) and a one-line rule for picking Standard, Flex, Priority, or Batch
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.
Streaming for Perceived Speed — Retry Only When Nothing Has Been Sent
Perceived speed is set by TTFT more than total time. But as my opening mistake shows, if a stream drops mid-way and you restart from the beginning, the user sees the same text twice.
Before (old version), it retried unconditionally:
# Before (excerpt): restarts from the top even after yielding textfor attempt in range(max_retries + 1): try: async for chunk in await client.aio.models.generate_content_stream(...): yield chunk.text return except Exception: await asyncio.sleep(2 ** attempt) # <- already-sent text streams again
After, it branches on how much has gone out. If nothing was sent, it retries. If something was sent, it hands the decision back to the caller.
# stream.py — streaming that never shows the same text twiceimport asynciofrom google import genaifrom google.genai import errorsfrom models import FLASHclient = genai.Client()class StreamCut(Exception): """The stream broke after partial output. `sent` holds what was already delivered.""" def __init__(self, sent: str, cause: Exception): super().__init__(f"stream cut after {len(sent)} chars: {cause}") self.sent = sentRETRYABLE = (429, 500, 503, 504)async def safe_stream(prompt: str, model: str = FLASH, max_retries: int = 2): for attempt in range(max_retries + 1): sent = [] try: stream = await client.aio.models.generate_content_stream(model=model, contents=prompt) async for chunk in stream: if chunk.text: sent.append(chunk.text) yield chunk.text return except errors.APIError as e: if sent: # anything delivered? never resend raise StreamCut("".join(sent), e) from e if e.code not in RETRYABLE or attempt == max_retries: raise await asyncio.sleep(2 ** attempt)
When the UI catches StreamCut, it can show a "continue" button or send the delivered text back as context and ask for the rest. Which is cheaper comes down to paying for the delivered text again as input versus paying for a full regeneration. My rough rule: short answers restart, long answers continue.
Text that has reached the screen never reaches it twice. I design every retry path backwards from that sentence.
Choosing a Pricing Tier — Standard, Flex, Priority, Batch
Flex and Priority inference tiers arrived in the Gemini API in April 2026. On the official pricing table, Flex costs half of Standard, the same as Batch (I checked this on the 3.7 Flash and 3.8 Flash rows). Priority costs more than Standard and gets processed first when capacity is tight.
Tier
Price
How you wait
Good for
Standard
Baseline
Synchronous, normal latency
Chat where a person is waiting
Priority
Above Standard (check the multiplier on Pricing)
Synchronous, prioritized under load
Support flows that must not stall
Flex
Half of Standard
Synchronous, no latency guarantee
Background work that can wait minutes
Batch
Half of Standard
Asynchronous job, collect later
Large overnight runs
Here is the decision in one line: if a person is waiting, Standard; if it truly can't stall, Priority; if it can wait minutes, Flex; if tomorrow morning is fine, Batch. Flex and Batch cost the same, so the only difference is whether you want the result on the same connection.
The old version sent the tier through a custom HTTP header. I couldn't match that against the official instructions, so I removed it. Now tier selection lives in one function, and I copy the exact field name from the official Flex inference and Priority inference samples.
# tiers.py — the only place tiers are chosen. Copy the field name from the official sample into TIER_FIELD.from dataclasses import dataclassTIER_FIELD = None # the config field name shown in the official sample; None means send as Standard@dataclassclass Job: user_waiting: bool # is a person waiting on screen? must_not_fail: bool # would a slowdown under load hurt? deadline_s: int # seconds until the result is neededdef choose_tier(job: Job) -> str: if job.user_waiting: return "priority" if job.must_not_fail else "standard" if job.deadline_s >= 6 * 3600: return "batch" # tomorrow is fine -> hand it to the Batch API return "flex"def tier_config(tier: str) -> dict: """Extra keys for generate_content's config. Adds nothing while TIER_FIELD is unset.""" if tier in ("standard", "batch") or TIER_FIELD is None: return {} return {TIER_FIELD: tier}
With TIER_FIELD unset, everything goes out as Standard. That costs more, but it's safer than sending a field that doesn't exist. Give Flex calls their own client timeout. If you route background work to Flex while keeping your short chat timeout, you'll read "the cheaper tier fails more" when the real cause is your timeout.
Context Caching — Decide by Minimum Tokens and Call Frequency
The old "minimum 32,768 tokens" figure was outdated. As of September 2026, the official Context caching page lists 4,096 for 3.5–3.8 Flash and 3.1 Pro Preview, and 2,048 for the 2.5 models. On top of that, gemini-4-argon does not support explicit caching (cachedContents).
The other defect: the old get_or_create_cache promised to return None below break-even, but never called its own check. Its "characters ÷ 4" token estimate is also far off for Japanese text. The fixed version counts with count_tokens and only creates a cache when the math works.
# cache.py — explicit caching that refuses to create a losing cacheimport hashlibfrom google import genaifrom google.genai import typesfrom models import FLASH, HEAVYclient = genai.Client()MIN_TOKENS = {"gemini-3.8-flash": 4096} # models not listed default to the larger 4,096NO_EXPLICIT_CACHE = {HEAVY}def worth_caching(model: str, tokens: int, calls_per_hour: float, input_price: float, cached_price: float, storage_per_hour: float) -> bool: """Does hourly savings beat hourly storage? (all prices USD per 1M tokens)""" if model in NO_EXPLICIT_CACHE or tokens < MIN_TOKENS.get(model, 4096): return False saved = calls_per_hour * tokens * (input_price - cached_price) / 1e6 storage = tokens * storage_per_hour / 1e6 return saved > storage_registry: dict[str, str] = {}def get_cache(model: str, system_text: str, calls_per_hour: float, prices: dict) -> str | None: key = hashlib.sha256(f"{model}\n{system_text}".encode()).hexdigest()[:16] if key in _registry: return _registry[key] tokens = client.models.count_tokens(model=model, contents=system_text).total_tokens if not worth_caching(model, tokens, calls_per_hour, **prices): return None cache = client.caches.create( model=model, config=types.CreateCachedContentConfig( system_instruction=system_text, ttl="3600s", display_name=f"ctx-{key}"), ) _registry[key] = cache.name return cache.name
Pass today's input_price, cached_price, and storage_per_hour from the Pricing page in prices. I keep prices outside the function because break-even moves the day an introductory price ends.
Confirm it's working with usage_metadata.cached_content_token_count. If it keeps coming back 0, you're either under the minimum or calling a different model than the one the cache was built for. Automatic rerouting is very good at causing the second case, so look at the number at least once around December 1. I wrote more about keeping per-generation minimums in a lookup table in the caching strategy article.
Model Routing — Three Lanes, and Count the Misroutes
Sending everything to one model is like moving every parcel by truck. I run three lanes: Lite for classification and tagging, Flash for most work, Argon only for long multi-step tasks.
The old router had two defects. It checked context_tokens > 50000 first, so the > 100000 branch could never run. And its sample output (0.85) didn't match what the code actually computed (0.75). The fixed version checks the larger threshold first and also uses expected output length.
# router.py — three lanes, always returning the reasonimport refrom dataclasses import dataclassfrom models import LITE, FLASH, HEAVY@dataclassclass Route: model: str score: float reason: strHIGH = [r"(分析|比較|analy[sz]e|compare).*(詳細|detail)", r"(設計|design).*(システム|system)", r"(証明|prove|theorem)", r"(リファクタ|refactor)"]LOW = [r"(翻訳|translate|要約|summar)", r"(分類|classif|タグ|tag)", r"(整形|format|変換|convert)"]def route(prompt: str, context_tokens: int = 0, expected_out_tokens: int = 300) -> Route: score, why = 0.5, [] for p in HIGH: if re.search(p, prompt, re.I): score += 0.15; why.append(f"high:{p[:12]}") for p in LOW: if re.search(p, prompt, re.I): score -= 0.15; why.append(f"low:{p[:12]}") if context_tokens > 100_000: # check the larger threshold first score += 0.2; why.append("ctx>100k") elif context_tokens > 50_000: score += 0.1; why.append("ctx>50k") if expected_out_tokens > 800: score += 0.1; why.append("out>800") elif expected_out_tokens < 200: score -= 0.1; why.append("out<200") score = max(0.0, min(1.0, round(score, 2))) model = HEAVY if score >= 0.75 else LITE if score < 0.35 else FLASH return Route(model, score, ",".join(why) or "baseline")if __name__ == "__main__": print(route("Translate this into Japanese: Hello world", expected_out_tokens=50)) print(route("Analyze this microservice setup and give detailed improvements", context_tokens=80_000))
The second call lands exactly on the 0.75 threshold and goes to Argon. "Exactly on the line" is the trap: add or remove one signal and the request can end up in any of the three lanes. In the old version I typed the sample output by hand and published one that didn't match the code. Now I always run the example and paste the result, and I log the reason string so I can trace later why a request went where it did.
Once routing is live, count two things every week: the share of Lite/Flash requests that had to be redone, and the share of Argon requests where Flash would have produced the same result. If the first is high, lower the threshold. If the second is high, raise it.
Flow Control — Read 429 as "Slow Down," Not "Stop"
Rate limits apply per project, and the ceiling depends on your billing tier and the model. The specific RPM numbers in the old version had gone stale, so I removed them; the AI Studio rate-limit screen is the reliable place to see yours.
The old AdaptiveRateLimiter had two defects: a 429 retry skipped the limiter on the way back in, and a request that hit 429 three times in a row was left as None with no error.
# limiter.py — slow down on 429, recover gradually on successimport asyncio, timefrom collections import dequefrom google import genaifrom google.genai import errorsfrom models import LITEclient = genai.Client()class AdaptiveLimiter: def __init__(self, rpm: int, floor: int = 5): self.ceiling, self.rpm, self.floor = rpm, rpm, floor self._t: deque[float] = deque() self._lock = asyncio.Lock() async def acquire(self): while True: async with self._lock: now = time.monotonic() while self._t and now - self._t[0] > 60: self._t.popleft() if len(self._t) < self.rpm: self._t.append(now) return wait = 60 - (now - self._t[0]) + 0.05 await asyncio.sleep(wait) # release the lock before sleeping def on_429(self): self.rpm = max(self.floor, int(self.rpm * 0.7)) def on_success(self): self.rpm = min(self.ceiling, self.rpm + 1)async def run_batch(prompts: list[str], limiter: AdaptiveLimiter, model: str = LITE, concurrency: int = 8): sem = asyncio.Semaphore(concurrency) results: list[dict] = [{} for _ in prompts] async def one(i: int, p: str): async with sem: for attempt in range(4): await limiter.acquire() # go back through the limiter on every retry try: r = await client.aio.models.generate_content(model=model, contents=p) limiter.on_success() results[i] = {"ok": True, "text": r.text, "served": r.model_version} return except errors.APIError as e: if e.code == 429: limiter.on_429() elif e.code not in (500, 503, 504): results[i] = {"ok": False, "error": f"{e.code} {e.message}"} return await asyncio.sleep(2 ** attempt) results[i] = {"ok": False, "error": "retries exhausted"} # never leave it silently empty await asyncio.gather(*(one(i, p) for i, p in enumerate(prompts))) return results
Every result is either a success or a failure with a reason, because I once miscounted None rows in a morning tally. If your overnight volume is large, it's usually better to stop making synchronous calls altogether and move to the Batch API — half the price, and 429s stop being your problem.
Thinking Depth — On 3.8 Flash, Use thinking_level
The old version passed thinking_budget to gemini-2.5-pro and read usage_metadata.thinking_tokens. Neither applies now. The official 3.8 Flash migration checklist says to replace thinking_budget with the string-valued thinking_level, and to drop temperature, top_p, and top_k from the generation config (from 3.6 Flash onward, setting them doesn't change the result). Thought tokens are reported as thoughts_token_count.
# thinking.py — pick thinking depth per task and record what it usedfrom google import genaifrom google.genai import typesfrom models import FLASHclient = genai.Client()LEVEL = {"classify": "minimal", "summarize": "low", "code": "medium", "analysis": "high"}def generate(prompt: str, task: str) -> tuple[str, dict]: r = client.models.generate_content( model=FLASH, contents=prompt, config=types.GenerateContentConfig( thinking_config=types.ThinkingConfig(thinking_level=LEVEL.get(task, "low")), max_output_tokens=4096, # leave room so thinking doesn't eat the answer ), ) u = r.usage_metadata return r.text, { "task": task, "served": r.model_version, "in": u.prompt_token_count, "out": u.candidates_token_count, "thoughts": getattr(u, "thoughts_token_count", 0) or 0, }
Thought tokens are billed at the output rate. If a task's thoughts keeps exceeding out, there's room to drop its thinking_level one step and compare quality. Conversely, when the answer is cut off and finish_reason is MAX_TOKENS, thinking used up the output ceiling.
Monitoring — All Three Axes on One Line
Every function above returns requested, served, and token counts. Collect them in one place and read one line each morning.
# monitor.py — one record per request, plus a daily summaryimport jsonfrom collections import Counterfrom dataclasses import dataclass, asdictfrom datetime import datefrom models import price_on@dataclassclass Rec: requested: str served: str tier: str ttft_ms: float total_ms: float in_tokens: int cached_tokens: int out_tokens: int thought_tokens: int ok: boolTIER_MULT = {"standard": 1.0, "flex": 0.5, "batch": 0.5} # add priority after checking Pricingdef cost(r: Rec, day: date) -> float | None: if r.tier not in TIER_MULT: return None # never compute with a multiplier you don't know inp, out = price_on(r.served, day) # you're billed at the model that answered billable_in = r.in_tokens - r.cached_tokens return (billable_in * inp + (r.out_tokens + r.thought_tokens) * out) / 1e6 * TIER_MULT[r.tier]def summary(recs: list[Rec], day: date) -> dict: ok = [r for r in recs if r.ok] ttfts = sorted(r.ttft_ms for r in ok) p95 = ttfts[min(len(ttfts) - 1, int(len(ttfts) * 0.95))] if ttfts else None costs = [c for c in (cost(r, day) for r in recs) if c is not None] return { "requests": len(recs), "error_rate": round(1 - len(ok) / len(recs), 4) if recs else None, "p95_ttft_ms": p95, "cost_usd": round(sum(costs), 4), "uncosted": len(recs) - len(costs), "served": dict(Counter(r.served for r in recs)), # the old version never counted "rerouted": sum(r.requested != r.served for r in recs), "cache_hit_tokens": sum(r.cached_tokens for r in recs), }def append_jsonl(path: str, r: Rec): with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(asdict(r), ensure_ascii=False) + "\n")
The old model_distribution assigned 1 to every model instead of counting, which is why it's a Counter now. A non-zero uncosted means a model missing from the price table or a tier with an unknown multiplier slipped in. That field exists so I never fill an estimate with made-up numbers.
Triage: From Symptom to Cause
Symptom
Likely cause
How to check
Fix
Output style and the bill changed on 12/1
Automatic reroute of 2.5 models
Count rows where requested ≠ served
Update the model constants and re-baseline
Same text appears twice
Restarting a stream that already delivered output
Log delivered length right before a retry
Never resend after delivery; raise StreamCut
cached_content_token_count stays 0
Below the minimum, or calling a different model
Compare count_tokens and served
Consolidate the fixed prefix above 4,096, or drop the cache
Cache creation fails after moving to Argon
gemini-4-argon doesn't support explicit caching
Is the error raised by caches.create?
Let implicit caching handle Argon; keep explicit caches on Flash
Output still varies with low temperature
From 3.6 Flash on, the setting has no effect
Change the value and see if behavior moves
Constrain output with a JSON schema; remove the setting
More failures after switching to Flex
Still using the short chat timeout
Are the failures timeouts?
Give Flex its own timeout, or move to Batch
Answer cut off with MAX_TOKENS
Thinking consumed the output ceiling
Check thoughts_token_count
Lower thinking_level or raise max_output_tokens
Common Misconceptions
"A faster model lowers total cost." The unit price drops, but if redos go up, so does the bill. Routing can only be judged together with the redo rate.
"Temperature 0 makes answers consistent." From 3.6 Flash onward, the official migration guide deprecates temperature, and changing it doesn't change results. If you need consistency, fix the output shape with a schema, and if needed, run it twice and diff.
"Caching pays off for longer documents." Length doesn't decide it; how many times you call it while it's stored does. A long document you call a few times a day only piles up storage charges.
Where to Start
The order I actually followed was measurement → the streaming fix → output limits → routing → caching and pricing tiers. For the first week, install only monitor.py and collect data. Next, fix duplicate streaming and set max_output_tokens to the length you really need. I added routing and caching only after the records showed which tasks made up which share of the bill.
Early on, I tried too hard to ship caching and routing in the same week. I couldn't tell which one had helped, and it took two weeks of removing one and re-checking to find out. My rule now: change one variable at a time, and judge it on a week of records.
The Next Thing You'll Hit
Right after you set this up, the most likely snag is handling rows whose served changed with the December 1 reroute. I covered logging requested and served models side by side, and catching the day they diverge, in the requested-vs-served logging article. If you move heavy work to Argon, search your code first for explicit caching, temperature, small output limits, and short timeouts — the steps are in the pre-migration scan for gemini-4-argon. If you need to rethink the 429 ceiling itself, see the rate limiting and quota management guide.
If you can, run profile.py once today and save one line confirming that requested and served match. On the morning of December 1, that line becomes your point of comparison.
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.