High-Concurrency Live Comment and Danmaku System: Architecture Design and Implementation
This article breaks down the architecture of a real-time comment and danmaku system built for high concurrency. It covers the core challenges of burst traffic, low latency, ordering, content safety, and cost, then walks through a five-layer design spanning the access layer, logic layer, real-time distribution layer, storage layer, and supporting services. You will find practical patterns for connection handling and authentication, tiered rate limiting, a standardized message processing pipeline, room-based fan-out with batching, hot/warm/cold storage tiering, cursor-based pagination, elastic scaling, and observability. The approach applies to live streaming interaction, online education Q&A, and community comment sections.
1. Problem Background and Core Challenges
In scenarios such as video playback, live interaction, and online classrooms, danmaku (bullet comments) and comment sections are the most typical forms of real-time interaction. Sending a short piece of text may look trivial, but under high concurrency it simultaneously triggers pressure on the access layer, real-time broadcast, storage writes, and content safety. The login, registration, messaging, feed, and favorites entry points found in the original material essentially reflect the information architecture of a typical content community product: a user identity system, a real-time interaction area, a personalized message feed, and a content favorites system. This article strips away the specific product attributes and abstracts the problem into a general technical one: how to design a real-time interaction system that is scalable, low-latency, and governable.
The core challenges can be summarized in five points:
- Burst traffic: concurrency spikes sharply the moment a hot piece of content goes live, with QPS reaching tens of times the daily level.
- Low-latency requirements: the latency threshold users can subjectively perceive is typically within a few hundred milliseconds.
- Strong ordering: messages under the same content must preserve time order to avoid “a reply appearing before the original post.”
- Content safety: text, images, and emojis may all carry violating content and require synchronous moderation.
- Cost constraints: short text with high-frequency writes means storage and bandwidth costs must be carefully controlled.
2. Overall Layered Architecture
A five-layer structure is recommended, where each layer has a single responsibility and can scale independently:
- Access layer: maintains long connections, handles authentication, rate limiting, and protocol parsing.
- Logic layer: handles message validation, business rules, moderation orchestration, and routing computation.
- Real-time distribution layer: handles message fan-out and merging by room dimension.
- Storage layer: handles persistence, retrieval, and hot/cold tiering.
- Supporting layer: includes the configuration center, monitoring and alerting, logging service, and content safety capabilities.
A schematic of the layered call relationships can be expressed as:
Client --(long connection/short request)--> Access Layer --(RPC)--> Logic LayerLogic Layer --> Moderation Orchestration --> Message Queue --> Distribution Layer --> SubscribersLogic Layer --> Storage Layer(hot/warm/cold) --> Retrieval ServiceFull pipeline --> Logging Service + Monitoring & Alerting
3. Access Layer: Connections and Authentication
The danmaku scenario is extremely sensitive to connection counts, and handling hundreds of thousands of long connections on a single machine is a common design target. Key points include:
- Front-load authentication: complete identity verification during the handshake to avoid re-authenticating on every subsequent message. Unauthenticated users can be read-only, while write operations require login, which is consistent with the common practice in community products of “participate after logging in.”
- Tiered rate limiting: apply token bucket rate limiting across three dimensions—user, content, and source IP—to prevent a single point from flooding and overwhelming a room.
- Lean protocol: high-frequency small messages are well suited to binary or compact encoding to reduce header overhead.
- Heartbeat and reconnection: design exponential backoff reconnection to avoid a reconnection storm when the server restarts.
# Pseudocode: access layer rate limiting and authentication skeletondef on_connect(conn, token):user = auth.verify(token) # Front-load authenticationif user is None:conn.close(reason="unauthorized")returnlimiter = TokenBucket(user.id, rate=5, burst=10)conn.bind(limiter)def on_message(conn, payload):if not conn.limiter.allow(): # Tiered rate limitingconn.send({"code": 429})returnenqueue_to_logic(conn.room_id, conn.user, payload)
4. Logic Layer and Message Processing
The logic layer is the central point for business rules and governance policies. It is recommended to standardize the processing flow into fixed stages for pluggable extension:
- Structure validation: field length, frequency, and content type whitelist.
- Content safety: text first passes through sensitive-word and semantic models, while images go through asynchronous moderation with degraded display first.
- Business rules: blocked-word replacement, level-based permissions, and room ban status checks.
- Routing computation: determine the target room and whether persistence is needed.
- Delivery: write to the message queue, which the distribution layer consumes asynchronously.
Making moderation a dual channel of “synchronous lightweight + asynchronous deep” is a common approach that balances latency and compliance: lightweight rules synchronously intercept obvious violations, while the deep model asynchronously re-reviews and supports after-the-fact tracing and withdrawal.
5. Real-Time Distribution and Ordering Consistency
The core of the distribution layer is “aggregation by room.” The room is a natural shard key; routing messages from the same room to the same distribution unit guarantees ordering without additional coordination.
- Merging and rate reduction: high-traffic rooms use time-window merging, for example pushing in batches every 100 milliseconds, which significantly reduces fan-out cost.
- Sampling and tiering: for extremely long rooms, tier users so that new users receive a sampled stream, avoiding full broadcast.
- Backpressure control: when a subscriber consumes too slowly, drop intermediate-state messages and keep only the latest state to prevent memory buildup.
A simplified model of ordering guarantees:
room_id -> hash -> shardA monotonically increasing sequence number seq is maintained within a shardThe client renders messages sorted by seq, and a gap triggers a re-pull
6. Storage and Retrieval Design
High-frequency writes of short text mean storage must implement hot/cold tiering:
- Hot data: in-memory or low-latency key-value storage that carries the message window of the most recent several minutes.
- Warm data: document or wide-table storage that supports paginated retrieval of historical comments by content ID.
- Cold data: object storage archival for auditing and offline analysis.
- Counting and deduplication: counts such as likes and reply counts go through independent counters to avoid hot-row contention.
Pagination must use a cursor rather than an offset, because offset pagination produces duplicates and omissions under high write volumes:
-- Recommended: cursor-based retrieval of historical messagesSELECT id, content, created_atFROM commentWHERE content_id = ? AND id < ? -- cursorORDER BY id DESCLIMIT 20;
7. Elastic Scaling and Capacity Planning
Common means of handling burst traffic include horizontal scaling of the stateless logic layer, shard rebalancing by room dimension, the message queue as a peak-shaving buffer, and dedicated resource pools for hot content. Capacity planning should estimate bandwidth using “peak QPS × average bytes per message × fan-out factor” and reserve three to five times the headroom. Load testing must cover three models: steady state, pulse, and sustained high pressure, respectively validating scaling speed, buffering capacity, and the effectiveness of degradation strategies.
8. Observability and Content Governance
A three-tier observability system must be established: the access layer monitors connection counts and failure rates, the logic layer monitors moderation interception rates and processing latency, and the distribution layer monitors end-to-end latency and drop rates. Logs are collected centrally into the logging service, and metrics are wired into monitoring and alerting with tiered thresholds. On the content governance side, a complete audit trail should be retained, supporting traceback across three dimensions—user, content, and time—and providing self-service appeals and rapid withdrawal capabilities.
If the overall system is built on the cloud, you can combine a container platform to host stateless services, a message queue for peak shaving, object storage for archival, and logging and monitoring services for operational support, allowing you to focus your effort on the business rules themselves.
9. Conclusion
The difficulty of a real-time interaction system lies not in processing a single message, but in the layered coordination and governance loop under burst traffic. Through access-layer authentication and rate limiting, a standardized processing pipeline in the logic layer, room-based aggregation and batching in the distribution layer, and hot/cold storage tiering with cursor-based pagination, combined with robust observability and content safety mechanisms, you can achieve stability and compliance while maintaining low latency. This methodology applies equally to live streaming interaction, online education Q&A, and community comment sections.
