API Design Strategy
Architecture Overview
Our API design follows a clean separation of concerns, organizing functionality into decoupled APIs that are independent of UI logic. Reusable code is organized into Manager classes and scripts for maximum maintainability and scalability.
Core Design Principles
API-First Design
All functionality is exposed through well-defined APIs that are decoupled from UI components, enabling third-party integrations and SDK generation.
Manager Classes
Reusable business logic is encapsulated in Manager classes that handle specific domains like broadcasts, sessions, and user management.
Database-Driven Sessions
Real-time session management through database-backed services that track active sessions, user states, and broadcast metadata.
Database Configuration
DigitalOcean PostgreSQL Database
ubuntu-s-2vcpu-4gb-120gb-intel-nyc1-01
159.223.163.228
10.116.0.4
db-postgresql-nyc1-09356
postgresql://doadmin:AVNS_shh-nTuXPc-4auqvZT4@db-postgresql-nyc1-09356-do-user-10190096-0.d.db.ondigitalocean.com:25060/defaultdb?sslmode=require
Database Schema Requirements
A robust database layer is essential for managing real-time broadcast sessions and user interactions. The following tables support our core functionality:
Broadcast Sessions Table
CREATE TABLE broadcast_sessions ( id UUID PRIMARY KEY, title VARCHAR(255) NOT NULL, user_id UUID NOT NULL, status ENUM('active', 'paused', 'ended', 'private') DEFAULT 'active', visibility ENUM('public', 'private') DEFAULT 'public', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, started_at TIMESTAMP, ended_at TIMESTAMP, viewer_count INTEGER DEFAULT 0, max_viewers INTEGER DEFAULT 0, rtmp_url VARCHAR(500), hls_url VARCHAR(500), webrtc_endpoint VARCHAR(500), metadata JSONB, ai_intent VARCHAR(100), tags TEXT[], is_featured BOOLEAN DEFAULT FALSE );
Active Viewers Table
CREATE TABLE active_viewers ( id UUID PRIMARY KEY, session_id UUID REFERENCES broadcast_sessions(id), user_id UUID, joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_seen TIMESTAMP DEFAULT CURRENT_TIMESTAMP, user_agent TEXT, ip_address INET, is_authenticated BOOLEAN DEFAULT FALSE );
Session Events Table
CREATE TABLE session_events ( id UUID PRIMARY KEY, session_id UUID REFERENCES broadcast_sessions(id), event_type VARCHAR(50) NOT NULL, event_data JSONB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, user_id UUID, metadata JSONB );
New API Endpoints
Broadcast Management APIs
POST /api/broadcasts { "title": "My Live Stream", "visibility": "public", "ai_intent": "gaming", "tags": ["gaming", "live"], "max_viewers": 1000 }
GET /api/broadcasts/active ?visibility=public &limit=20 &offset=0 &sort=viewer_count
POST /api/broadcasts/:id/join { "user_id": "optional", "join_token": "optional" }
PATCH /api/broadcasts/:id { "status": "paused", "viewer_count": 150 }
Session Management APIs
GET /api/sessions/:id Response: { "id": "uuid", "title": "Stream Title", "user": "username", "viewer_count": 150, "started_at": "2024-01-01T10:00:00Z", "visibility": "public", "status": "active" }
GET /api/sessions/:id/analytics ?period=1h &metrics=viewer_count,engagement
Manager Classes Architecture
BroadcastManager
Handles all broadcast-related operations including session creation, status updates, viewer management, and real-time data synchronization.
class BroadcastManager { func createBroadcast(request: CreateBroadcastRequest) async throws -> Broadcast func updateBroadcastStatus(id: UUID, status: BroadcastStatus) async throws func getActiveBroadcasts(visibility: Visibility?) async throws -> [Broadcast] func joinBroadcast(id: UUID, user: User?) async throws -> JoinResponse func leaveBroadcast(id: UUID, userId: UUID) async throws func getBroadcastAnalytics(id: UUID) async throws -> Analytics func updateViewerCount(id: UUID, count: Int) async throws }
SessionManager
Manages real-time session data, user connections, and event tracking for comprehensive session monitoring and analytics.
class SessionManager { func trackUserJoin(sessionId: UUID, user: User) async throws func trackUserLeave(sessionId: UUID, userId: UUID) async throws func logSessionEvent(sessionId: UUID, event: SessionEvent) async throws func getSessionMetrics(sessionId: UUID) async throws -> SessionMetrics func updateSessionMetadata(sessionId: UUID, metadata: [String: Any]) async throws }
Web Components Integration
Active Sessions Component
A web component that displays and refreshes active broadcast sessions, allowing users to discover and join public streams in real-time.
<active-sessions refresh-interval="5000" max-sessions="20" show-viewer-count="true" show-duration="true" filter="public"> </active-sessions>
Home Page Integration
The home page will feature a live feed of active public broadcasts showing stream name, broadcaster, duration, viewer count, and join functionality.
- Stream title and thumbnail
- Broadcaster username
- Live duration timer
- Current viewer count
- Join/View button
- Category tags
- Auto-refresh every 5 seconds
- WebSocket for live updates
- Sort by viewer count
- Filter by category
- Search functionality
- Featured streams section
Implementation Roadmap
Phase 1: Core Infrastructure
- Database schema implementation (PostgreSQL)
- BroadcastManager and SessionManager classes
- Basic CRUD APIs for broadcasts and sessions
- Real-time viewer count tracking
Phase 2: Web Components
- Active sessions web component
- Home page integration with live feed
- Real-time updates via WebSocket
- Search and filtering capabilities
Phase 3: Advanced Features
- AI intent classification for broadcasts
- Advanced analytics and metrics
- Session event tracking and logging
- Performance optimization and caching
API Security & Performance
Authentication
- JWT tokens for API access
- Rate limiting per endpoint
- API key management
- User session validation
Performance
- Redis caching for active sessions
- Database indexing optimization
- Connection pooling
- CDN for static assets
Monitoring
- Real-time metrics collection
- Error tracking and alerting
- Performance monitoring
- Usage analytics