Architecture Overview
PianoRhythm Server is designed as a high-performance, real-time multiplayer gaming server built with modern Rust technologies. This document provides a comprehensive overview of the system architecture, design principles, and key components.
๐ฏ Design Principlesโ
Real-time Firstโ
- Low-latency communication through WebSocket connections
- Event-driven architecture for immediate response to user actions
- Optimized message serialization using Protocol Buffers
Scalabilityโ
- Horizontal scaling through stateless server instances
- Actor-based concurrency for efficient resource utilization
- Distributed state management using Redis clustering
Reliabilityโ
- Fault tolerance through supervisor patterns
- Graceful degradation when external services are unavailable
- Comprehensive error handling and recovery mechanisms
Performanceโ
- Zero-copy operations where possible
- Connection pooling for database and cache connections
- Efficient memory management with Rust's ownership system
๐๏ธ High-Level Architectureโ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Load Balancer โ โ Load Balancer โ โ Load Balancer โ
โ (Ingress) โ โ (Ingress) โ โ (Ingress) โ
โโโโโโโโโโโฌโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโ
โ โ โ
โผ โผ โผ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Server Instance โ โ Server Instance โ โ Server Instance โ
โ (Pod) โ โ (Pod) โ โ (Pod) โ
โโโโโโโโโโโฌโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโ
โ โ โ
โโโโโโโโโโโโฌโโโโโโโโโโโโดโโโโโโโโโโโฌโโโโโโโโโโโโ
โ โ
โผ โผ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ Redis Cluster โ โ MongoDB Cluster โ
โ (State/Cache) โ โ (Persistence) โ
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
๐ง Core Componentsโ
1. Web Server Layer (Actix Web)โ
- HTTP/HTTPS endpoints for REST API
- WebSocket upgrade handling for real-time connections
- Middleware stack for authentication, CORS, rate limiting
- Static file serving for assets and documentation
2. Actor System (Actix)โ
The server uses an actor-based architecture for concurrent processing:
Core Actorsโ
PianoRhythmState- Central state management actorUserManager- User session and authentication managementRoomManager- Room lifecycle and user assignmentConnectionManager- WebSocket connection handling
Specialized Actorsโ
AnalyticsTracker- Event tracking and metrics collectionUserStatsTracker- User statistics and achievementsSheetMusicStatsTracker- Music performance analyticsStatusPageMonitor- System health monitoringSentryActor- Error reporting and alertingSeqLoggerActor- Structured logging aggregation
3. State Management Layerโ
- Redis - Primary state store for real-time data
- MongoDB - Persistent storage for user data, rooms, and history
- In-memory caches - Hot data caching for performance
4. Communication Layerโ
- WebSocket Protocol - Real-time bidirectional communication
- Protocol Buffers - Efficient binary message serialization
- Redis Pub/Sub - Inter-server messaging for scaling
๐ Data Flow Architectureโ
Client Connection Flowโ
Client โ Load Balancer โ Server Instance โ WebSocket Handler โ Actor System
Message Processing Flowโ
WebSocket Message โ Deserialization โ Actor Routing โ Business Logic โ State Update โ Response
State Synchronization Flowโ
State Change โ Redis Update โ Pub/Sub Notification โ Other Instances โ Client Updates
๐ Security Architectureโ
Authentication Layerโ
- JWT tokens with Ed25519 signatures
- Session management with secure cookies
- OAuth2 integration for third-party authentication
Authorization Layerโ
- Role-based access control (RBAC)
- Resource-level permissions for rooms and features
- Rate limiting per user and endpoint
Data Protectionโ
- Input validation and sanitization
- SQL injection prevention through parameterized queries
- XSS protection through content security policies
๐ Performance Characteristicsโ
Concurrency Modelโ
- Async/await throughout the application
- Actor isolation prevents shared mutable state
- Connection pooling for database and Redis connections
Memory Managementโ
- Zero-copy operations for message passing
- Efficient serialization with Protocol Buffers
- Automatic memory management through Rust's ownership system
Scalability Metricsโ
- Horizontal scaling - Add more server instances
- Vertical scaling - Increase resources per instance
- Database scaling - MongoDB sharding and Redis clustering
๐ Event-Driven Architectureโ
Event Typesโ
- User Events - Login, logout, profile updates
- Room Events - Creation, updates, user joins/leaves
- Game Events - MIDI messages, chat messages, commands
- System Events - Health checks, metrics, alerts
Event Processingโ
- Event Reception - WebSocket or HTTP endpoint
- Validation - Input validation and authentication
- Actor Routing - Message sent to appropriate actor
- Business Logic - Event processing and state updates
- State Persistence - Updates saved to Redis/MongoDB
- Notification - Other clients notified of changes
๐ง Configuration Managementโ
Environment-Based Configurationโ
- Development - Local development settings
- Staging - Pre-production testing environment
- Production - Live production configuration
Configuration Sourcesโ
- Environment variables - Runtime configuration
- Configuration files - Static application settings
- Kubernetes ConfigMaps - Container orchestration config
- Kubernetes Secrets - Sensitive configuration data
๐ Monitoring and Observabilityโ
Metrics Collectionโ
- Prometheus metrics - Performance and business metrics
- Custom metrics - Application-specific measurements
- System metrics - CPU, memory, network usage
Logging Strategyโ
- Structured logging - JSON-formatted log entries
- Log levels - Debug, info, warn, error categorization
- Centralized logging - Seq aggregation and analysis
Error Trackingโ
- Sentry integration - Automatic error reporting
- Error context - Rich error information and stack traces
- Performance monitoring - Transaction tracing and profiling
๐ฎ Future Architecture Considerationsโ
Microservices Evolutionโ
- Service decomposition - Breaking monolith into services
- API gateway - Centralized API management
- Service mesh - Inter-service communication
Advanced Scalingโ
- Auto-scaling - Dynamic resource allocation
- Multi-region deployment - Global distribution
- Edge computing - Reduced latency through edge nodes
Technology Evolutionโ
- WebAssembly - Client-side performance improvements
- GraphQL - More flexible API queries
- Event sourcing - Complete event history tracking
This architecture provides a solid foundation for a scalable, real-time multiplayer gaming platform while maintaining flexibility for future enhancements and optimizations.