Edge-Native Digital Twin Portfolio Engine: Cloudflare Workers AI, Vectorize RAG & D1
Sub-40ms global TTFB, 816 code-preserving RAG chunks, stateful multi-model failover, and $0/mo serverless edge footprint.
“If you are an Agentic Infrastructure Architect, your public platform shouldn’t be a static brochure—the platform itself must be a live, observable, fault-tolerant distributed system.”
1. The Problem
Most engineering portfolios are static HTML templates or over-provisioned cloud VMs that either fail to demonstrate real systems engineering or incur $100+/month in idle compute, managed database, and vector-index bills.
To serve three distinct audiences simultaneously—executive hiring panels needing 30-second outcome verification, peer architects inspecting real BGP/Terraform/agentic implementations, and autonomous AI search crawlers ingesting structured context—we needed a Living Cognitive Platform (virtualsach.in) capable of running:
- A Real-Time Vector RAG Digital Twin grounded in 20 years of verified production case studies and 125+ engineering field notes.
- Interactive Systems & Outage Simulators (3 AM Incident Command, Multi-Agent Orchestration, BGP/NSX Topology Inspector, and Browser WebGPU Arena).
- An Anonymous Bidirectional Peer & Advisory Contact Gateway routing live messages directly to Telegram forum topics with persistent relational state.
2. The Constraints
- Zero Cold Starts &
<40msGlobal TTFB: Every static and dynamic route had to execute at the network edge across 300+ global PoPs without container spin-up delays. $0/MonthIdle Unit Economics: The entire stack—compute, relational SQL, key-value state, vector similarity search, and LLM inference—had to operate sustainably inside serverless edge bounds without idle VM or NAT gateway charges.- 100% First-Party Privacy & Zero Third-Party Trackers: No Google Analytics, no third-party tracking pixels, and no external cookie banners; all telemetry had to be self-hosted in edge SQLite (
Cloudflare D1). - Graceful Degradation Under Provider Rate Limits: If the primary edge LLM or Vectorize binding experienced rate-limiting or local-dev offline mode, the Digital Twin had to fail over transparently without throwing
HTTP 500errors.
3. Architecture & Key Decisions
We architected the platform on Astro v7 Hybrid SSR compiled to Cloudflare Workers, uniting five serverless edge primitives (Workers AI, Vectorize, D1 SQLite, Workers KV, and R2) with client-side WebGPU execution:
flowchart TB
subgraph Client["Client & Browser Runtime"]
UI["Astro v7 ViewTransitions UI<br/>+ Interactive Systems Lab"]
WebGPU["On-Device WebGPU Worker<br/>(FunctionGemma / Qwen / Whisper WASM)"]
UI <--> WebGPU
end
subgraph Edge["Cloudflare Global Edge Runtime (11ms Startup)"]
Worker["Cloudflare SSR Worker<br/>Rate Limiter & Security Middleware"]
KV["Workers KV<br/>(Circuit Breaker FSM & Hybrid Session Cache)"]
D1["Cloudflare D1 SQLite<br/>(Chat History, Guestbook, NOC Telemetry)"]
end
subgraph Cognitive["Cognitive & Retrieval Plane"]
Vec["Cloudflare Vectorize<br/>(384-d BGE Cosine Index · 816 Chunks)"]
LocalRAG["Deterministic Keyword/BM25 Fallback<br/>(Zero-Dependency Local Retriever)"]
AI["Workers AI Inference<br/>(Llama 3.3 70B FP8 → Llama 4 Scout → Llama 3.1 8B + BGE Reranker)"]
end
UI -->|"HTTPS / SSE Stream"| Worker
Worker <--> KV
Worker <--> D1
Worker -->|"1. Embed & Query"| Vec
Vec -.->|"Offline / Binding Fallback"| LocalRAG
Worker -->|"2. Stream Grounded Completion"| AI
Decision 1: Hybrid Two-Tier RAG (Cloudflare Vectorize + Deterministic Local Fallback)
Relying solely on an external vector database makes local CI/CD testing brittle and creates a single point of failure during vector-index maintenance. We built a compile-time knowledge pipeline (scripts/generate-rag-chunks.js) that chunks Case Studies and Field Notes into src/lib/ragKnowledgeBase.ts (816 code-preserving chunks / 1,200-char segments with fenced code retention).
At runtime, /api/chat queries Cloudflare Vectorize using @cf/baai/bge-small-en-v1.5 (384-dimensional embeddings) and automatically falls back to our in-worker lexical/era scorer if Vectorize is unreachable.
Decision 2: KV-Backed Circuit Breaker & Hybrid Cache-Aside State
To keep chat latency under 50ms and survive downstream model throttling, we combined a KV Cache-Aside Session Layer (30-minute TTL backed by D1 SQLite persistence) with a Stateful Circuit Breaker FSM:
// Edge Circuit Breaker with automatic model tier failover
export async function runWithFallback(
env: Env,
runInference: (model: string) => Promise<ReadableStream>,
) {
const cbState = (await env.KV?.get('circuit_breaker_state')) || 'CLOSED';
if (cbState === 'OPEN') {
return runInference('@cf/meta/llama-3-8b-instruct');
}
try {
return await runInference('@cf/meta/llama-3.1-8b-instruct-fast');
} catch (err) {
await env.KV?.put('circuit_breaker_state', 'OPEN', { expirationTtl: 300 });
return runInference('@cf/meta/llama-3-8b-instruct');
}
}
Decision 3: Machine-Readable Identity Layer (/llms.txt, /resume.json, JSON-LD)
Because AI recruiting agents and technical search engines parse structured schemas before rendering DOM elements, we exposed canonical machine-readable endpoints (/llms.txt, /resume.json, /api/profile.json, and Schema.org/Person JSON-LD) directly at the root edge.
4. Failure Modes & What Went Wrong
Incident 1: Main-Thread UI Freeze During Browser WebGPU Model Loading
- What Happened: When we first added client-side LLM inference (
SmolLM2/Qwen2.5/FunctionGemma) to the Systems Lab, loading quantized ONNX weights on the browser’s main UI thread froze scrolling and caused Chrome tab OOM crashes on mobile devices. - Root Cause: Shader compilation and tensor buffer allocation blocked the main JavaScript event loop.
- Architectural Fix: We isolated all
@huggingface/transformersand WebGPU execution inside dedicated background Web Workers, addednavigator.gpucapability pre-checks, and cached model shards in browserCacheStorage—restoring locked 60 FPS UI performance.
Incident 2: Duplicate Telegram Webhook Delivery Under Retry Jitter
- What Happened: When replying to anonymous recruiter messages from Telegram on a flaky mobile connection, Telegram’s webhook dispatcher occasionally delivered the same
update_idtwice, inserting duplicate replies into the D1 conversation thread. - Root Cause: Webhook handlers were not idempotent across edge PoP retries.
- Architectural Fix: We added an atomic KV Deduplication Gate (
tg_dedup:<update_id>with 24-hour TTL) at the top of/api/telegram-webhookplus a pre-push Docker Playwright E2E gate (36/36viewport & API tests) and154/154Vitest unit tests.
5. Measurable Outcomes
| Metric | Traditional Cloud VM Portfolio (Before) | Edge-Native Cognitive Platform (After) | Impact |
|---|---|---|---|
| Global Time-To-First-Byte (TTFB) | ~380ms (single-region origin VM) | <40ms globally (11ms Worker startup) |
9.5x faster edge response |
| RAG Knowledge Base Coverage | 21 static blog posts | 816 code-preserving chunks across 4 tracks | 100% grounded citations in AI Twin |
| Automated Verification Suite | Manual browser checks | 154 unit tests + 36 Docker E2E tests | Zero visual or API regressions |
| Monthly Infrastructure Cost | ~$85/mo (VM + Managed Postgres + Pinecone) | $0/month (Cloudflare Serverless Tier) | 100% opex elimination at 99.99% SLA |
6. First-Principles Takeaway
Constraint breeds architectural elegance.
Anyone can spin up a $500/month Kubernetes cluster and a managed vector database to host a personal website. Designing a globally distributed cognitive platform—complete with vector RAG, stateful circuit breakers, bidirectional messaging, and 190 automated unit/E2E tests—that boots in 11ms and runs for $0/month at the network edge forces you to respect memory bounds, caching hierarchy, and deterministic fallback paths at every layer.
Architecture and decisions: mine. Debugging sessions at odd hours: mine. AI assistance: structure, syntax, first draft. — Sachin
⚡ Challenge This Architecture Blueprint with Virtual Sachin (AI Digital Twin)
Stress-test the architectural decisions, failure modes, and operational trade-offs behind Edge-Native Digital Twin Portfolio Engine: Cloudflare Workers AI, Vectorize RAG & D1 directly against the edge-native RAG Digital Twin: