RAG AI Edge Architecture — Full Edge-Computing & Cloudflare Partner Capabilities
Document version: 1.1 Purpose: Define architecture, feature modules, and phased roadmap for Full Edge-Computing RAG AI HR capabilities, assuming the same Cloudflare-friendly stack as Zuplo and Cloudflare. No code generation — planning and design scope only.
Prego RAG AI adopts a Full Edge-Computing model: no dependency on external regional servers; like Zuplo, auth, quota, vector search, LLM inference, and audit run on the Cloudflare global edge.
Principle
Description
Edge-first
API gateway, business logic, AI inference, and vector search all run inside the Cloudflare network.
Cloudflare-native
Workers, Workers AI, Vectorize, D1, R2, Zuplo (gateway) as first-class. Minimize external LLM API dependency (Phase 1 goal: remove).
Multi-tenancy
Tenant Key Management, Usage Quota, and namespace isolation enforced at the edge.
Compliance & security
Data retention, deletion, and audit design aligned to Singapore PDPA, SOC2, etc.
2. Core Component Design
2.1 ① Edge Orchestration (Zuplo + Workers)
Zuplo: API Gateway
Role
Detail
Tenant auth
Key Management — issue and validate API keys per tenant/consumer. Extend existing Prego–Zuplo integration (Frappe API Key registration) pattern.
AI usage limits
Usage Quota enforced at the edge. Daily/monthly AI call limits per tenant/plan; 429 or soft warning on excess. Zuplo Policy uses request count and KV or D1 aggregates.
Routing
Route RAG/AI endpoints (/ai/query, /ai/embed, /ai/guardrail) to Worker backends.
Workers: Business logic and AI pipeline
Role
Detail
HR workflow
Integrate with existing HR APIs (leave, attendance, policy). Fetch context (user role, department, permissions) from D1 for RAG responses.
AI prompt chaining
User query → (optional) Guardrail check → vector search for context → assemble prompt for LLM → (optional) Guardrail re-check → audit log. Multiple steps in one Worker or sub-requests.
Model calls
Workers AI (@cloudflare/workers-ai) for Llama 3, Mistral, etc. No external LLM API (Phase 1 goal).
User role, department, permissions. Filter “which documents can this user access?” for RAG.
Existing
Integrate with tenants_master, tenant_runtime. Extend with RAG tables (tenant_ai_settings, role_profiles, etc.).
R2: RAG source documents and lifecycle
Use
Content
Source storage
Uploaded policies, manuals (PDF/Office). Path e.g. rag-docs/{tenant_id}/{document_set_id}/{object_key}.
Lifecycle rules
R2 bucket Lifecycle for auto deletion. e.g. delete or archive after N days. PDPA retention compliance.
Access
Workers only. No direct client access. Tenant prefix isolation.
PDPA / compliance
Design includes procedures: on retention expiry or consent withdrawal, delete R2 objects, clear Vectorize namespace, delete D1 metadata for that tenant/document set. Align with existing “delete after transfer” and “Fail Sanely” policies.
3. Zuplo-Based Usage Limits and Metering & Billing
From a Global Principal Architect perspective: use Zuplo to measure Cloudflare RAG AI usage in real time and link to Stripe billing.
3.1 Principle: Edge-based usage tracking
Compute and record token usage at the gateway so every request is counted, without extra latency. No separate metering service; Zuplo Inbound/Outbound policies handle it.
3.2 Flow
Step
Owner
Content
1. Auth and quota (Pre-proc)
Zuplo
On request, get tenant_id from API Key/JWT. Look up remaining quota in D1 (or KV). Return 429 if over to avoid AI cost.
2. AI request/response
Workers AI
RAG answer. Response header or body includes token count from Workers AI (e.g. x-ai-usage-tokens or metadata).
3. Record usage (Post-proc)
Zuplo Custom Policy
Outbound policy intercepts response, extracts tokens. Async update D1 usage table and Stripe Usage-based Billing (subscription_items/.../usage_records). Use waitUntil (or Zuplo equivalent) so recording does not delay response.
3.3 Zuplo Custom Policy (implementation)
Place: Zuplo Inbound for tenant ID and quota check; Outbound for post-response usage recording. Or single Outbound: next() → get response → extract tokens → async record.
Code: This doc is planning only; implement using Zuplo Policy API, next(), waitUntil per official docs.
3.4 Billing scenarios and pricing
Tier
Billing model
Zuplo enforcement
Free / Basic
Hard quota (free allowance)
Zuplo returns 429 when over; block AI request.
Premium
Tiered pricing
Included usage up to limit; overage at $X per 1k tokens. Stripe Metered Billing via usage_records.
Enterprise
Volume discount
Lower unit at scale. Optional dedicated gateway or separate quota and Stripe Product/Price mapping.
3.5 Principal Architect notes (metering & billing)
Note
Content
Idempotency
Use idempotency_key when reporting to Stripe to avoid duplicate submissions (e.g. tenant_id + request_id + timestamp or Zuplo request ID).
Soft limit alert
At 80% / 90% usage, Zuplo Policy or separate Worker sends email/Slack. Advance warning to avoid surprise bills.
Caching
Use Zuplo Cache for same/similar questions to skip AI compute. Lower customer cost and improve Prego margin. Cache key includes tenant_id and question hash.
4. Vectorize & D1 Provisioning (Pulumi)
For Automated Provisioning (Cloudflare partnership): create Vectorize index, D1 database, and service token for Workers in the customer’s Cloudflare account in one go.
4.1 Goals and scope
Executor: Pulumi (TypeScript or Python). Input: customer Cloudflare Account ID; create resources in that account.
Multi-tenancy: Single index with namespace isolation, or (option) per-tenant index policy.
Outputs: D1 database_id, Vectorize index name, API Token (Secret) — for Zuplo or control module.
4.2 Resources to provision
Resource
Design
D1
Name e.g. prego_hr_master_db. Tenant metadata, AI settings, Role Profile. Integrate with existing Prego D1 schema or separate per customer.
Vectorize
Name e.g. prego-hr-knowledge-base. Preset: Workers AI–optimized (e.g. cf-baai-bge-small-en-v1.5). Dimensions from preset (e.g. 768). Use Namespace for Statutory/Company etc. in one index.
API token (service account)
For Workers to access D1, R2, Vectorize. Scopes: Workers R2 Storage Write, Workers Scripts Write, D1 Write (or minimal for those resources). Token value as Secret only (Pulumi pulumi.secret or equivalent).
4.3 Namespace isolation
Recommended: One Vectorize index with per-tenant namespace. Always pass tenant_id (namespace) on query/upsert for logical isolation without separate indexes.
Alternative: If enterprise demands a fully separate index per tenant, design option for Pulumi to create per-tenant Vectorize index; document cost/ops tradeoff.
4.4 Implementation and partner strategy
Item
Content
Zero-touch deployment
Customer enters Account ID (and if needed API Token) in Prego settings; Pulumi runs and within ~1 minute AI infra (D1, Vectorize, token) is set up in their account. Core to strong partner integration.
Privacy isolation
Vectorize by namespace or per-tenant index; D1 by tenant DB or row-level isolation. Ensures customer data is physically and logically separated.
Cost transparency
Resources live in customer’s Cloudflare account; Vectorize/D1/R2 appear on customer’s Cloudflare bill. Prego charges SaaS fee only.
4.5 Zuplo and Worker integration
Store provisioning outputs (D1 database_id, Vectorize index name) in Zuplo env or Control Plane D1. Worker reads them per request.
API Token injected at deploy via Wrangler Secret or Cloudflare env. Zuplo handles auth; Worker accesses D1/Vectorize directly.
5. RAG AI Enterprise Feature Modules
Package differentiated AI HR capabilities as a Cloudflare partner.
Module
Detail (enterprise grade)
Cloudflare tech
Statutory Guardrail
AI checks real-time for labour-law violations by country; flags user/admin or AI output.
Workers AI (Llama 3 / Mistral): classify and explain using regulation text + user input.
Document Intelligence
Answer from large policy docs immediately. Natural-language question → relevant chunks → summary/answer.
Vectorize (namespace=tenant): embed and similarity search. Workers AI: answer from context + query.
Privacy Masking
Before AI: de-identify NRIC/FIN etc. at the edge. Only masked text to AI and vector store.
Workers: regex/pattern for NRIC/FIN → mask (e.g. ***1234) before Workers AI/Vectorize.
Audit Logging
All AI Q&A and Guardrail results in immutable logs. Audit and compliance.
R2 (log prefix or bucket): JSON logs. Optional Logpush for long-term retention/analytics.
All modules run on edge orchestration: Zuplo auth and Quota → Worker pipeline: Guardrail / Document Intelligence / Privacy Masking / Audit.
6. Phased Roadmap (Phase 1–4)
6.1 Phase 1: Build (Wrangler & dev)
Goal
Content
Deploy standard
All RAG/AI code as modular architecture deployable with Wrangler. Workers, Workers AI, Vectorize, D1, R2 in Wrangler config.
Remove LLM dependency
Use @cloudflare/workers-ai only; no external LLM API. Llama 3, Mistral, etc.
Outputs
RAG Worker(s), Vectorize index and namespace policy, D1 schema extension, R2 bucket and Lifecycle draft, local/staging Wrangler dev. Details: rag-ai-phase1-implementation-plan.md.
6.2 Phase 2: Security & compliance
Goal
Content
PDPA, SOC2
Verify data deletion, access control, audit logic for Singapore PDPA and SOC2. Document and verify R2 Lifecycle, D1 delete, Vectorize namespace cleanup.
Architecture review
Review with Cloudflare security. Align edge data handling, key management, log retention.
R2 버킷 Lifecycle Rules로 자동 파기 설정. 예: 업로드 후 N일 경과 시 삭제 또는 아카이브. PDPA 보관 제한 준수.
접근 제어
Worker만 R2에 접근. 클라이언트 직접 접근 없음. 테넌트별 prefix로 격리.
PDPA·규제 연동
보관 기간 초과·동의 철회 시 해당 테넌트/문서 집합에 대한 R2 객체 삭제·Vectorize namespace 정리·D1 메타 삭제 절차를 설계에 포함.
기존 기획서의 “이관 후 삭제”“Fail Sanely” 정책과 정합성 유지.
3. Zuplo 기반 사용량 제한 및 메터링·빌링 (Metering & Billing)
Global Principal Architect 관점에서, Zuplo를 활용해 Cloudflare 기반 RAG AI 사용량을 실시간 측정하고 Stripe 청구와 연동하는 엔터프라이즈급 메터링·빌링 설계를 정의한다.
3.1 핵심 원칙: Edge-based Usage Tracking
모든 요청이 통과하는 게이트웨이 단계에서 토큰 사용량을 계산·기록함으로써, 추가 지연 없이 정확한 과금을 실현한다. 백엔드에 별도 메터링 서비스를 두지 않고 Zuplo의 Inbound/Outbound 정책으로 처리한다.
3.2 사용량 측정 플로우 (The Flow)
단계
담당
내용
1. 인증 및 할당량 확인 (Pre-proc)
Zuplo
요청 수신 시 API Key/JWT에서 tenant_id 추출. D1(또는 KV)에서 해당 테넌트의 남은 쿼터(Quota) 조회. 초과 시 즉시 429 반환하여 AI 호출 비용 발생 방지.
2. AI 요청 및 응답
Workers AI
RAG 답변 생성. 응답 헤더 또는 바디에 Workers AI가 제공하는 토큰 수(Token Count) 정보 포함. (예: x-ai-usage-tokens 또는 응답 메타데이터 필드.)
3. 사용량 기록 (Post-proc)
Zuplo Custom Policy
Outbound 정책에서 응답을 가로채, 토큰 정보 추출. 비동기로 D1 사용량 테이블 업데이트 및 Stripe Usage-based Billing API(subscription_items/.../usage_records)로 전송. 응답 반환 지연을 막기 위해 waitUntil(또는 Zuplo 동등 메커니즘)으로 기록을 백그라운드 처리.
3.3 Zuplo Custom Policy 설계 요건 (구현 시 참고)
위치: Zuplo Inbound 정책에서 테넌트 식별·쿼터 체크; Outbound 정책에서 응답 후 사용량 기록. 또는 단일 Outbound 정책에서 “next() 호출 → 응답 수신 → 토큰 추출 → 비동기 기록” 순서로 처리.
입력: 요청 시 request.user.data.tenantId(또는 Consumer 메타데이터)로 테넌트 확정.
기록 내용: tenant_id, 토큰 수, 타임스탬프. D1에는 일/월 누적 또는 row 추가; Stripe에는 quantity=tokens, timestamp, action=increment 전달.
코드: 본 문서는 기획만 포함. 실제 Policy 구현 시 Zuplo Policy API·next()·waitUntil 등 공식 문서 참조.
3.4 청구 시나리오 및 요금제 설계
요금제 단계
과금 모델 (Billing Model)
Zuplo 제어 방식 (Enforcement)
Free / Basic
Hard Quota (무료 제공량)
설정된 토큰 수 초과 시 Zuplo가 429 Too Many Requests 반환. AI 요청 자체를 차단.
Premium
Tiered Pricing
일정 사용량까지 포함, 초과분은 1,000 토큰당 $X 등 단가 과금. Stripe Metered Billing으로 usage_records 누적 후 청구서 반영.
Enterprise
Volume Discount
대량 사용 시 단가 인하. 필요 시 전용 게이트웨이 또는 별도 Quota 상한·Stripe Product/Price 매핑.
3.5 Principal Architect 제언 (메터링·빌링)
제언
내용
Idempotency (멱등성)
Stripe에 사용량을 리포트할 때 네트워크 오류로 중복 전송되지 않도록 idempotency_key 사용. 예: tenant_id + request_id + timestamp 또는 Zuplo 요청 ID.
Soft Limit Alert
사용량이 **80%·90%**에 도달했을 때 Zuplo Policy 또는 별도 Worker에서 이메일·Slack 알림. 고객이 예기치 않은 청구를 받지 않도록 사전 경고.
Caching
동일·유사 질문에 대해 Zuplo Cache를 활용해 AI 연산을 건너뛰도록 설계. 고객 비용 절감 및 Prego 이익률 개선. 캐시 키에 tenant_id·질문 해시 포함.
4. Vectorize·D1 환경 프로비저닝 (Pulumi)
Cloudflare 파트너십의 자동화된 프로비저닝(Automated Provisioning) 을 위해, 엔터프라이즈 고객의 Cloudflare 계정에 Vectorize 인덱스, D1 데이터베이스, 그리고 이를 제어할 Workers용 서비스 토큰을 한 번에 생성하는 설계를 정의한다.
4.1 목표 및 범위
실행 주체: Pulumi (TypeScript 또는 Python). 고객(파트너 연동 시)의 Cloudflare Account ID를 입력받아 해당 계정에 리소스 생성.
Multi-tenancy: 단일 인덱스 내 Namespace 격리 또는(선택) 테넌트별 인덱스 생성 정책을 반영.
산출물: D1 database_id, Vectorize index name, API Token(Secret) — Zuplo 또는 관리 모듈에서 참조.
4.2 프로비저닝 대상 리소스
리소스
설계 요건
D1 데이터베이스
이름 예: prego_hr_master_db. 테넌트 메타데이터·AI 설정·Role Profile 등 저장. 기존 Prego D1 스키마와 연동하거나 고객 전용 DB로 분리.
Vectorize 인덱스
이름 예: prego-hr-knowledge-base. Preset: Cloudflare Workers AI 최적화 모델(예: cf-baai-bge-small-en-v1.5). 차원은 preset에 따름(예: 768). Statutory(노동법)·Company(사내규정) 등은 Namespace로 구분하여 단일 인덱스에서 다중 용도 지원.
API 토큰 (서비스 계정)
Workers가 D1·R2·Vectorize에 접근하기 위한 API Token. 권한: Workers R2 Storage Write, Workers Scripts Write, D1 Write(또는 계정 내 해당 리소스에 대한 최소 권한). 생성된 토큰 값은 Secret으로만 전달(Pulumi pulumi.secret 또는 동등).
4.3 Namespace 격리 전략
권장: 하나의 Vectorize 인덱스에 테넌트별 namespace 할당. 쿼리·upsert 시 항상 해당 tenant_id(namespace)만 지정하여 물리적 격리 없이 논리적 완전 격리 보장.