Production AI Architecture Blueprints
Production reference architectures, interactive multi-layer topology explorers, live trade-off matrices, and deterministic agents/spec/ trees for AI-first applications. 6 blueprints.
01Deterministic Agent Runtime Blueprint: noVibes Spec Tree
Replacing non-deterministic prompt instructions with strict, compiler-enforced schema contracts. Select any specification below to inspect, copy, or download the exact runtime guarantees.
# Technical Stack & Constraints
- Model Tier: Gemini 3.7 Flash (Gemini Developer API)
- Hidden Reasoning: thinking_level left unset (Gemini 3 default: dynamic)
- Host Runtime: Google Cloud Run (Node.js 22 LTS / Containerized)
- Ingress Security: Firebase App Check (reCAPTCHA Enterprise / Play Integrity)
- Transactional State: Cloud Firestore with atomic multi-document transactions
- Tool Transport: Model Context Protocol (MCP) stateless over Cloud Run SSE
# System Architecture & Topology
1. Ingress Layer:
Client (Web/Mobile) ──[App Check Token]──> Cloud Run Ingress Gateway
2. State & Session Coordination:
Cloud Run ──[Single Source of Truth]──> Cloud Firestore (Transaction Lock)
3. Inference Execution:
Gateway ──[Streaming SSE]──> Gemini 3.7 Flash ──[Tool Call Schema]──> MCP Server
"tok-keyword">import { getFirestore, "tok-type">FieldValue } "tok-keyword">from "firebase-admin/firestore";
"tok-keyword">interface "tok-type">SessionLock {
lockedBy: "tok-type">string;
lockedAt: "tok-type">number;
status: "ACQUIRED" | "RELEASED";
turnCount: "tok-type">number;
}
"tok-comment">/**
* Acquires a leased lock on the agent session in a Firestore transaction before tool execution.
* Server SDKs lock the documents a transaction reads, so contending workers retry.
* Throws an error "tok-keyword">if another worker holds an active lock.
*/
"tok-keyword">export "tok-keyword">async "tok-keyword">function acquireSessionLock(
sessionId: "tok-type">string,
workerId: "tok-type">string
): "tok-type">Promise<"tok-type">void> {
"tok-keyword">const db = getFirestore();
"tok-keyword">const sessionRef = db.collection("agent_sessions").doc(sessionId);
"tok-keyword">await db.runTransaction("tok-keyword">async (transaction) => {
"tok-keyword">const snap = "tok-keyword">await transaction.get(sessionRef);
"tok-keyword">const data = snap.data() "tok-keyword">as "tok-type">SessionLock | "tok-type">undefined;
"tok-keyword">const now = Date.now();
"tok-keyword">const isLocked = data?.status === "ACQUIRED" && (now - data.lockedAt < 30_000);
"tok-keyword">if (isLocked && data?.lockedBy !== workerId) {
"tok-keyword">throw "tok-keyword">new Error(`Concurrent mutation blocked: Session ${sessionId} is locked by worker ${data.lockedBy}.`);
}
transaction.set(sessionRef, {
lockedBy: workerId,
lockedAt: now,
status: "ACQUIRED",
turnCount: "tok-type">FieldValue.increment(1)
}, { merge: true });
});
}
"tok-keyword">import { getFirestore, "tok-type">FieldValue } "tok-keyword">from "firebase-admin/firestore";
"tok-keyword">const DAILY_TOKEN_BUDGET = 250_000;
"tok-keyword">export "tok-keyword">async "tok-keyword">function verifyTokenBudget(
userId: "tok-type">string,
estimatedTokens: "tok-type">number
): "tok-type">Promise<{ allowed: "tok-type">boolean; remainingTokens: "tok-type">number }> {
"tok-keyword">const db = getFirestore();
"tok-comment">// One document per user per UTC day, so the daily budget refills at midnight UTC
"tok-keyword">const quotaRef = db.collection("token_quotas").doc(userId + "_" + "tok-keyword">new Date().toISOString().slice(0, 10));
"tok-keyword">return "tok-keyword">await db.runTransaction("tok-keyword">async (tx) => {
"tok-keyword">const snap = "tok-keyword">await tx.get(quotaRef);
"tok-keyword">const used = snap.data()?.usedTokens ?? 0;
"tok-keyword">if (used + estimatedTokens > DAILY_TOKEN_BUDGET) {
"tok-keyword">return { allowed: false, remainingTokens: Math.max(0, DAILY_TOKEN_BUDGET - used) };
}
tx.set(quotaRef, {
usedTokens: "tok-type">FieldValue.increment(estimatedTokens),
lastUpdated: Date.now()
}, { merge: true });
"tok-keyword">return { allowed: true, remainingTokens: DAILY_TOKEN_BUDGET - (used + estimatedTokens) };
});
}
# Backend API & Tool Handshake Contracts
- Endpoint: POST /api/v1/agent/deliberate
- Headers:
- X-Firebase-AppCheck: <JWT>
- Authorization: Bearer <ID_TOKEN>
- Error Handling Contract:
- 401: Invalid App Check Attestation (Abort immediately)
- 429: Token Burn Ceiling reached (Return cached summary)
- 503: Model temporarily overloaded (Retry with exponential backoff)
"tok-keyword">version: "1.0"
"tok-keyword">pipeline: "deterministic-agent-runtime"
"tok-keyword">verification_gates:
- stage: "01_syntax"
"tok-keyword"> command: "node --check dist/server.js"
"tok-keyword"> required: true
- stage: "02_contracts"
"tok-keyword"> command: "npm run test:contracts"
"tok-keyword"> required: true
- stage: "03_attestation"
"tok-keyword"> command: "curl -H &"tok-comment">#039;X-Firebase-AppCheck: token' https://SERVICE-PROJECT_NUMBER.REGION.run.app/health"
"tok-keyword"> required: true
- stage: "04_tokenomics_audit"
"tok-keyword"> command: "node scripts/verify-token-caps.mjs"
"tok-keyword"> required: true
02Transactional Memory and State Store Blueprint: Split-Brain Defense
Static markdown summaries inevitably drift from live database state during concurrent writes. This architecture enforces ACID transaction boundaries and atomic session mutex locks across multi-turn agent sidecars.
Rejects requests without a valid App Check token (Apple App Attest or DeviceCheck, Android Play Integrity) in the worker's middleware, before any Firestore read or LLM call. It attests the app, not the user, so user auth still sits behind it.
View Implementation Contract (TypeScript / Firestore Lock)↓
// Leased Session Mutex in Cloud Run Worker
const LEASE_MS = 30_000;
const owner = crypto.randomUUID();
const sessionRef = db.collection("agent_sessions").doc(sessionId);
// Acquire before calling LLM tools. Server SDK transactions lock the documents they read;
// contention retries the callback. set() with merge also creates a brand-new session.
await db.runTransaction(async (tx) => {
const lock = (await tx.get(sessionRef)).data();
if (lock?.status === "LOCKED" && (lock.leaseUntil?.toMillis() ?? 0) > Date.now()) {
throw new Error("Concurrent mutation blocked: Session locked by active execution.");
}
tx.set(sessionRef, { status: "LOCKED", owner, leaseUntil: Timestamp.fromMillis(Date.now() + LEASE_MS) }, { merge: true });
});
try {
// ...run the turn; renew leaseUntil if a turn can outlast LEASE_MS
} finally {
// Release only this owner's lease; an expired lease another worker took over stays theirs
await db.runTransaction(async (tx) => {
if ((await tx.get(sessionRef)).data()?.owner === owner) tx.update(sessionRef, { status: "IDLE" });
});
}| Memory Model | Concurrency Safety | ACID Guarantee | Operational Overhead |
|---|---|---|---|
| Static Markdown Files | High Risk (Dual-write collisions; silent file overwrite) | None (Eventual manual overwrite) | Low (Local filesystem) |
| Vector-Only RAG Retrieval | Moderate (Stale embeddings; probabilistic similarity) | None (Approximate recall) | Moderate (Vector DB indexing) |
| Firestore Atomic Transactions | Low Risk (Firestore transaction: server SDKs lock the documents they read; contention retries) | Full ACID single/multi-document | Zero Server Management (Serverless) |
03The 3-Layer AI Tokenomics Defense Blueprint
Cloud billing alerts can arrive hours after a runaway prompt loop drains your budget, and budget alerts don't pause anything. This 3-layer defense stack puts App Check attestation, atomic Firestore token buckets, and a best-effort Firebase spend cap in front of the bill.
Rejects requests without a valid App Check token before they spend LLM tokens. On your own Cloud Run backend your middleware verifies it inside the billed instance; for Firebase AI Logic, Firebase enforces it once enforcement is on. It stops some abuse, not all.
View Implementation Contract (Per-User Token Bucket)↓
// Low-latency Ingress Token Bucket Check
// One document per user per UTC day, so the budget refills at midnight UTC
const day = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
const userRateRef = db.collection("token_limits").doc(userId + "_" + day);
await db.runTransaction(async (tx) => {
const currentTokens = (await tx.get(userRateRef)).data()?.usedTokens ?? 0;
if (currentTokens + requestedTokens > DAILY_BUDGET) {
throw new Error("Quota exceeded: daily token budget exhausted until 00:00 UTC.");
}
tx.set(userRateRef, { usedTokens: FieldValue.increment(requestedTokens) }, { merge: true });
});| Defense Layer | Mechanism | Latency Impact | Primary Trade-off |
|---|---|---|---|
| 1. Ingress Defense | Firebase App Check attestation | <5ms (Middleware token verification) | Requires client SDK integration; rejects unattested scripts before the LLM call, but not all abuse. |
| 2. Application Limit | Firestore atomic increment per-UID | ~15ms (Database transaction) | Adds small database lookup; prevents runaway recursive agent loops. |
| 3. Solvency Fuse | Firebase spend cap (Preview): one service in one project | Asynchronous (enforcement can lag several minutes) | Best-effort cutoff: overage during the lag is billed, so app-level limits still come first. |
04Read-Time Fact Check Blueprint: 4-Plane Memory Guard
Relying on static RAG documentation blindfolds agents to live infrastructure drift. This 4-plane memory guard triangulates across living database state, runtime telemetry, and skeptical verification before tool execution.
Repository-anchored constraints, schemas, and API contracts (agents/spec/) that never mutate during runtime turns, preventing conversational goal drift.
View Implementation Contract (POSIX Verifier Gate Schema)↓
// Layer-3 POSIX Gate Verification Protocol
export interface EpistemicVerificationGate {
specHash: string; // Git commit hash of agents/spec/
stateVersion: number; // Version counter each Firestore transaction increments
trajectoryId: string; // Current agent conversation session
verifierArgv: string[]; // e.g. ["node", "--check", "dist/index.js"], run without a shell
}
export function assertGateConformance(gate: EpistemicVerificationGate): void {
if (!gate.specHash || gate.stateVersion <= 0 || gate.verifierArgv.length === 0) {
throw new Error("Epistemic Gate Violation: Unanchored state detected.");
}
}| Grounding Strategy | Context Freshness | Hallucination Resistance | Token Efficiency |
|---|---|---|---|
| Prompt Injection Only | Degrades after turn 3 | Low (Vulnerable to context drift) | Poor (Redundant system prompts) |
| Standard Vector RAG | Probabilistic recall | Moderate (Misses structured invariants) | Moderate (Chunk retrieval overhead) |
| 4-Plane Read-Time Fact Check | ACID Real-time Verified | Maximum (Gated by POSIX Layer 3) | High (Context caching on Plane 1) |
05The Strangler Fig Brownfield AI Blueprint
Rewriting enterprise monoliths to support generative AI introduces fatal regression risks. This edge-routing facade injects containerized Cloud Run sidecars incrementally with zero modifications to legacy databases.
Intercepts inbound traffic at the edge. Routes standard CRUD requests to the legacy monolith while cleanly directing AI copilot paths to containerized Cloud Run sidecars.
View Implementation Contract (Edge Facade Routing Map)↓
// External Application Load Balancer URL Map (Cloud Armor filters; the URL map routes)
// /api/v1/legacy/* -> Legacy Compute Engine Monolith (Pass-through)
// /ai/* -> Cloud Run AI Copilot Sidecar (verifies App Check in its middleware)
// A sidecar 5xx is not replayed to the monolith; roll back by repointing /ai/*| Architecture Pattern | Implementation Risk | Production Velocity | Legacy Scope of Impact |
|---|---|---|---|
| Greenfield Monolith Rewrite | High (Logic regression risks) | Slow (6 to 12 months) | Total (Entire system in flight) |
| Strangler Fig Sidecar | Near Zero (Isolated microservice) | Fast (Deploy in days) | Isolated to /ai/* endpoints |
06Zero-Backend Mobile AI Blueprint: Hardware Attestation with Firebase AI Logic
Routing mobile AI traffic through custom proxy servers doubles network latency and adds idle compute costs. This architecture streams responses directly from Gemini to Android and iOS apps secured by hardware App Check attestation.
Directly invokes Gemini streaming APIs via Firebase AI Logic SDK with hardware-level cryptographic attestation attached automatically to each request.
View Implementation Contract (Swift Direct Streaming)↓
// Direct iOS SDK Invocation via Firebase AI Logic
import FirebaseAILogic
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
let model = ai.generativeModel(modelName: "gemini-3.7-flash")
// With App Check configured, the SDK attaches its token; Firebase enforces it once enforcement is on
let stream = try model.generateContentStream("Analyze local system metrics...")
for try await chunk in stream {
print(chunk.text ?? "")
}| Architecture Option | Infrastructure Cost | Client Security Guarantee | Proxy Maintenance |
|---|---|---|---|
| Custom Proxy Microservice | High (24/7 serverless runtime) | Requires manual API key / JWT parsing | High (Gateway ops and cert maintenance) |
| Firebase AI Logic + App Check | $0 Idle compute (Direct SDK) | Hardware-backed cryptographic attestation | Zero (Firebase enforces App Check for AI Logic) |