Hybrid AI on GCP: On-Device Gemini Nano, Cloud Run & BigQuery

Architecture Brief: Build privacy-first Hybrid AI on GCP with on-device Gemini Nano PII redaction, Cloud Run FastAPI, and partitioned BigQuery telemetry.

Why Two-Stage Hybrid Inference Beats Cloud-Only AI Architecture

Modern enterprise teams hiring an AI Application Engineer, GCP Professional Cloud Architect, or GCP Professional Data Engineer increasingly hit a hard architectural constraint: regulated workflows in Healthcare (PHI), FinTech (PCI/KYC), and enterprise SaaS contain sensitive personal identifiers that should never cross the public internet in raw form.

Instead of uploading raw customer documents or clinical notes directly to cloud LLMs, a clean two-stage hybrid pipeline executes Stage 1 PII scrubbing and structured JSON classification on-device (using Chrome's local Prompt API / Gemini Nano), verifies the boundary deterministically in application code, and streams Stage 2 deep reasoning over only the de-identified summary through Google Cloud and Cloud Run microservices.

Stage 1: On-Device Structured Redaction & Deterministic Regex Guardrails

Using hybrid inference modes (ONLY_ON_DEVICE and PREFER_ON_DEVICE with schema constraints), Stage 1 extracts structured findings and transcribes attached document images directly inside the browser. Before any Stage 2 cloud request or persistence occurs, deterministic TypeScript scrubbers re-verify zero leaks.

export async function consumeStreamWithTimeout(
  stream: AsyncIterable<{ text: () => string }>,
  chunkTimeoutMs: number,
  onChunk: (accumulated: string) => void
): Promise<string> {
  const iterator = stream[Symbol.asyncIterator]();
  let accumulated = "";
  try {
    while (true) {
      const nextPromise = iterator.next();
      void nextPromise.catch(() => undefined);
      let timerId: ReturnType<typeof setTimeout> | undefined;
      const step = await Promise.race([
        nextPromise,
        new Promise<never>((_, reject) => {
          timerId = setTimeout(() => reject(new Error("Stream inactivity timeout")), chunkTimeoutMs);
        }),
      ]).finally(() => { if (timerId !== undefined) clearTimeout(timerId); });
      if (step.done) break;
      const piece = step.value.text();
      if (piece) {
        accumulated += piece;
        onChunk(accumulated);
      }
    }
  } catch (err) {
    void Promise.resolve(iterator.return?.()).catch(() => undefined);
    throw err;
  }
  return accumulated;
}

Resilient Stage 2 Cloud Failover & Cloud Run / BigQuery Telemetry Pipeline

Real-world SSE streams occasionally stall mid-response or drop at chunk boundaries. Wrapping the stream consumer with a bounded chunk-inactivity watchdog lets the client cancel cleanly—preventing unhandled promise rejections—and seamlessly fall back to unchunked generation or secondary cloud models controlled via dynamic Remote Config flags.

On the GCP backend side, a Cloud Engineer and Backend Engineer can ingest anonymized Stage 1/Stage 2 latency, token-cost, and inference-source telemetry (ON_DEVICE vs IN_CLOUD) into a Cloud Run FastAPI service that streams rows directly into partitioned BigQuery tables using the Storage Write API—zero raw text, zero PII, full FinOps visibility.

from fastapi import FastAPI
from google.cloud import bigquery
from pydantic import BaseModel, Field

app = FastAPI()
bq_client = bigquery.Client()

class TelemetryEvent(BaseModel):
    inference_source: str = Field(pattern="^(ON_DEVICE|IN_CLOUD)$")
    model_used: str = Field(max_length=80)
    latency_ms: int = Field(ge=0, le=120_000)
    scrubbed_token_categories: int = Field(ge=0, le=50)

@app.post("/v1/telemetry/inference")
async def record_inference_metric(evt: TelemetryEvent) -> dict[str, str]:
    # Strictly de-identified quantitative metrics only
    errors = bq_client.insert_rows_json(
        "analytics_prod.hybrid_inference_metrics",
        [evt.model_dump()],
    )
    return {"status": "ok" if not errors else "retry_queued"}

Frequently Asked Questions: Hybrid AI on GCP

How does Stage 1 ensure zero personal data leaks before Stage 2 cloud synthesis?

Stage 1 runs structured extraction with explicit redaction rules on-device first, then passes the output through a deterministic client-side regex scrubber (enforceDeterministicRedaction) right before any Stage 2 cloud call so raw patient names, SSNs, phone numbers, emails, and addresses never leave browser memory.

What happens when a user loses internet connectivity during Stage 2 synthesis?

Routing Stage 2 with PREFER_IN_CLOUD combined with browser IndexedDB persistence ensures previously saved de-identified summaries stay readable offline and new synthesis requests fall back automatically to local on-device weights when downloaded.

Why pair BigQuery partitioned telemetry tables with Cloud Run FastAPI?

Cloud Run scales stateless Python and Go ingestion endpoints smoothly during traffic spikes while BigQuery partitioning by event date plus clustering on inference_source keeps operational FinOps dashboards sub-second at minimal storage cost.

How can I hire Aldian Fazrihady to architect a Hybrid AI or GCP system?

You can explore the role specialization guides for Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend Engineer, AI Application Engineer, and Full Stack Engineer, scan external coding deliverables with our Contagious Interview Safety Scanner, or book a sprint via the 1-Day Programming Service ($100 / Rp 1,000,000).


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 25+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs