Architecture Overview

PadawanForge is a cognitive training game platform built with modern web technologies and deployed on Cloudflare’s edge infrastructure for optimal global performance.

System Architecture

High-Level Architecture

PadawanForge Platform
├── Frontend: Astro 5.10.1 + React 19 + Shadcn UI
├── Backend: Cloudflare Workers (Node.js Compatible)
├── Database: Cloudflare D1 (SQLite)
├── Real-time: Durable Objects (WebSocket)
├── Background: Cloudflare Workflows
├── AI: Cloudflare Workers AI
├── Storage: Cloudflare KV + R2
└── Auth: OAuth2 (Google, Discord)

Technology Stack

Frontend Technologies

  • Astro Framework 5.10.1: Static site generation with island architecture
  • React 19.0.0: Interactive components with concurrent features
  • Shadcn UI: Modern, accessible UI component library
  • Tailwind CSS 3.4.0: Utility-first CSS framework
  • TypeScript 5.x: Type-safe development across the stack

Backend Infrastructure

  • Cloudflare Workers: Serverless JavaScript runtime at the edge
  • Cloudflare D1: Distributed SQLite database
  • Cloudflare KV: Key-value storage for sessions and cache
  • Cloudflare R2: Object storage for static assets
  • Durable Objects: Stateful WebSocket connections for real-time features
  • Cloudflare Workflows: Long-running background processes

AI & Machine Learning

  • Cloudflare Workers AI: Edge-based AI inference
  • AutoRAG (AI Search): Managed RAG pipelines for NPC knowledge bases (Planned v1.4.0)
  • Multiple AI Models: Llama 3.1/3.2, DialoGPT, Mistral, Qwen, OpenChat
  • Adaptive Algorithms: Performance-based difficulty adjustment

Core Systems

Game Engine

The core game engine manages 7-minute cognitive training sessions with real-time scoring and progression tracking.

Session Management

interface GameSession {
  id: string;
  playerId: string;
  duration: 420; // 7 minutes in seconds
  statements: Statement[];
  responses: Response[];
  startTime: Date;
  endTime?: Date;
  score: number;
  streak: number;
  accuracy: number;
  workflowId?: string; // Cloudflare Workflow for background processing
}

Statement Generation

AI-powered content creation generates educational true/false statements:

  • Topics: History, Science, Mathematics, Literature, Philosophy
  • Difficulty Levels: Basic, Intermediate, Advanced
  • Quality Assurance: Factual accuracy and educational value validation
  • Model Selection: Adaptive model choice based on content type

Authentication System

Multi-provider OAuth2 authentication with connected accounts:

Supported Providers

  • Google OAuth 2.0: OpenID Connect with profile information
  • Discord OAuth 2.0: Standard OAuth flow with user data

Security Features

  • UUID-based Identity: Privacy-focused player identification
  • Session Management: Secure HTTP-only cookies with KV storage
  • CSRF Protection: State parameter validation
  • Account Linking: Multiple providers per account
  • Token Validation: Secure API token handling

Database Architecture

Segmented data architecture for performance and privacy:

Core Tables

  • players: Core identity and authentication
  • player_profiles: Display names and public information
  • player_preferences: Settings and UI preferences
  • player_game_data: Levels, experience, and achievements
  • player_personal_info: Private information with granular controls
  • npc_system_prompts: AI personality configurations
  • player_npc_inventory: User-created NPC configurations

Performance Optimizations

  • Targeted Indexes: Optimized for common query patterns
  • Foreign Key Integrity: Proper relationships with cascading deletes
  • View Abstractions: Simplified data access through views
  • Connection Pooling: Efficient database connection management

Real-time Features

WebSocket-based real-time communication through Durable Objects:

Chat System

  • Multi-room Support: Separate lobbies with player limits
  • Message Persistence: Chat history storage and retrieval
  • Moderation Tools: Content filtering and administrative controls
  • Connection Management: Automatic reconnection and error recovery

