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.

Agent ArchitectureACID State Store

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.

Interactive topology explorerClick any layer to inspect failure domains
Layer 1
Client Ingress
App Check JWT Gate
Layer 2
Cloud Run Worker
SSE Streaming Gateway
Layer 3
Firestore Mutex
Leased Transactional Lock
Layer 4
Atomic Commit
Turn State Flush
Layer 1: Client Ingress & Firebase App CheckSLA: 401 Before Any DB Write

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.

Failure Strategy401 Immediate Drop
Isolation LevelWorker Middleware
Recovery SLAZero DB Mutation
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 ModelConcurrency SafetyACID GuaranteeOperational Overhead
Static Markdown FilesHigh Risk (Dual-write collisions; silent file overwrite)None (Eventual manual overwrite)Low (Local filesystem)
Vector-Only RAG RetrievalModerate (Stale embeddings; probabilistic similarity)None (Approximate recall)Moderate (Vector DB indexing)
Firestore Atomic TransactionsLow Risk (Firestore transaction: server SDKs lock the documents they read; contention retries)Full ACID single/multi-documentZero Server Management (Serverless)
Read full split-brain breakdown →
AI TokenomicsSolvency Stack

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.

Defense pipeline topologyClick layer to inspect protection mechanism
Defense 1
Firebase App Check
App Attestation Gate
Defense 2
Firestore Token Bucket
Per-User Atomic Quota
Defense 3
Firebase Spend Cap
Per-Service Pause
Defense 1: Firebase App Check AttestationSpeed: <5ms Middleware Check

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.

Defense TargetAutomated Bot Abuse
Latency Impact<5ms in Middleware
Account ProtectionNo LLM Spend on a 401
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 LayerMechanismLatency ImpactPrimary Trade-off
1. Ingress DefenseFirebase App Check attestation<5ms (Middleware token verification)Requires client SDK integration; rejects unattested scripts before the LLM call, but not all abuse.
2. Application LimitFirestore atomic increment per-UID~15ms (Database transaction)Adds small database lookup; prevents runaway recursive agent loops.
3. Solvency FuseFirebase spend cap (Preview): one service in one projectAsynchronous (enforcement can lag several minutes)Best-effort cutoff: overage during the lag is billed, so app-level limits still come first.
Read full tokenomics breakdown →
Context Grounding4-Plane Memory Guard

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.

4-plane grounding topologyClick plane to inspect verification role
Plane 1
Base Specs
Static Immutable Tree
Plane 2
Dynamic State
ACID Database Snapshot
Plane 3
Trajectory Log
Execution Transcript
Plane 4
Verifier Gate
POSIX Layer 3 Exit Check
Plane 1: Base Specs (Immutable Repository Anchor)Integrity: 100% Deterministic

Repository-anchored constraints, schemas, and API contracts (agents/spec/) that never mutate during runtime turns, preventing conversational goal drift.

Source of TruthVersion Controlled Spec
Mutation PolicyImmutable at Runtime
Verification ModeSchema Conformance
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 StrategyContext FreshnessHallucination ResistanceToken Efficiency
Prompt Injection OnlyDegrades after turn 3Low (Vulnerable to context drift)Poor (Redundant system prompts)
Standard Vector RAGProbabilistic recallModerate (Misses structured invariants)Moderate (Chunk retrieval overhead)
4-Plane Read-Time Fact CheckACID Real-time VerifiedMaximum (Gated by POSIX Layer 3)High (Context caching on Plane 1)
Read full document myopia analysis →
Brownfield ModernizationZero-Rewrite Sidecar

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.

Migration topologyClick layer to inspect routing logic
Layer 1
Edge URL Map
Cloud Armor Facade
Layer 2
AI Copilot Sidecar
Cloud Run Microservice
Layer 3
Identity Bridge
Firebase Auth State
Layer 1: Edge URL Map & Cloud Armor FacadeSLA: 99.99% Routing Uptime

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.

Rollback PathRepoint One Route
Monolith ImpactZero DB Modification
Cutover MechanismRoute-by-Route Ramp
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 PatternImplementation RiskProduction VelocityLegacy Scope of Impact
Greenfield Monolith RewriteHigh (Logic regression risks)Slow (6 to 12 months)Total (Entire system in flight)
Strangler Fig SidecarNear Zero (Isolated microservice)Fast (Deploy in days)Isolated to /ai/* endpoints
Mobile AIZero Idle Compute

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.

Direct inference pipelineClick node to inspect client attestation
NODE 1
Native App
Swift / Kotlin SDK
NODE 2
Hardware Attest
DeviceCheck / Play Integrity
NODE 3
Direct Inference
Gemini 3.7 Flash Stream
Node 1: Native Mobile Client (Swift / Kotlin)Compute Cost: $0 Idle

Directly invokes Gemini streaming APIs via Firebase AI Logic SDK with hardware-level cryptographic attestation attached automatically to each request.

Attestation EngineDeviceCheck / Play Integrity
Proxy InfrastructureNone (Zero-Proxy Direct)
First-Chunk LatencyDirect TCP to Gateway
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 OptionInfrastructure CostClient Security GuaranteeProxy Maintenance
Custom Proxy MicroserviceHigh (24/7 serverless runtime)Requires manual API key / JWT parsingHigh (Gateway ops and cert maintenance)
Firebase AI Logic + App Check$0 Idle compute (Direct SDK)Hardware-backed cryptographic attestationZero (Firebase enforces App Check for AI Logic)