# 02 System Architecture — InvestPlay ## Overview InvestPlay follows a **Microservices-oriented Monorepo** architecture. It relies on a multi-tenant, role-based backend (Node.js/NestJS), an API-first headless CMS for dynamic educational content, and a unified React frontend that compiles to Web, Mobile (Capacitor), and Desktop (Tauri). The system is designed for high scalability, B2B white-labeling, strict data isolation between institutions, and robust controls over third-party API costs (like AI). ## 1. Top-Level Architectural Pattern - **Monorepo Management:** Managed via `Turborepo` or `Nx` to share TypeScript interfaces, design tokens, UI components, and localization strings across all apps and services. - **Infrastructure:** Containerized via **Docker**. Deployable to AWS, GCP, or a dedicated VPS environment (e.g., Contabo) via Docker Compose or Kubernetes. - **Multi-Tenancy:** Schema-level or Row-Level Security (RLS) multi-tenancy. Every request is scoped to a `tenantId` to ensure institutional data isolation. ## 2. Frontend Layer (Client Apps) The frontend uses a "Write Once, Run Everywhere" strategy to minimize maintenance overhead while maximizing device reach. - **Core UI Framework:** **React** (Vite or Next.js) + **TypeScript** + **TailwindCSS**. - **Web App:** Standard SPA/SSR React application served via browser. - **Mobile App (iOS/Android):** Wrapped using **Capacitor**. Provides native device capabilities (push notifications, haptics, biometrics) using the web codebase. - **Desktop App (Windows/macOS/Linux):** Wrapped using **Tauri v2**. Rust-based, highly performant, and memory-efficient alternative to Electron. - **State Management:** `Zustand` for global state (auth, active tenant) and `React Query` / `Apollo Client` for server state and caching. - **UI Component Library:** Shared internal package built on `Radix UI` or `shadcn/ui` for accessible, headless components. ## 3. Backend Layer (Core API) The backend handles business logic, real-time simulation streaming, gamification rules, and AI proxying. - **Core Framework:** **Node.js with NestJS**. Enforces a strict, modular architecture. - **API Protocol:** **GraphQL** (Primary data fetching) and **REST** (Webhooks, third-party integrations). - **Real-Time Protocol:** **WebSockets (Socket.io)** used exclusively for real-time multiplayer classroom simulations, live leaderboards, and AI chat streaming. - **Background Workers:** **BullMQ** running on Redis for asynchronous tasks (e.g., end-of-day portfolio valuation, weekly email digests, analytics rollup, market tick generation). ### Key NestJS Modules - `AuthModule`: Handles JWT generation, SSO mapping, and role guards. - `TenantModule`: Manages institutional settings, white-label UI configs, and feature flags. - `CurriculumModule`: Interfaces with the Headless CMS to serve lessons and track student progress. - `SimulationModule`: The "Time Machine" engine. Broadcasts historical market ticks via WebSockets. - `PortfolioModule`: Executes virtual trades, calculates ROI, ESG scores, and risk metrics. - `AICoachModule`: The secure proxy for LLM requests (enforces token limits, prompt injection). ## 4. Data Layer - **Primary Database:** **PostgreSQL** accessed via **Prisma ORM**. Chosen for strict ACID compliance, relational integrity (essential for ledgers and transactions), and native JSON support (for flexible telemetry metadata). - **In-Memory Store / Cache:** **Redis**. Handles WebSocket state, active user sessions, API rate-limiting token buckets, and fast-read leaderboards (Sorted Sets). - **Blob Storage:** **S3-compatible storage** (AWS S3, Cloudflare R2, or MinIO). Stores user avatars, generated PDF reports, and downloaded CSV historical market data. ## 5. Content Layer (Headless CMS) Educational content must be separated from application code to allow non-technical curriculum designers to update lessons. - **CMS Engine:** **Strapi** or **Payload CMS**. - **Content Structure:** Lessons are built using a **Dynamic Block Model**. A lesson is a JSON array of components (e.g., `[ { type: 'Hero' }, { type: 'Text' }, { type: 'BudgetGame' }, { type: 'Quiz' } ]`). - **Localization:** Native i18n support at the CMS level. The frontend requests content using the `Accept-Language` header. ## 6. AI Integration & Cost Control Architecture The AI Coach is a metered, securely proxied service. **Client apps never communicate directly with OpenAI or Google Gemini.** - **Proxy Routing:** All chat requests hit the NestJS `AICoachModule`. - **Context Injection:** The backend intercepts the request, appends the user's current virtual portfolio state, recent mistakes, and the specific lesson context into the hidden System Prompt. - **Rate Limiting (Token Bucket algorithm via Redis):** - *User limit:* Max N requests per day. - *Tenant limit:* Max N tokens per month per school. - **Billing Strategy:** If a university exceeds its monthly quota, the backend returns a `429 Too Many Requests` or gracefully falls back to static hint systems, unless the institution provides their own API key (Bring-Your-Own-Key mode). ## 7. Third-Party Integrations - **Authentication & SSO:** **Clerk** or **Auth0**. Handles secure JWTs and provides out-of-the-box B2B SAML SSO (so universities can log in with their `.edu` Microsoft/Google accounts). - **Transactional Emails:** **Resend** using `React Email` for templating (Welcome emails, teacher invites, weekly progress reports). - **B2B Billing:** **Stripe Connect**. Manages institutional SaaS subscriptions (e.g., charging a school based on active student seats). - **Push Notifications:** **Firebase Cloud Messaging (FCM)** for iOS/Android alerts. - **Historical Market Data:** **Yahoo Finance (CSV exports)** or **Alpha Vantage (EOD APIs)** used asynchronously by background workers to seed "Blind Simulation" scenarios. ## 8. Security & Compliance - **No Real Money Connectivity:** The system explicitly lacks Plaid, Stripe (for B2C), or real brokerage API integrations for students. `Decimal` types in PostgreSQL represent isolated virtual currency. - **GDPR Compliance:** - Soft-delete functionality for all user data. - Telemetry and analytics data routed to institutional dashboards is aggregated. - Anonymization pipelines strip PII (Personal Identifiable Information) before data is exported for research purposes. - AI Prompt sanitization ensures no PII is sent to external LLM providers. - **API Security:** CORS whitelisting, helmet (HTTP headers), JWT payload verification, and GraphQL query depth limiting to prevent Denial of Service (DoS) attacks.