GEMINI LABJP
NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20
Articles/API / SDK
API / SDK/2026-05-26Advanced

Coalescing Gemini API Requests with SSE Fan-out: Collapsing 100 Simultaneous Hits into a Single Call

How I rebuilt the post-push-notification thundering herd on a 50M-download wallpaper app into a Cloudflare Durable Objects coalescer with SSE fan-out, cutting Gemini API costs by 92% with 14 days of production telemetry.

Gemini API192architecture15Durable ObjectsSSEcost optimization8production140

Premium Article

I've been shipping indie apps since 2014, and the moment that still scares me most is the first ten seconds after a push notification goes out. A server that normally hums along at 5 requests per second gets hit with 800–1,200 simultaneous calls. Gemini API costs scale linearly, p99 latency easily blows past 9 seconds, and Crashlytics fills up with timeout reports.

After being burned by this "10-second cliff" too many times on a wallpaper app that now sits at over 50 million cumulative downloads, I rebuilt the post-notification path around request coalescing and SSE fan-out on Cloudflare Durable Objects. The new shape cut Gemini calls during the 10-second cliff to 1/12 and brought monthly API costs down by 92%. The code below is the version that ran in production for 14 consecutive days, cross-checked against Crashlytics and AdMob reports.

Why "just cache it" doesn't reach the problem

My first attempt was a KV-backed response cache keyed on a SHA-256 of the prompt, with a 5-minute TTL. That worked beautifully after minute 6. Inside the cliff, however, the problem isn't cache hits — it's the cache-miss thundering herd.

When a notification lands, 1,200 devices wake up at roughly the same instant and send the same prompt (today's recommended wallpaper, this week's themed bundle, etc.). The first request starts calling Gemini; the remaining 1,199 also see a cache miss and start calling Gemini in parallel. The cache isn't written until 1.5 seconds later, by which point 1,199 redundant requests have already been billed.

Coalescing patches exactly this gap. Inflight requests sharing the same prompt hash get folded into one Gemini call, and when the response arrives it fans out to every waiting requester. The idea is elementary, but in a production setting with Stripe webhooks and AdMob anomaly detection sharing the runtime, the design has five non-obvious decisions baked into it.

Decision 1: how to choose the coalescing key

My first prototype keyed on the SHA-256 of the full prompt. That maximizes coalescing in theory, but the moment per-user variables (locale, device language, last wallpaper viewed) sneak into the prompt, the miss rate explodes and most requests stop coalescing at all.

The pattern I ended up with is "template ID + shared variables" as the key, with per-user variables injected at a later layer. The prompt gets restructured like this:

type PromptSpec = {
  templateId: string;          // e.g. "daily-recommend-v3"
  sharedVars: Record<string, string>;  // e.g. { dayOfYear: "147", theme: "calm" }
  perUserVars: Record<string, string>; // e.g. { lastViewed: "wp-12345", locale: "ja-JP" }
};
 
async function coalesceKey(spec: PromptSpec): Promise<string> {
  const payload = JSON.stringify({
    t: spec.templateId,
    s: spec.sharedVars,
  });
  const buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(payload));
  return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, "0")).join("");
}

Per-user variables get appended to the prompt as a "reader profile" section, and Gemini is asked via structured output to return N candidates. Filtering and reordering happen per-user inside the Worker. That separation lifted the coalescing hit rate from 18% to 71% and actually shaved 80ms off p99 — the Worker-side filtering runs in parallel and is much cheaper than a redundant Gemini call.

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
Durable Object code that coalesces 100 simultaneous identical-prompt hits into one Gemini call (measured 12x cost reduction)
The coalescing key design used in the 50M-download wallpaper app, and why a 5-second TTL window beat a fixed 1-second one (80ms p99 swing)
Promotion strategy when the primary stream drops mid-flight, plus the SSE backfill implementation for reconnecting clients
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-07-02
Routing Between Local Gemma 4 and the Gemini API Cut My Bill from ¥32,000 to ¥9,000 — A Production Hybrid Router Design
How I cut a ¥32,000/month Gemini API bill to the ¥9,000 range with hybrid inference: routing design, a full Python router, production pitfalls, and how Gemma 4 arriving on the Gemini API in July 2026 changes the decision.
API / SDK2026-06-22
Gemini API on Google Cloud: Diagnosing Production Errors Layer by Layer
Systematically diagnose Gemini API errors in Google Cloud production environments. Covers IAM permissions, Vertex AI vs AI Studio, VPC Service Controls, quota management, service accounts, and multi-region failover with full code examples.
📚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 →