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 Preview (Beyond API / Google AI)
- Hidden Reasoning: Dynamic backend scaling (ThinkingBudget: -1)
- 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 an atomic OCC lock on the agent session before tool execution.
* 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-keyword">const quotaRef = db.collection("token_quotas").doc(userId);
"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 Streaming TCP chunk tear (Automatic client keep-alive retry)
"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://runtime.cloudrun.app/healthz"
"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.
Blocks unverified scripts and bots at the network edge via hardware-backed client attestation (Apple DeviceCheck or Android Play Integrity), ensuring only genuine client applications reach the execution gateway.
View Implementation Contract (TypeScript / Firestore Lock)↓
// Atomic Session Mutex in Cloud Run Worker
await db.runTransaction(async (transaction) => {
const sessionRef = db.collection("agent_sessions").doc(sessionId);
const session = await transaction.get(sessionRef);
if (session.data()?.status === "LOCKED") {
throw new Error("Concurrent mutation blocked: Session locked by active execution.");
}
// Acquire atomic lock before calling LLM tools
transaction.update(sessionRef, { status: "LOCKED", lockedAt: Date.now() });
});| 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 | Zero Risk (Optimistic concurrency control; serialized turns) | Full ACID single/multi-document | Zero Server Management (Serverless) |
03The 3-Layer AI Tokenomics Defense Blueprint
Cloud billing alerts arrive hours after a runaway prompt loop drains your budget. This 3-layer defense stack enforces edge attestation, atomic Firestore token buckets, and real-time circuit breakers.
Filters synthetic traffic, bot farms, and script scraping at the reverse proxy layer before invocation touches billable LLM tokens or Cloud Run compute instances.
View Implementation Contract (Per-User Token Bucket)↓
// Low-latency Ingress Token Bucket Check
const userRateRef = db.collection("token_limits").doc(userId);
const result = await db.runTransaction(async (tx) => {
const doc = await tx.get(userRateRef);
const currentTokens = doc.data()?.usedTokens || 0;
if (currentTokens + requestedTokens > DAILY_BUDGET) {
throw new Error("Quota exceeded: Token bucket exhausted for 24h window.");
}
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 (Edge token verification) | Requires client SDK integration; blocks synthetic scripts at the edge. |
| 2. Application Limit | Firestore atomic increment per-UID | ~15ms (Database transaction) | Adds small database lookup; prevents runaway recursive agent loops. |
| 3. Solvency Fuse | Google Cloud Billing Spend Cap | Asynchronous (15-45m metering lag) | Lag requires app-level limits, but acts as guaranteed insolvency cutoff. |
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; // Firestore OCC sequence number
trajectoryId: string; // Current agent conversation session
verifierCommand: string; // e.g. "node --check dist/index.js"
}
export function assertGateConformance(gate: EpistemicVerificationGate): boolean {
if (!gate.specHash || gate.stateVersion <= 0) {
throw new Error("Epistemic Gate Violation: Unanchored state detected.");
}
return true;
}| 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)↓
// API Gateway / Cloud Armor URL Route Map
// /api/v1/legacy/* -> Legacy Compute Engine Monolith (Pass-through)
// /api/v1/ai-copilot -> Cloud Run Stateful Sidecar (Firebase App Check Verified)
// Automatic fallback on 5xx to preserve monolithic uptime| 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 = AILogic.aiLogic()
let model = ai.generativeModel(modelName: "gemini-3.7-flash")
// Stream response with hardware Firebase App Check token attached automatically
let stream = 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 (Fully managed Google Cloud edge) |