Watch Together - Technical Specification
Overview
Section titled “Overview”Watch Together is a real-time collaborative video synchronization platform enabling multiple users to watch content from YouTube, Twitch, and 1800+ other sites simultaneously. The system prioritizes sub-second synchronization accuracy, robust error recovery, and a premium user experience.
System Architecture
Section titled “System Architecture”High-Level Architecture
Section titled “High-Level Architecture”┌─────────────────────────────────────────────────────────────────────────────┐│ User Browsers ││ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ││ │ User A │ │ User B │ │ User C │ │ Extension │ ││ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │└──────────┼────────────────┼────────────────┼────────────────┼───────────────┘ │ HTTPS │ HTTPS │ HTTPS │ HTTPS └────────────────┴────────────────┴────────────────┘ │┌───────────────────────────────────▼─────────────────────────────────────────┐│ Cloudflare (Optional) ││ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ││ │ Zero Trust │ │ Tunnel │ │ Caching │ ││ │ Authentication │ │ Connector │ │ (Optional) │ ││ └─────────────────┘ └─────────────────┘ └─────────────────┘ │└───────────────────────────────────┬─────────────────────────────────────────┘ │ HTTP┌───────────────────────────────────▼─────────────────────────────────────────┐│ Nginx Reverse Proxy ││ ┌────────────────┐ ┌────────────────┐ ┌────────────────────────┐ ││ │ /api/* │ │ /ws/* │ │ /* │ ││ │ REST + Proxy │ │ WebSocket │ │ Static/SSR Pages │ ││ └───────┬────────┘ └───────┬────────┘ └───────────┬────────────┘ │└───────────┼───────────────────┼───────────────────────┼─────────────────────┘ │ │ │┌───────────▼───────────────────▼───────────┐ ┌───────▼─────────────────────┐│ FastAPI Backend │ │ Next.js Frontend ││ ┌─────────────────────────────────────┐ │ │ ┌───────────────────────┐ ││ │ connection_manager.py │ │ │ │ App Router │ ││ │ • WebSocket room management │ │ │ │ • SSR pages │ ││ │ • Real-time sync state │ │ │ │ • Client components │ ││ │ • Heartbeat broadcasting │ │ │ └───────────────────────┘ ││ └─────────────────────────────────────┘ │ │ ┌───────────────────────┐ ││ ┌─────────────────────────────────────┐ │ │ │ Custom Player │ ││ │ main.py │ │ │ │ • useDashSync │ ││ │ • REST API endpoints │ │ │ │ • useHlsPlayer │ ││ │ • Video proxy (HLS/DASH) │ │ │ │ • useAudioNorm │ ││ │ • Cookie management │ │ │ └───────────────────────┘ ││ └─────────────────────────────────────┘ │ │ ┌───────────────────────┐ ││ ┌─────────────────────────────────────┐ │ │ │ useRoomSync │ ││ │ services/resolver.py │ │ │ │ • WebSocket client │ ││ │ • yt-dlp integration │ │ │ │ • State management │ ││ │ • Format selection │ │ │ └───────────────────────┘ ││ │ • Cookie fallback chain │ │ └─────────────────────────────┘│ └─────────────────────────────────────┘ │└───────────────────────────────────────────┘Container Architecture
Section titled “Container Architecture”services: frontend: # Next.js 16 + React 19 (internal port 3000, not exposed) backend: # FastAPI + yt-dlp (internal port 8000, not exposed) volumes: - ./data:/app/data bgutil: # PO token provider (internal port 4416, not exposed) proxy: # Nginx reverse proxy (port 80, only externally exposed port) ports: ["80:80"] tunnel: # Cloudflare Tunnel (optional)All container images are pinned to specific versions. Resource limits (memory + CPU) are configured for each service. Only the nginx proxy port is exposed to the host network.
Core Components
Section titled “Core Components”1. Video Resolution Engine
Section titled “1. Video Resolution Engine”The backend uses yt-dlp with a multi-pass cookie strategy to maximize video access.
┌─────────────────────────────────────────────────────────────────┐│ Resolution Flow │├─────────────────────────────────────────────────────────────────┤│ 1. Check format cache (2-hour TTL) ││ ├── HIT: Return cached manifest URLs ││ └── MISS: Continue to resolution ││ ││ 2. Whose cookies (memory-only, from the extension): ││ ├── a) Requester's, if they cover the site ││ ├── b) A connected room member's — allowlisted sites, ││ │ single-video pages only (YouTube, Twitch, Kick) ││ └── c) None ││ ││ 3. yt-dlp extraction: ││ ├── Format: bestvideo*+bestaudio/best ││ ├── PO Token: bgutil-ytdlp-pot-provider ││ └── JS Runtime: Node.js for challenges ││ ││ 4. Stream type detection: ││ ├── DASH: Separate video + audio URLs ││ ├── HLS: Single manifest URL ││ └── Direct: Progressive download URL │└─────────────────────────────────────────────────────────────────┘2. Synchronization Engine
Section titled “2. Synchronization Engine”Real-time sync uses WebSockets with intelligent drift correction.
┌─────────────────────────────────────────────────────────────────┐│ Sync Protocol │├─────────────────────────────────────────────────────────────────┤│ Server → Client (every 5 seconds): ││ { ││ "type": "heartbeat", ││ "timestamp": 125.43, // Authoritative position ││ "is_playing": true, ││ "server_time": 1704567890 // For latency calculation ││ } ││ ││ Client drift correction: ││ ┌─────────────────────────────────────────────────────────────┐││ │ drift = client_time - server_time │││ │ │││ │ if |drift| > 3.0s: │││ │ → Hard seek to server_time │││ │ elif |drift| > 0.5s: │││ │ → Adjust playbackRate (0.95x or 1.05x) │││ │ else: │││ │ → Normal playback (1.0x) │││ └─────────────────────────────────────────────────────────────┘││ ││ Client → Server (on user action): ││ { ││ "type": "seek" | "play" | "pause", ││ "timestamp": 90.0 ││ } │└─────────────────────────────────────────────────────────────────┘3. DASH A/V Synchronization
Section titled “3. DASH A/V Synchronization”For separate video/audio streams, the useDashSync hook maintains sync.
┌─────────────────────────────────────────────────────────────────┐│ DASH Sync Loop (4Hz) │├─────────────────────────────────────────────────────────────────┤│ 1. Buffer monitoring: ││ ├── videoBuffer = video.buffered.end - video.currentTime ││ ├── audioBuffer = audio.buffered.end - audio.currentTime ││ └── if min(buffer) < 0.8s → Pause audio preemptively ││ ││ 2. A/V drift calculation: ││ drift = audio.currentTime - video.currentTime ││ ││ 3. Correction: ││ ├── |drift| > 2.0s → Emergency sync (bypass cooldown) ││ ├── |drift| > 0.8s → Heavy sync (pause, seek, resume) ││ ├── |drift| > 0.2s → Rate adjustment (0.97x or 1.03x) ││ └── |drift| < 0.2s → Normal (1.0x) ││ ││ 4. Recovery: ││ ├── Buffer recovered (>1.5s) → Resume audio ││ ├── Audio stopped unexpectedly → Restart audio ││ └── Tab visibility change → Re-sync on return │└─────────────────────────────────────────────────────────────────┘4. Proxy & Caching
Section titled “4. Proxy & Caching”The video proxy handles CORS bypass and implements multi-tier caching.
┌─────────────────────────────────────────────────────────────────┐│ Proxy Architecture │├─────────────────────────────────────────────────────────────────┤│ Request: /api/proxy?url=<encoded_url> ││ ││ 1. Manifest handling: ││ ├── Detect .m3u8/.mpd by extension or content-type ││ ├── Rewrite all URLs to /api/proxy?url=... ││ └── Return with appropriate MIME type ││ ││ 2. Segment caching (3-tier): ││ ┌───────────────────────────────────────────────────────┐ ││ │ L1: Memory Cache (LRU) │ ││ │ • Segments < 25MB │ ││ │ • Audio: 500 entries, Video: 200 entries │ ││ │ • Adaptive TTL based on access frequency │ ││ ├───────────────────────────────────────────────────────┤ ││ │ L2: Disk Bucket Cache │ ││ │ • 10MB buckets for position-aware caching │ ││ │ • Enables efficient seeking │ ││ │ • Max 50GB total size │ ││ ├───────────────────────────────────────────────────────┤ ││ │ L3: Upstream (YouTube/Twitch CDN) │ ││ │ • Passthrough with Range header support │ ││ │ • Streaming response (no buffering) │ ││ └───────────────────────────────────────────────────────┘ ││ ││ 3. Response headers: ││ ├── Access-Control-Allow-Origin: (configured via env) ││ ├── Accept-Ranges: bytes ││ ├── Content-Range: bytes x-y/total ││ └── Connection: close (HTTP/2 compatibility) │└─────────────────────────────────────────────────────────────────┘Technical Stack
Section titled “Technical Stack”Frontend
Section titled “Frontend”| Component | Technology | Purpose |
|---|---|---|
| Framework | Next.js 16 | App Router, SSR |
| UI Library | React 19 | Components, hooks |
| Styling | TailwindCSS 4 | Utility-first CSS |
| Player | hls.js | HLS streaming |
| DnD | @dnd-kit | Drag-and-drop queue |
| Icons | Lucide React | Icon set |
Backend
Section titled “Backend”| Component | Technology | Purpose |
|---|---|---|
| Framework | FastAPI | Async REST API |
| Python | 3.11+ | Runtime |
| Video | yt-dlp | Video resolution |
| PO Token | bgutil-ytdlp-pot-provider | YouTube auth |
| Database | aiosqlite | Async SQLite |
| HTTP | httpx | Async HTTP client |
| WebSocket | websockets | Real-time communication |
Infrastructure
Section titled “Infrastructure”| Component | Technology | Purpose |
|---|---|---|
| Container | Docker Compose | Orchestration |
| Proxy | Nginx | Reverse proxy, routing |
| Tunnel | Cloudflare | Secure external access |
| Auth | Cloudflare Zero Trust | User authentication |
Data Models
Section titled “Data Models”Room State
Section titled “Room State”interface Room { id: string; members: { [email: string]: { name: string; is_guest: boolean; joined_at: string; } }; queue: QueueItem[]; current_video: VideoState | null; is_playing: boolean; timestamp: number; last_active: string;}
interface QueueItem { id: string; url: string; title: string; thumbnail: string; duration: number; added_by: string; added_at: string;}
interface VideoState { url: string; title: string; thumbnail: string; stream_type: 'hls' | 'dash' | 'direct'; video_url?: string; // DASH only audio_url?: string; // DASH only qualities: QualityOption[];}WebSocket Messages
Section titled “WebSocket Messages”// Client → Servertype ClientMessage = | { type: 'play'; timestamp: number } | { type: 'pause'; timestamp: number } | { type: 'seek'; timestamp: number } | { type: 'queue_add'; url: string } | { type: 'queue_remove'; item_id: string } | { type: 'queue_reorder'; queue: string[] } | { type: 'queue_play'; item_id: string } | { type: 'pong' };
// Server → Clienttype ServerMessage = | { type: 'room_state'; room: Room } | { type: 'heartbeat'; timestamp: number; is_playing: boolean } | { type: 'play'; timestamp: number; by: string } | { type: 'pause'; timestamp: number; by: string } | { type: 'seek'; timestamp: number; by: string } | { type: 'set_video'; video: VideoState } | { type: 'queue_update'; queue: QueueItem[] } | { type: 'member_joined' | 'member_left'; email: string } | { type: 'ping' } | { type: 'error'; message: string };API Endpoints
Section titled “API Endpoints”REST API
Section titled “REST API”| Endpoint | Method | Description |
|---|---|---|
/api/resolve |
POST | Resolve video URL to streams |
/api/proxy |
GET | Proxy video segments |
/api/rooms |
GET | List active rooms |
/api/rooms/{id} |
GET | Get room details |
/api/cookies |
GET | Whether the server holds the user’s cookies, and until when |
/api/cookies |
DELETE | Drop the user’s cookies from memory now |
/api/extension/sync |
POST | Extension delivers cookies (bearer token) |
/api/extension/download/{browser} |
GET | Packaged extension build (chrome, firefox) |
WebSocket
Section titled “WebSocket”| Endpoint | Description |
|---|---|
/ws/{room_id} |
Room synchronization |
/ws/share/{room_id}?role=publisher |
The sharer’s encoded screen, as binary chunks. Accepted only from the room’s current sharer: the verified identity and the connection id from the sync payload |
/ws/share/{room_id}?role=viewer |
One viewer’s copy of that stream: the format, the retained initialisation segment, then the stream from the next cluster. Viewers may not send media |
Security Considerations
Section titled “Security Considerations”- SSRF Protection:
validate_proxy_url()blocks access to private/reserved/loopback IPs viaipaddressmodule + DNS resolution - CORS: Configurable via
ALLOWED_ORIGINSenv var. Credentials disabled when wildcard origin is used - Authentication: Cloudflare Zero Trust header (
cf-access-authenticated-user-email) in production;?user=query param only whenDEVELOPMENT_MODE=true - Cookies: Never persisted. Delivered only by the extension (1MB limit, strict Netscape validation), held in process memory until 30 minutes after the last sync or until the member disconnects the extension, written for yt-dlp to a private RAM-backed scratch file for one extraction. Lent to a room only while the owner is connected or for 30 minutes after they leave it, only by a member actually signed in to the site, only for single-video pages of YouTube, Twitch and Kick
- Room Access: All users can join any room (authentication handled by Cloudflare)
- Connection Limits:
MAX_CONNECTIONS_PER_ROOM(50) andMAX_CONNECTIONS_PER_USER(10) prevent resource exhaustion - Room ID Sanitization: IDs restricted to alphanumeric + hyphen/underscore via regex
- Non-root Containers: All services run as non-root users
- Container Hardening: Pinned image versions, memory/CPU resource limits, internal ports not exposed to host
- Security Headers: Nginx sets CSP, HSTS, Permissions-Policy, X-Content-Type-Options, X-Frame-Options
- Extension Security: Host permissions scoped to specific video CDN domains; tokens stored in
chrome.storage.local(not synced across devices) - WebSocket Security: Room state initialization protected by
_state_lockfor atomic creation + role assignment
Performance Optimizations
Section titled “Performance Optimizations”- Format Caching: 2-hour TTL prevents redundant yt-dlp calls
- Segment Caching: Multi-tier cache with adaptive TTL
- Prefetching: Next segments prefetched based on playback position
- Connection Pooling: Reused HTTP connections for upstream requests
- Streaming Response: No buffering for video proxy
Roadmap
Section titled “Roadmap”Completed
Section titled “Completed”- Universal video resolution (yt-dlp, with boot-time + hourly idle-safe PyPI auto-updates)
- Real-time WebSocket sync
- DASH A/V synchronization
- HLS playback with hls.js
- Quality selection (up to 4K)
- Cookie authentication
- Browser extension for cookie sync
- Audio normalization
- Mono audio downmix
- Drag-and-drop queue
- Room persistence