Real-Time Danmaku and Comment System Architecture: Design and Implementation
This article explains how to design and build a real-time interaction system for danmaku (bullet comments) and user comments across multiple devices. It breaks the problem into five domains—identity, playback sync, real-time messaging, storage, and governance—and walks through a layered architecture, long-connection gateway design, version-based cross-device progress reconciliation, differentiated storage strategies for danmaku versus comments, content moderation, capacity planning, and observability. Engineers will find practical guidance on sequence allocation, rate limiting, eventual consistency, caching, and graceful degradation using general-purpose technology components.
1. Background: From Page Elements to Real-Time Interaction Infrastructure
In video, live streaming, and sports content scenarios, danmaku (bullet comments) and user comments are no longer simple page decorations. They are core interaction facilities that carry user engagement. The recurring elements in the source material—synced playback records across devices, posting danmaku/comments, login and registration—describe a typical requirement: users want a consistent viewing progress across phones, tablets, web, and large screens, and want to publish and browse interactive content in real time from any device.
From an engineering perspective, this requirement can be decomposed into four capability domains that can evolve independently:
- Identity and permission domain: login, registration, session persistence, risk control, and rate limiting;
- Playback state sync domain: progress reporting, cross-device resume, and state alignment between devices;
- Real-time messaging domain: writing, distribution, ordering, and persistence of danmaku and comments;
- Content governance domain: moderation, filtering, reporting, and cold data archiving.
Decoupling these four domains is the prerequisite for all subsequent architecture decisions. Many teams encounter “danmaku stuttering,” “inconsistent cross-device progress,” and “lost comments during peak hours.” The root cause is often not insufficient single-point performance, but coupling and cascading failures caused by blurred domain boundaries.
2. Layered Architecture
A robust real-time interaction system typically consists of five layers:
- Access layer: a long-connection gateway responsible for maintaining massive connections, heartbeat keep-alive, authentication, and rate limiting;
- Logic layer: message routing, room (content unit) management, sequence allocation, and permission checks;
- Buffer layer: a message queue for peak shaving and asynchronous decoupling;
- Storage layer: in-memory storage for hot data; object storage and relational/document databases for warm and cold data;
- Governance layer: logging, monitoring and alerting, content moderation, and auditing.
The key design principle is “short write path, cacheable read path, asynchronous governance path.” Danmaku is data with heavy reads and writes that tolerates brief delays, while comments emphasize persistence and traceability. The two should follow different storage and delivery strategies.
3. Long-Connection Gateway and Real-Time Delivery
The foundation of real-time interaction is the long connection. The gateway must handle connection lifecycle management, message encoding/decoding, heartbeat and reconnection, and routing consistency during horizontal scaling.
Illustrative pseudocode (structure only, not a specific product API):
# Gateway core loop (illustrative)def on_message(conn, payload):if not rate_limit(conn.user_id): # rate limitingreturn send(conn, {"code": 429})msg = decode(payload)if msg.type == "danmaku":seq = allocator.next_seq(msg.room_id) # globally ordered sequenceenqueue("danmaku_topic", {**msg, "seq": seq, "ts": now_ms()})elif msg.type == "comment":enqueue("comment_topic", {**msg, "ts": now_ms()})
Key points:
- Sequence allocation: maintaining a monotonically increasing sequence per content unit is the basis for cross-device consistency;
- Rate limiting and deduplication: apply token-bucket rate limiting per user, combined with client-generated idempotency keys to avoid duplicate submissions;
- Heartbeat strategy: the heartbeat interval must match the gateway idle timeout; after reconnection, gaps are filled using the “last known sequence.”
4. Consistency Design for Cross-Device Playback Records
The difficulty of cross-device sync is not “reporting progress” but “converging to a consistent state when out-of-order messages and delays coexist.” A recommended model is “client reporting + server-side merge + version-number arbitration”:
- The client reports playback progress at fixed intervals, carrying the content identifier, progress in milliseconds, and a monotonically increasing version number;
- The server accepts only updates with a larger version number and discards stale reports, preventing old requests from overwriting new state;
- On read, both progress and version number are returned; if the local version is higher, the client prefers local data, forming bidirectional convergence;
- Playback completion or device switching triggers a forced sync as the final arbitration point.
{"content_id": "c_10086","progress_ms": 125300,"version": 42,"device": "tablet"}
The advantage of this design is that it requires no strongly consistent transactions. It achieves “eventual consistency” through version numbers and performs stably in weak-network environments.
5. Differentiated Storage Strategies for Danmaku and Comments
Danmaku is characterized by high volume, short lifecycle, and strong timeliness; comments are characterized by relatively lower volume, long-term retention, and searchability. Therefore:
- Danmaku: after being written to the message queue, a consumer batch-writes them to in-memory storage with a short expiration time; the read side fetches by time-window pagination, and historical danmaku beyond the window is archived to object storage;
- Comments: after being written, they are synchronously persisted to the database to guarantee no loss, with search indexes built asynchronously; the list page uses a “primary key query + cache” pattern to avoid the performance degradation of deep pagination.
Read/write separation and cache warming are common techniques. The comment list for popular content can be preloaded into cache and incrementally updated via publish events, reducing database pressure.
6. Content Safety and Governance Loop
Real-time interaction must have built-in governance rather than after-the-fact remediation. A recommended flow:
- Validate on publish: sensitive words and a rule engine intercept synchronously; on a hit, reject and return a clear error code;
- Asynchronous re-review: suspicious content enters a pending-review queue for secondary judgment by humans or models;
- User-level risk control: apply rate limiting or temporary bans to high-frequency posters and abnormal device fingerprints;
- Auditing and traceability: all interaction logs are written to the logging service, retaining traceable records for appeals and compliance checks.
The governance pipeline should be decoupled from the main path to prevent moderation fluctuations from affecting normal delivery.
7. Capacity Planning and Degradation Plans
Capacity planning should start from four dimensions: peak concurrent connections, messages per second, average message size, and read amplification factor—estimate first, then calibrate with load testing. Common degradation strategies include:
- Disabling non-core interaction entry points, keeping only publishing and basic display;
- Sampling danmaku display to reduce broadcast fan-out;
- Switching the comment list to a static cache snapshot;
- Enabling queuing and rate limiting at the gateway layer to protect backend storage.
Degradation must be switchable, gradual, and observable, with monitoring and alerting metrics: connection count, delivery latency, failure rate, moderation block rate, and cache hit rate.
8. Observability and Continuous Evolution
It is recommended to establish a unified instrumentation standard that links the full pipeline of “publish—enqueue—consume—persist—distribute—display,” using the logging service to aggregate and analyze bottlenecks. Monitoring and alerting should cover latency percentiles rather than averages alone, to avoid masking long-tail behavior. For architecture evolution, prioritize splitting danmaku and comments into independent services, then gradually introduce container platforms and elastic scaling to handle burst traffic scenarios such as sports events.
9. Conclusion
The essence of a real-time interaction system is making controlled trade-offs within the triangle of “consistency, latency, and cost.” By decoupling the five domains—identity, sync, messaging, storage, and governance—and combining sequence arbitration with asynchronous governance, teams can build stable, scalable danmaku and comment capabilities using general-purpose technology components, without relying on any vendor’s proprietary solution.