Live Updates

  • Player Status: Online/offline presence indicators
  • Game Progress: Real-time scoring and leaderboards
  • Notifications: Achievement unlocks and system messages
  • State Synchronization: Consistent state across all clients

AI Integration

Edge-based artificial intelligence for content generation and personalization:

Content Generation

  • Statement Creation: Topic-specific educational content
  • Difficulty Calibration: Performance-based content adjustment
  • Quality Validation: Automated fact-checking and clarity assessment
  • Model Optimization: Adaptive model selection for different tasks

Personalization

  • Adaptive Learning: Custom difficulty progression
  • Topic Recommendations: Performance-based suggestions
  • Virtual Tutors: AI personalities for guidance and motivation
  • Response Optimization: Context-aware AI responses

AutoRAG Knowledge Bases (Planned v1.4.0)

  • Semantic Retrieval: Vector-based search for NPC knowledge
  • Per-NPC Knowledge: Domain-specific knowledge bases per NPC
  • Automatic Indexing: Cloudflare manages embeddings and vector storage
  • Grounded Responses: Reduce hallucinations with retrieved context
  • Query Rewriting: Intelligent query improvement for better results

Background Processing

Cloudflare Workflows for long-running tasks:

Workflow Types

  • Player Workflows: Level progression, achievements, daily rewards
  • Session Management: Cleanup, analytics, data processing
  • AI Content Generation: Batch statement creation and validation
  • Notification Processing: Email and push notification delivery

Workflow Features

  • Reliable Execution: Automatic retry and error handling
  • State Persistence: Long-running state management
  • Integration: Seamless connection with Workers and Durable Objects
  • Cost Optimization: Efficient resource utilization

Data Flow

Request Processing

graph TD
    A[User Request] --> B[Cloudflare Edge]
    B --> C[Workers Runtime]
    C --> D{Request Type}
    D -->|API| E[API Handler]
    D -->|Static| F[Astro SSG]
    D -->|WebSocket| G[Durable Object]
    D -->|Background| H[Cloudflare Workflow]
    E --> I[D1 Database]
    E --> J[KV Storage]
    G --> K[Real-time State]
    F --> L[CDN Cache]
    H --> M[Long-running Tasks]

Game Session Flow

  1. Session Creation: Generate unique session with AI statements
  2. Player Interaction: Real-time response processing and scoring
  3. State Persistence: Continuous progress saving to D1 database
  4. Background Processing: Workflow execution for analytics and rewards
  5. Session Completion: Final scoring and experience point calculation
  6. Analytics Storage: Performance metrics for improvement tracking

Authentication Flow

  1. OAuth Initiation: Redirect to provider authorization
  2. Callback Processing: Exchange authorization code for tokens
  3. User Information: Fetch profile data from provider APIs
  4. Account Management: Create or link to existing account
  5. Session Creation: Generate secure session with KV storage
  6. Role Assignment: Assign appropriate user roles and permissions

Deployment Architecture

Edge Distribution

Cloudflare’s global network provides low-latency access:

  • 200+ Locations: Global edge presence for optimal performance
  • Automatic Scaling: Traffic-based resource allocation
  • DDoS Protection: Built-in security and availability
  • SSL/TLS: Automatic certificate management
  • Platform Proxy: Seamless local development experience

Environment Management

interface Environment {
  // Database connections
  DB: D1Database;
  SESSION: KVNamespace;
  FILES: R2Bucket;
  
  // AI and external services
  AI: Ai;
  
  // Durable Objects
  CHAT_LOBBY: DurableObjectNamespace;
  ROOM_MANAGER: DurableObjectNamespace;
  
  // Workflows
  PLAYER_WORKFLOW: WorkflowEntrypoint;
  
  // Configuration
  API_TOKEN: string;
  APP_NAME: string;
  
