High-Concurrency Live Comment and Danmaku System Architecture and Performance Optimization

    This article breaks down the architecture design and performance optimization of high-concurrency live comment and danmaku (bullet comment) systems used in video playback, live sports, and online classrooms. It explains why real-time interaction traffic differs from regular workloads, then walks through a five-layer architecture, connection and rate-limiting design, message processing with peak shaving and fan-out, tiered storage and read paths, capacity planning, observability, and common pitfalls to avoid.

    1. Why Real-Time Interaction Demands a Stronger Architecture

    In scenarios like video playback, live sports viewing, and online classrooms, danmaku (bullet comments) and comments are the most typical real-time interaction capabilities. They may look like “sending a short piece of text,” but their traffic model differs significantly from ordinary business workloads:

    • Strong burstiness: The opening of a stream, a decisive match point, or a highlight moment can trigger a flood of danmaku within seconds, with instantaneous write volume reaching dozens of times the average.
    • Strong real-time requirements: Users expect danmaku to appear on screen within a few hundred milliseconds; excessive latency directly ruins the experience.
    • High read amplification: A single danmaku produces one write, yet may be read by thousands of online users in the same room.
    • Massive data with a clear hot/cold split: Recent data is accessed frequently, while historical data is rarely accessed but must remain queryable.

    These four factors mean the system cannot rely on a naive “synchronous database write + full query” implementation. Instead, it must apply targeted designs at the access layer, processing layer, and storage layer.

    2. Layered Architecture Overview

    A mature real-time interaction system is typically divided into five layers:

    1. Access layer: Maintains long-lived connections, handles authentication, rate limiting, and message encoding/decoding.
    2. Message processing layer: Handles validation, filtering, ordering, and fan-out computation.
    3. Storage layer: Keeps hot data in memory, persists warm data, and archives cold data.
    4. Distribution layer: Pushes messages to online terminals within a room.
    5. Supporting systems: Monitoring and alerting, logging services, configuration centers, and load-testing platforms.

    The core value of layering lies in “fault isolation” and “independent scaling”: the access layer scales by connection count, the processing layer scales by message throughput, and the storage layer scales by capacity and read/write ratio, with each layer decoupled from the others.

    3. Access Layer Design Essentials

    3.1 Long-Lived Connections and Heartbeats

    Real-time interaction relies on long-lived connections. Three parameters must be defined during design: heartbeat interval, heartbeat timeout, and the reconnection backoff strategy. Too short a heartbeat interval generates large amounts of useless traffic, while too long an interval fails to detect dead connections promptly. A recommended approach is for the server to issue the heartbeat period, for the client to report on that period, and for the server to proactively reclaim a connection after several consecutive misses.

    3.2 Access Rate Limiting and Prioritization

    Rate limiting should be completed as close to the user as possible, preventing useless traffic from penetrating to the backend. Common strategies include:

    • Per-user rate limiting: A cap on the number of sends by the same user to the same room within a unit of time.
    • Per-room rate limiting: A soft threshold on the room’s overall write rate; once exceeded, traffic enters queuing or degradation.
    • Priority queues: High-priority content such as paid interactions and host messages travels through a dedicated channel, ensuring it is not crowded out by ordinary danmaku.

    3.3 Message Structure Convention

    A compact binary or short-key encoding is recommended, with fields kept backward compatible. An illustrative structure is shown below:

    1. {
    2. "room_id": "10086",
    3. "msg_id": "01J8Z3K2Q7X9",
    4. "user_id": "u_88231",
    5. "content": "太精彩了",
    6. "ts": 1730000000123,
    7. "type": 1,
    8. "ext": {}
    9. }

    Here, msg_id should be a globally unique and monotonically increasing identifier to facilitate later sorting and deduplication; ts is finalized by the server to avoid out-of-order messages caused by client clock drift.

    4. Message Processing Pipeline: Peak Shaving, Asynchrony, and Fan-Out

    4.1 Peak Shaving

    The most effective tactic in flood scenarios is to introduce a message queue as a buffer. The access layer does only three things: “receive, enqueue, return,” compressing the synchronous path to a minimum and handing the real processing pressure to a horizontally scalable consumer cluster. The queue backlog itself is an excellent capacity signal that can be used directly for auto-scaling decisions.

    4.2 Validation and Content Safety

    The processing layer must handle length truncation, frequency validation, and sensitive content detection. Content safety is best implemented with a two-stage model of “synchronous lightweight rules + asynchronous deep review”: lightweight rules guarantee millisecond-level responses, while deep review runs in the background and, upon a hit, notifies the client to remove already-displayed content via a recall instruction.

    4.3 Fan-Out Strategy

    Fan-out is the most expensive step. If every message is pushed individually to every connection in a room, the complexity is O(messages × online users). Optimization directions include:

    • Batched push: Merge multiple danmaku within a short time window into a single batch, significantly reducing the number of packets.
    • Sampling and rate-limited display: For extremely popular rooms, display a sampled subset by policy to keep visual density controllable.
    • Hierarchical broadcast: Group connections by their gateway, broadcast once between gateways, then let each gateway distribute locally.

    5. Storage and Read Paths

    5.1 Three-Tier Data Temperature Classification

    • Hot data: Danmaku from the last few minutes in currently popular rooms, kept in an in-memory cache for millisecond-level reads.
    • Warm data: Data from the last several days, written to distributed storage or a relational database, partitioned by room and time.
    • Cold data: Historical archives placed in object storage, loaded on demand, with cost as the priority.

    5.2 Read/Write Separation and Cache Consistency

    Danmaku reads far exceed writes, so read/write separation yields clear benefits. For cache updates, “invalidate after write + delayed double delete” or “overwrite by version number” is recommended to avoid stale values being written back under concurrency. For counting data (such as like counts and online user counts), in-memory accumulation plus periodic flushing can be used, tolerating brief inconsistency.

    5.3 Partitioning and Indexing

    Storage design should use room_id + time as the primary partition key so that queries naturally converge to a small number of partitions. Too many secondary indexes should be avoided, as they cause severe write amplification. After hot/cold separation, historical queries go through an independent read-only path to avoid affecting the real-time path.

    6. Capacity Planning and Elastic Scaling

    Capacity estimation can follow this approach:

    1. Estimate the peak number of online rooms and the average number of online users per room to obtain the total concurrent connections.
    2. Determine the flood factor based on the historical peak-to-average ratio (typically 3–10 for interaction scenarios).
    3. From the two metrics of connections per instance and message throughput per instance, separately estimate the number of access-layer and processing-layer instances, take the larger value, and reserve redundancy.
    4. Calculate storage capacity as “average daily entries × bytes per entry × retention days × number of replicas,” and reserve room for growth.

    Elastic scaling should be based on composite metrics such as queue backlog, connection count, and push latency, rather than CPU utilization alone, because the bottleneck in interaction scenarios is often connections and network rather than compute.

    7. Observability and Stability Assurance

    • Core metrics: Send success rate, end-to-end latency percentiles (P95/P99), queue backlog, cache hit rate, and push failure rate.
    • Logging and tracing: Attach a unified identifier to each message to enable full-link tracing from access to distribution.
    • Alert tiers: Latency degradation and backlog growth are tier-1 alerts, single-point failures are tier-2, and capacity watermarks are tier-3.
    • Degradation plans: In extreme cases, disable historical queries, reduce push frequency, and keep only the high-priority channel in sequence to ensure the main path stays available.
    • Routine load testing: Validate capacity assumptions with shadow traffic or dedicated load-testing rooms to avoid discovering bottlenecks only after launch.

    8. Common Pitfalls

    1. Treating danmaku like ordinary comments with synchronous database writes: Database connections are quickly exhausted during floods.
    2. Over-relying on client-side ordering: Displays become inconsistent across clients and are easy to tamper with.
    3. Caches without expiration or eviction policies: Memory grows continuously until the service becomes unavailable.
    4. Monitoring only averages: Averages hide the long tail; percentiles must be observed.
    5. Ignoring the recall and review loop: This creates high compliance risk and degrades user experience.

    9. Conclusion

    The essence of a real-time interaction system is a typical problem of “high-concurrency writes + high fan-out reads + strong real-time constraints.” Through access-layer rate limiting, message-queue peak shaving, asynchronous processing, tiered caching, and hot/cold separated storage, combined with a complete observability system and degradation plans, flood traffic can be stably supported at controllable cost. Building such a system on top of the general capabilities of cloud platforms such as Baidu AI Cloud (including message queues, container platforms, object storage, logging services, and monitoring and alerting) allows teams to focus more on business logic itself, leaving elasticity and operational complexity to the infrastructure.