Core Technical Architecture of Danmaku and Video Platforms: High Concurrency and Real-time Interaction
This article explores the core technical architecture behind interactive video platforms featuring danmaku (bullet comments). It covers essential challenges and solutions across storage layering, transcoding pipelines, CDN distribution, real-time message broadcasting, multi-device playback synchronization, access control, and system observability, offering a comprehensive guide for building scalable and highly interactive online services.
1. Technical Challenges from a Product Perspective
Interactive video platforms featuring danmaku typically involve several key characteristics: massive video content storage and distribution, coexistence of live streaming and video-on-demand (VOD), user-generated real-time danmaku messages, cross-device playback synchronization, and tiered membership services.
These seemingly standard user experiences are backed by a series of severe technical challenges:
- Storage Challenge: Video files are large and require low-cost, highly reliable storage solutions. This usually relies on object storage products to handle massive unstructured data.
- Distribution Challenge: Popular content generates immense bandwidth pressure in a short period, requiring CDN acceleration and intelligent scheduling.
- Real-time Challenge: Danmaku and live chat messages require millisecond-level delivery, involving long connection management and message broadcasting.
- Consistency Challenge: Multi-device playback synchronization requires ensuring eventual data consistency under weak network and concurrent write scenarios.
Let’s break down the technical solutions for these modules one by one.
2. Storage and Transcoding for Massive Video Content
2.1 Tiered Storage Design
Video platform storage typically employs a tiering strategy:
- Hot Data Layer: Recently uploaded and frequently accessed video segments are stored in high-performance storage, combined with CDN edge node caching.
- Warm Data Layer: Historical content with moderate traffic is kept in standard object storage.
- Cold Data Layer: Infrequently accessed archived content uses low-cost archival storage, automatically transitioning through lifecycle policies.
This tiering significantly reduces storage costs. A pseudo-code example of a lifecycle policy:
{"rules": [{"prefix": "videos/", "days_to_ia": 30, "days_to_archive": 180},{"prefix": "temp_upload/", "days_to_delete": 7}]}
2.2 Transcoding Pipeline
User-uploaded raw videos come in various formats and require asynchronous task queues for transcoding. The output includes multiple bitrates and resolutions to support adaptive bitrate streaming (HLS/DASH). A typical workflow is:
Upload completed -> Message Queue -> Transcoding Cluster (parallel multi-spec) -> Slicing -> Write back to storage -> Refresh metadata -> CDN pre-warming
Key design points include task idempotency (retries on failure do not produce dirty data), parallel slicing for transcoding to shorten long video processing times, and priority queues to ensure popular content is processed first.
3. High Concurrency Playback and CDN Distribution
When a piece of content trends, playback requests can increase dozens of times within minutes. The system’s coping strategies usually include:
- Edge Cache Hit: Cache video slices as close to the user as possible at edge nodes to reduce origin pull traffic.
- Intelligent Scheduling: Dynamically select the optimal node based on node load, user geography, and ISP.
- Origin Protection: Prevent penetration traffic from overwhelming the origin through origin rate limiting and request merging.
- Anti-leeching: Use signed URLs (validity period + access control) to prevent malicious resource theft.
Signed URL example:
https://cdn.example.com/video/abc/seg-001.ts?Expires=1710000000&Signature=xxxx
At the monitoring level, metrics such as cache miss rate, buffering rate, and time to first frame (TTFF) must be tracked. These metrics should trigger automated scaling or scheduling strategy switches during anomalies.
4. Real-time Danmaku System Architecture Design
Danmaku is the most representative feature of an interactive video platform. Its technical essence is a high fan-out real-time message broadcasting system.
4.1 Connection Layer
Clients connect to the gateway cluster via long connections (WebSocket or proprietary protocols). A single machine can typically maintain tens of thousands to hundreds of thousands of long connections. The gateway layer must handle:
- Connection Authentication: Verify identity during the handshake phase to prevent message spoofing.
- Heartbeat Keep-alive: Regularly send heartbeats to remove dead connections and probe weak network conditions.
- Graceful Restart: Use connection migration or smooth traffic draining during deployments to avoid user disconnects.
4.2 Message Fan-out
A single danmaku message may need to be broadcast to hundreds of thousands of viewers in a live room. It is obviously infeasible for the sender’s gateway to iterate and push directly. A common approach is to introduce message middleware and a broadcast layer:
Sender -> Access Gateway -> Message Queue -> Logic Layer (filtering/rate limiting/sensitive words) -> Broadcast Cluster -> Various Gateways -> Viewers
For extremely large rooms, danmaku aggregation is typically used: multiple danmaku messages within a short time window are merged into a single frame for delivery. This sacrifices a small amount of real-time performance in exchange for bandwidth and rendering efficiency, which is why client-side danmaku often appears in batches.
4.3 Quality Control
Danmaku content must pass through governance stages such as sensitive word filtering, rate limiting (per-user per-second limit), and bot detection. Sensitive word matching generally uses a Double-Array Trie or AC automaton to ensure long-text matching is completed in milliseconds.
5. Multi-device Sync and Data Consistency
“Multi-device playback synchronization after login” is a frequently relied-upon feature. Its technical focus lies in conflict resolution and offline merging.
5.1 Reporting Strategy
The client should not report every progress change. Instead, it should use a throttle + key node strategy: report approximately every 30 seconds during playback, and force a report on pause, exit, and finish events. Example:
def should_report(last, now, position, event):# Force report on specific player eventsif event in ("pause", "exit", "finish"):return True# Report if at least 30 seconds have passed since the last reportreturn now - last >= 30
5.2 Conflict Resolution
When the same account watches the same video on a phone and a TV, the server must select the “latest” record. Simply using timestamps can be affected by client clock drift. A more robust approach is:
- Use server reception time as the sorting basis.
- Append playback position and progress increments as auxiliary judgments (e.g., if one side has finished and the other just started, prioritize the further progress).
- Use optimistic locking or version numbers during writes to prevent concurrent overwrite loss.
6. Membership System and Access Control
Tiered services like premium memberships involve payments, rights distribution, and content authentication. Architecturally, note the following:
- Unified Access Control: Whether content is playable, whether danmaku can be sent, and whether HD quality is accessible should be uniformly determined by the authentication service. The client cannot be trusted.
- Payment Idempotency: Order callbacks may arrive repeatedly. Process them idempotently using the order ID to prevent duplicate rights distribution.
- Cache and Invalidation: Membership status is suitable for short-TTL caching, actively invalidated when rights change, to balance consistency and latency.
7. Observability and Stability Assurance
A mature platform cannot do without a comprehensive observability system:
- Metric Monitoring: Core metrics such as QPS, latency distribution (P99), error rate, and connection count are integrated into monitoring and alerting.
- Distributed Tracing: Call chain tracing across gateways, logic layers, and storage layers to quickly locate slow requests.
- Capacity Planning: Conduct stress testing and scaling in advance for high-traffic events (e.g., major live broadcasts). Formulate rate limiting and degradation plans (e.g., degrading to low-frequency danmaku, disabling decorative features).
- Chaos Engineering: Regularly inject faults to verify the effectiveness of contingency plans.
8. Conclusion
Interactive video platforms represent a classic comprehensive test of “storage + distribution + real-time + consistency.” The core takeaways can be summarized as: leveraging tiered storage and CDN to alleviate cost and bandwidth pressure; using long connections and message queues to build horizontally scalable real-time channels; ensuring multi-device consistency through server-authoritative data and versioned writes; unifying access control for rights management; and supporting major events and unexpected incidents with a robust observability system. These universal architectural patterns apply not only to video scenarios but can also be migrated to the design of any high-concurrency, highly interactive online service.