  // OAuth credentials
  OAUTH_GOOGLE_CLIENT_ID: string;
  OAUTH_GOOGLE_CLIENT_SECRET: string;
  OAUTH_DISCORD_CLIENT_ID: string;
  OAUTH_DISCORD_CLIENT_SECRET: string;
}

Production Configuration

  • Environment Variables: Secure secret management
  • Domain Management: Custom domain with SSL
  • Analytics: Request monitoring and performance tracking
  • Backup Systems: Automated data backup and recovery
  • Observability: Comprehensive logging and monitoring

Security Architecture

Data Protection

  • Encryption: TLS 1.3 for all communications
  • Input Validation: Comprehensive sanitization and validation
  • Output Encoding: XSS prevention through proper encoding
  • CSRF Protection: State tokens and same-site cookies
  • API Security: Token-based authentication and rate limiting

Access Control

  • Role-based Permissions: Granular administrative access
  • API Authentication: Token-based endpoint protection
  • Rate Limiting: Abuse prevention and resource protection
  • Audit Logging: Comprehensive action tracking
  • Session Security: Secure session management with KV storage

Privacy Controls

  • UUID Anonymization: Public identifiers protect user privacy
  • Granular Settings: Individual control over data visibility
  • Data Minimization: Collect only necessary information
  • Right to Deletion: Complete account and data removal
  • GDPR Compliance: Privacy-focused data handling

Performance Optimizations

Frontend Performance

  • Static Generation: Pre-built pages for optimal loading
  • Code Splitting: Lazy loading of JavaScript bundles
  • Asset Optimization: Compressed images and minified resources
  • Progressive Enhancement: Core functionality without JavaScript
  • Edge Caching: Automatic CDN distribution

Backend Performance

  • Edge Computing: Processing at Cloudflare’s edge locations
  • Database Optimization: Efficient queries and proper indexing
  • Caching Strategies: Multi-layer caching for frequently accessed data
  • Connection Pooling: Optimized database connection management
  • Workflow Optimization: Efficient background processing

Real-time Performance

  • WebSocket Optimization: Efficient message serialization
  • State Management: Minimal data transfer for updates
  • Connection Handling: Graceful reconnection and error recovery
  • Resource Cleanup: Automatic cleanup of inactive connections
  • Durable Object Scaling: Automatic scaling based on demand

Scalability Considerations

Horizontal Scaling

  • Stateless Workers: Automatic scaling based on traffic
  • Database Sharding: Regional data distribution for performance
  • CDN Distribution: Global content delivery network
  • Load Balancing: Automatic traffic distribution
  • Workflow Orchestration: Distributed background processing

Resource Management

  • Memory Optimization: Efficient data structures and garbage collection
  • CPU Utilization: Optimized algorithms and async processing
  • Storage Efficiency: Compressed data storage and archival strategies
  • Network Optimization: Minimized payload sizes and request counts
  • Cost Optimization: Efficient resource utilization

Monitoring and Alerting

  • Performance Metrics: Response times and throughput monitoring
  • Error Tracking: Comprehensive error logging and alerting
  • Resource Usage: CPU, memory, and storage utilization tracking
  • User Analytics: Engagement and performance metrics
  • Workflow Monitoring: Background task execution tracking

Future Scalability

  • Multi-region Deployment: Geographic distribution for performance
  • Advanced Caching: Intelligent caching strategies
  • AI Model Optimization: Model fine-tuning and optimization
  • Real-time Analytics: Live performance monitoring
  • Advanced Workflows: Complex orchestration patterns

This architecture provides PadawanForge with a robust, scalable, and performant foundation that leverages modern web technologies and Cloudflare’s edge infrastructure to deliver an optimal cognitive training experience to users worldwide. The integration of Cloudflare Workflows, enhanced AI capabilities, and improved development tooling ensures the platform can scale efficiently while maintaining high performance and reliability standards.

PadawanForge v1.4.1