# BankBot AI — System Architecture ## 1. High-Level Architecture ``` ┌─────────────────────────────────┐ │ CLIENT BROWSER │ │ Next.js 14 (React, TypeScript) │ │ │ │ Pages: │ │ / Dashboard │ │ /chat AI Assistant (WS) │ │ /analytics Spending Intel │ │ /simulator What-If Engine │ │ /transactions History │ │ /status Observability │ └──────────────┬───────────────────┘ │ HTTPS / WSS ┌──────────────▼───────────────────┐ │ NGINX REVERSE PROXY │ │ • TLS termination │ │ • Rate limiting (30r/m API) │ │ • Auth rate limit (10r/m) │ │ • WebSocket upgrade proxy │ │ • Static asset caching │ └──────────┬────────────┬──────────┘ │ │ ┌────────────────────▼──┐ ┌──────▼──────────────────┐ │ FastAPI Backend │ │ Next.js Standalone │ │ Python 3.11 │ │ Node.js 20 │ │ Uvicorn (2 workers) │ │ Port 3000 │ │ Port 8000 │ └──────────────────────────┘ │ │ │ Routers: │ │ /api/auth │ │ /api/dashboard │ │ /api/ai/* │ │ /api/ai/chat/ws (WS) │ │ /api/transactions │ │ /api/notifications │ │ /api/metrics │ └──────┬────────┬────────┘ │ │ ┌────────────▼──┐ ┌──▼──────────────┐ │ PostgreSQL 15 │ │ Redis 7 │ │ (Primary DB) │ │ (Cache Layer) │ │ │ │ │ │ Tables: │ │ Keys: │ │ users │ │ dashboard:* │ │ accounts │ │ ai:coaching:* │ │ transactions │ │ ai:behavior:* │ │ goals │ │ ai:twin:* │ │ investments │ │ ai:subs:* │ │ subscriptions │ │ │ │ notifications │ │ TTLs: │ │ fraud_logs │ │ dashboard: 2min │ │ ai_insights │ │ score: 10min │ │ analytics_ │ │ briefing: 1hr │ │ snapshots │ └──────────────────┘ └────────────────┘ │ ┌────────────▼──────────────────────────┐ │ AI ORCHESTRATION LAYER │ │ │ │ Priority Chain: │ │ 1. OpenAI (gpt-4o-mini) ← fastest │ │ ↓ if unavailable │ │ 2. Groq (llama-3.3-70b) ← free tier │ │ ↓ if unavailable │ │ 3. Ollama (llama3:latest) ← local │ │ ↓ if unavailable │ │ 4. Rule-based fallback ← always on │ │ │ │ Modules: │ │ • chat.py — contextual chat │ │ • coaching.py — health score │ │ • forecasting.py — balance prediction │ │ • simulation.py — what-if engine │ │ • fraud.py — anomaly detection │ │ • behavior.py — spending patterns │ │ • subscriptions.py — sub optimization │ └─────────────────────────────────────────┘ ``` --- ## 2. Data Flow — Dashboard Load ``` Browser Next.js FastAPI DB/Cache │ │ │ │ │── GET / │ │ │ │ │── fetch /api/ │ │ │ │ dashboard/ │ │ │ │ overview │ │ │ │ │── check cache ──► │ │ │ │◄── cache miss ── │ │ │ │── query accounts │ │ │ │── query txns │ │ │── JSON response ◄──│── query fraud │ │◄── render dashboard ──│ │── set cache(2min) │ │ │ │ │ │ [2nd request] │ │ │ │ │── fetch /api/ │ │ │ │ dashboard/ │ │ │ │ overview │ │ │ │ │── check cache ──► │ │ │ │◄── cache HIT ─── │ │◄── render (22ms) ─────│◄── JSON (22ms) ────│ │ ``` --- ## 3. Data Flow — WebSocket Chat ``` Browser FastAPI AI Backend │ │ │ │── WS connect ─────────► │ │◄── WS accepted ────────│ │ │ │ │ │── { type: "chat", │ │ │ message: "..." } ──►│ │ │ │── build context ──►│ │ │ (user profile, │ │ │ history, goals) │ │ │ │── stream tokens │◄── { type: "chat_start" } │ │◄── { type: "chat_chunk", content: "He" } │ │◄── { type: "chat_chunk", content: "re" } │ │◄── { type: "chat_chunk", content: " is" } │ │ ... (streaming) │ │◄── { type: "chat_end" } │ │ │ │ │── { type: "ping" } ───►│ (heartbeat 25s) │ │◄── { type: "pong" } ───│ │ ``` --- ## 4. AI Context Construction Every chat message is enriched with full user financial context: ```python system_prompt = f""" You are BankBot, an elite AI Financial Analyst. CURRENT USER PORTFOLIO: - Name: {user.name} - Financial Personality: {user.financial_personality} - Health Score: {score}/100 - Total Balance: ${total_balance:,.2f} - Accounts: {account_details} - Goals: {goals_details} - Investments: {investments_details} - Subscriptions: {subs_details} - Behavioral Insights: {behavior_insights} PRINCIPLES: 1. Never give generic advice — use real numbers 2. Respond like a Bloomberg Terminal analyst 3. Keep answers brief, actionable, financially meaningful """ ``` --- ## 5. Fraud Detection Algorithm ``` Transaction received │ ▼ ┌───────────────────────────────┐ │ Load last 30 transactions │ │ for this user │ └───────────────┬───────────────┘ │ ┌───────▼────────┐ │ Amount spike? │ > 3.5x avg → +40 pts │ │ > 2.0x avg → +20 pts └───────┬────────┘ │ ┌───────▼────────┐ │ Timing anomaly?│ 11PM–4AM → +25 pts └───────┬────────┘ │ ┌───────▼────────┐ │ Rapid fire? │ < 3 min gap → +20 pts └───────┬────────┘ │ ┌───────▼────────┐ │ Duplicate? │ Same merchant+amount │ │ within 10 min → +30 pts └───────┬────────┘ │ ┌───────▼────────┐ │ Score ≥ 30? │ → Log to fraud_logs │ Score ≥ 50? │ → Status: "flagged" │ Score < 30? │ → Status: "verified" └────────────────┘ ``` --- ## 6. Caching Strategy | Data | Cache Key | TTL | Reason | |------|-----------|-----|--------| | Dashboard overview | `dashboard:overview:{uid}` | 2 min | High-frequency, DB-heavy | | AI health score | `ai:coaching:score:{uid}` | 10 min | AI call expensive | | AI daily briefing | `ai:coaching:briefing:{uid}` | 1 hr | LLM cost control | | Behavior insights | `ai:behavior:insights:{uid}` | 10 min | Computation heavy | | Twin prediction | `ai:twin:predict:{uid}` | 5 min | Moderate cost | | Subscriptions | `ai:subs:optimize:{uid}` | 10 min | Stable data | Cache backend: Redis → in-memory dict fallback (automatic, no config needed). --- ## 7. Security Architecture ``` Request → Nginx (rate limit) → FastAPI middleware stack: 1. Rate limiter (120 req/min per IP) 2. Security headers (X-Frame-Options, CSP, etc.) 3. Request logger (structured JSON) 4. Process time header 5. CORS validation 6. Route handler └── JWT validation (if protected route) └── Business logic └── DB query / AI call / Cache lookup ``` **JWT Flow:** ``` Login → access_token (60min) + refresh_token (7 days) │ ▼ Request with Authorization: Bearer {access_token} │ ▼ Token expired? → POST /api/auth/refresh with refresh_token │ ▼ New access_token issued (refresh_token unchanged) │ ▼ Logout → client clears tokens (stateless) ``` --- ## 8. Deployment Architecture ``` Internet │ ▼ Cloudflare (DNS + DDoS protection) │ ▼ Nginx (SSL termination, rate limiting) │ ├──► Next.js Frontend (Vercel / Docker port 3000) │ └──► FastAPI Backend (Render / Docker port 8000) │ ├──► PostgreSQL (Render managed / Docker) ├──► Redis (Render managed / Docker) └──► AI Provider (OpenAI API / Groq API) ```