Architecture Design and Best Practices for Video Danmaku Systems

    This article explores the technical architecture and best practices for building a scalable video danmaku (bullet comment) system. It covers core challenges such as high concurrency, low latency, and fan-out amplification. Readers will gain insights into system layering (access, distribution, storage, and moderation), real-time message synchronization mechanisms, efficient storage models using time-slicing and ring buffers, and client-side experience optimization. This guide provides developers with a comprehensive methodology for designing high-concurrency real-time interactive systems.

    1. Technical Characteristics and Challenges of Danmaku Systems

    Danmaku (bullet comments) may seem like simple floating text on a video, but it is essentially a massive real-time messaging system. Compared to traditional comment sections, danmaku has three distinct characteristics:

    1. High-concurrency writes: During live broadcasts or peak viewing times of popular videos, tens of thousands or even hundreds of thousands of danmaku messages can be generated per second. The write pressure far exceeds traditional UGC scenarios.
    2. Low latency requirements: The core value of danmaku lies in the synchronous “shared experience” with the video. The ideal latency from sending to visibility for all viewers should be controlled from hundreds of milliseconds to a few seconds.
    3. Fan-out amplification for both reads and writes: A single danmaku message needs to be pushed to tens of thousands of concurrent viewers. The read-write ratio is not simply “read-heavy, write-light”; both sides are significantly amplified.

    These characteristics dictate that a danmaku system cannot simply rely on traditional “database + polling” solutions. It requires dedicated message channels and distribution architectures.

    2. Overall Architecture Layered Design

    A mature danmaku system is typically divided into four layers:

    Access Layer: Responsible for maintaining long client connections. Mainstream solutions use WebSocket or TCP-based proprietary protocols, combined with gateways for connection authentication, heartbeat keep-alive, and reconnection. The connection gateway itself is stateless to facilitate horizontal scaling.

    Distribution Layer: The core function is message fan-out. A common approach is the “room model + broadcast”: each danmaku first enters the message queue corresponding to the room, and then the distribution service subscribes to the queue and broadcasts it to all connections in that room. To reduce broadcast pressure, two practices are usually implemented:

    • Throttling and Sampling: When the volume of danmaku exceeds a threshold, the server samples and sends messages based on weight instead of pushing everything. This is an industry-standard practice because the human eye cannot read full danmaku during peak times anyway.
    • Tiered Channels: Danmaku is divided into regular messages and high-priority messages (such as system notifications or gift reminders) routed through different priority channels to ensure critical messages are not drowned out.

    Storage Layer: Danmaku is organized by “Video ID / Live Room ID + Time Slice”. In VOD (Video on Demand) scenarios, danmaku is sliced and stored according to the video timeline. When the client pulls data, it only needs to fetch a small segment near the current playback position, naturally supporting playback and seeking. In live streaming scenarios, a recent rolling window is primarily used, and historical danmaku can be asynchronously persisted to the database.

    Moderation Layer: All danmaku must undergo content moderation (sensitive word filtering, machine review, and manual review if necessary) before entering distribution. This is a non-negotiable compliance baseline.

    3. Message Channels and Synchronization Mechanisms

    Real-time performance relies on long connections, but connection jitter is inevitable in mobile network environments. Several key issues must be handled in engineering:

    Reconnection and Message Compensation: After a client reconnects, it pulls incremental messages from the server by carrying the “last received message sequence number” to avoid gaps in danmaku. This requires the distribution layer to maintain a monotonically increasing sequence number and a short-term message buffer for each room.

    Danmaku and Playback Progress Alignment: In VOD scenarios, danmaku is not “displayed upon receipt”; instead, it is rendered on the player’s timeline based on its attached timestamp. The client needs a small danmaku pool for preloading, usually prefetching data for a few seconds before and after the current progress.

    Heartbeat and Connection Migration: The heartbeat interval must balance “promptly detecting disconnections” with “saving power and traffic,” typically around 30 to 45 seconds. The gateway side cooperates with connection state synchronization to ensure that the room subscription relationship is not lost when the user switches networks.

    4. Storage Models and Data Structures

    The classic storage structure for VOD danmaku is a “Segmented Sorted List”:

    1. {
    2. "video_id": "v_10086",
    3. "segment": 60, // One segment per 60 seconds
    4. "danmaku": [
    5. {"t": 61.2, "uid": "...", "text": "...", "mode": "scroll"},
    6. {"t": 61.8, "uid": "...", "text": "...", "mode": "top"}
    7. ]
    8. }

    Storing by segment brings three benefits: First, the client pulls a small granularity, resulting in low traffic. Second, segments of popular videos can be multi-level cached (Memory -> Cache Service -> Persistent Storage), providing strong resistance to read pressure. Third, appending writes by segment avoids row-level lock contention.

    For live streaming scenarios, a “Ring Buffer + Async Archiving” model is more suitable: the most recent N minutes are kept in memory or cache for new viewers to quickly fetch, while data exceeding the window is asynchronously written to the persistent layer for post-event playback and data analysis.

    5. Content Security and Experience Optimization

    The openness of danmaku makes content security particularly critical:

    • Multi-level Filtering: The sending side first applies local sensitive word and frequency limits (e.g., limiting a single user to 1 message per second). The server then performs semantic-level moderation; high-risk content is directly intercepted or forwarded to manual review.
    • User Governance: Mechanisms like reporting, blocking, and danmaku credit scores are combined to create positive incentives.
    • Experience Optimization: Client-side rendering must handle danmaku track allocation, collision avoidance (preventing overlapping on the same track), and density control. It can offer multiple modes (top, bottom, scroll) and keyword blocking features, sinking some filtering logic to the client side to reduce invalid rendering.

    6. Summary

    A danmaku system is a comprehensive manifestation of three capabilities: real-time message distribution, sequential data storage, and content moderation. The core design principles are: using long connections to ensure real-time performance, using the room model and throttling/sampling to control fan-out costs, using time-sliced storage to support VOD playback, and using multi-level moderation to safeguard compliance baselines. By mastering this general architectural methodology, developers can migrate it to various high-concurrency real-time scenarios such as live streaming interactions, online collaboration, and real-time commenting.