High-Concurrency Danmaku System Architecture for Real-Time Interactive Live Streaming
This article breaks down the architecture of a high-concurrency danmaku (live scrolling comment) system for real-time interactive live streaming. It explains the core trade-offs among latency, reliability, and cost, then walks through a five-layer design covering access, gateway, message processing, distribution, and storage/observability. You will find practical details on long-lived connection handling, content validation, rate limiting, idempotent deduplication, fan-out optimization, hot and cold storage, capacity planning, alerting, and common failure modes. The goal is a predictable and operable real-time interaction foundation built through layered decoupling, asynchronous peak shaving, priority-based degradation, and observability.
1. Background and Problem Definition
In real-time interactive live streaming, danmaku (also called live comments or scrolling messages) is one of the capabilities that best reflects “audience participation.” Its typical characteristics are extremely high instantaneous traffic, a very short message lifecycle, and sensitivity to end-to-end latency, while also requiring that messages are “not lost, not out of order, and traceable.” These requirements naturally conflict, so designing a danmaku system is essentially about making trade-offs among latency, reliability, and cost.
From a traffic model perspective, danmaku requests have three clear characteristics:
- Spikiness: Moments such as going live, giveaways, and key match points can produce an order-of-magnitude jump in traffic within seconds.
- Short-lived value: A danmaku message usually has useful value for only a few seconds, and delivering it after that window has limited meaning.
- Strong fan-out: A single message must be received simultaneously by thousands of online users in the same room.
For these reasons, the traditional “request-response” API design is not suitable. General-purpose techniques such as message queues, long-lived connection gateways, and tiered caching need to be introduced.
2. Overall Layered Architecture
A deployable danmaku system is typically divided into five layers:
- Access layer: Handles protocol termination, authentication, and connection keep-alive, usually using long-lived connections to reduce handshake overhead.
- Gateway layer: Maintains session and room routing relationships and handles read/write separation for messages.
- Message processing layer: Responsible for validation, rate limiting, deduplication, formatting, and ordering.
- Distribution layer: Performs fan-out by room and pushes messages to online connections.
- Storage and observability layer: Handles cold data archiving, auditing, and monitoring/alerting.
The layers are decoupled through message queues, so spiky traffic can be buffered and downstream consumers can process at a steady rate according to their own capacity. This is the core idea of “peak shaving and valley filling.”
3. Access Layer and Long-Lived Connection Design
Using long-lived connections for downstream danmaku delivery is an industry consensus. Key design points include:
- Heartbeat keep-alive: Clients send heartbeats periodically, and the server reclaims a connection if no heartbeat is received within multiple cycles.
- Decoupling connections from users: A connection is bound to a session identifier rather than a business identity, making it easier for the same user to be online on multiple devices.
- Read/write separation: Upstream danmaku uses a short-lived connection or a separate channel to avoid downstream broadcast blocking upstream writes.
A sample connection registration logic is shown below (pseudocode):
def on_connect(conn, session):if not verify_token(session.token):return conn.close(401)gateway.bind(conn, session.uid)gateway.join_room(conn, session.room_id)heartbeat.start(conn, interval=25, timeout=75)
4. Message Processing: Validation, Rate Limiting, and Deduplication
Before a message enters the broadcast pipeline, four types of processing must be completed:
- Content safety validation: Text moderation and sensitive-word filtering should be completed synchronously on the access side to prevent non-compliant content from spreading.
- Rate limiting: Separate token buckets are set for each user and each room to prevent flooding from consuming bandwidth.
- Idempotent deduplication: Client retransmissions produce duplicate messages, so an idempotency key based on “session + client-side increasing sequence number” is needed.
- Ordering and sequencing: A monotonic sequence number is generated based on the server’s receive time to guarantee message order within the same room.
def handle_message(msg):if not rate_limiter.allow(msg.uid, msg.room_id):return DROPif seen.contains(msg.idempotent_key):return DROPmsg.seq = sequencer.next(msg.room_id)seen.mark(msg.idempotent_key, ttl=60)queue.publish("danmaku.normalize", msg)
5. Distribution and Fan-Out Strategy
Fan-out is the most expensive step. If the number of online users in a room is N, the push cost of a single message is O(N). Common optimization techniques include:
- Aggregation by room: Use the room as the smallest broadcast unit to avoid iterating connection by connection.
- Batch merging: Merge multiple danmaku messages within a very short window and deliver them at once to reduce the number of network packets.
- Tiered sampling: For very large rooms, sample pushes by priority, downsample regular danmaku, and deliver paid or high-priority messages in full.
- Edge node offloading: Push distribution capability down to access nodes closer to users to reduce pressure on backbone links.
6. Storage, Archiving, and Traceability
The storage strategy for danmaku should distinguish “hot” from “cold” data:
- Hot data is kept in an in-memory cache and retained only for the most recent few minutes, used to fill gaps after reconnection.
- Cold data is written asynchronously to object storage or a logging service for content auditing and playback.
- Playback scenarios can read in batches along a timeline, fully isolated from the real-time pipeline to avoid mutual interference.
7. Capacity Planning and Load Testing
Capacity evaluation is recommended to follow these steps:
- Estimate peak concurrent users and the per-user send frequency to obtain peak write TPS.
- Multiply by the average fan-out factor to obtain the total downstream push volume and bandwidth requirements.
- Reserve resources with 3-5x redundancy to cover sudden spikes.
- Use step-wise load testing to gradually approach the limit, and record latency percentiles rather than only looking at the average.
It is worth emphasizing that latency should focus on P99 and P999, because the average masks long-tail jitter, while user perception is precisely determined by the long tail.
8. Observability and Alerting
Four types of metrics must be established: connection count, write TPS, end-to-end latency percentiles, and drop rate. Alerts should use multi-level thresholds: a warning level signals abnormal trends, while a critical level triggers automatic scaling or a degradation switch. Trace identifiers should also be retained to make it easier to locate an anomaly to a specific stage.
9. Common Failures and Mitigations
- Connection avalanche: A gateway restart causes concentrated reconnections, so randomized backoff for reconnection should be introduced.
- Message backlog: When consumption capacity is insufficient, prioritize dropping low-priority danmaku to protect the core pipeline.
- Hot rooms: Traffic skew toward a single room requires room-level independent resource isolation.
- Moderation blocking: When the moderation service is unstable, degrade quickly to “rate limit first, then moderate” to prevent an overall outage.
10. Conclusion
The key to a high-concurrency danmaku system is not pursuing extreme single-point performance, but building a predictable and operable real-time interaction foundation through layered decoupling, asynchronous peak shaving, priority-based degradation, and comprehensive observability. With the general-purpose capabilities of cloud platforms such as Baidu AI Cloud, standard components like message queues, container platforms, object storage, and monitoring/alerting allow teams to focus their energy on business rules and experience optimization, delivering a stable and smooth real-time interaction experience at lower cost.
