Skip to main content
Backend & Distributed Systems 24 min readPublished November 23, 2026By Shiva Vinodkumar

Bilibili Danmaku Architecture: Real-Time WebSocket Message Fan-Out, Spatial Collision Avoidance & Client-Side Wasm Person Masking (2026)

Danmaku (弹幕, literally "bullet curtain") is the defining interactive paradigm of East Asian video platforms, pioneered by Niconico and perfected at planetary scale by China's Bilibili. Rather than relegating commentary to a static text feed beneath the video, Danmaku renders millions of simultaneous user comments flying directly across the active video viewport, synchronized to the exact millisecond timestamp of the media stream. Serving tens of millions of concurrent live viewers while preventing screen clutter and human facial occlusion requires a masterclass in distributed systems, epoll-based network gateways, and client-side WebAssembly computer vision.

Share:

Core Systems Takeaways

  • Gateway Concurrency: Bilibili uses specialized Go connection gateways leveraging Linux epoll and zero-copy TCP buffers to maintain over 1,000,000 persistent WebSocket sessions per physical bare-metal node.
  • Broadcast Topology: A two-tier fan-out architecture decouples stateful client gateways from stateless business logic using Kafka partition streams and Redis Cluster Pub/Sub channel hierarchies.
  • Spatial Collision Avoidance: Mathematical track allocation algorithms model comments as 1D intervals with dynamic velocities, preventing overlapping text across horizontal flight channels.
  • Smart Danmaku AI Occlusion: WebAssembly-compiled DeepLab/MobileNet models execute in the browser via WebGPU to generate real-time 8-bit alpha silhouette masks, compositing flying comments *behind* humans in the video frame.
  • Protocol Serialization Efficiency: Binary Protobuf packets with gzip/deflate compression reduce per-message framing overhead from 400 bytes of JSON to 28 bytes of packed binary.

1. The Scale Challenge: Millions of Concurrent Bullet Comments

In traditional live-streaming architectures (such as Twitch or YouTube Live), chat messages are rendered in a vertical sidebar. If message volume spikes to 10,000 messages per second, the client simply drops older messages or increases scroll velocity. The video stream itself is completely decoupled from the chat renderer.

In Danmaku architectures, every single message is an animated visual entity overlaid onto the video canvas. During major live events—such as Bilibili's annual New Year Gala (最美的夜) or League of Legends World Championship broadcasts—message ingress peaks at over 800,000 comments per second. A single popular live room may have 3,000,000 concurrent viewers. Broadcasting every comment to every viewer would require a broadcast throughput of:

Broadcast Volume = 800,000 messages/sec * 3,000,000 viewers 
                 = 2,400,000,000,000 outbound deliveries/sec (2.4 Trillion pkts/sec)

This is physically impossible on public Internet infrastructure without multi-tiered
downsampling, client-side density shedding, and hierarchical edge fan-out.

To solve this planetary routing challenge, Bilibili engineered a specialized distributed topology separating message ingestion, filtering/moderation, hierarchical broadcast trees, and edge push gateways.

2. Distributed Gateway Architecture: Linux Epoll & Two-Tier Fan-Out

Bilibili separates its real-time infrastructure into two primary tiers: the Comet Gateway Tier and the Job/Logic Tier (built on their open-source Kratos microservices framework).

+-----------------------------------------------------------------------------------+
|                        BILIBILI REAL-TIME DANMAKU TOPOLOGY                        |
+-----------------------------------------------------------------------------------+
                                                                                     
 [Client WebSocket / TCP] <========> [Edge CDN Anycast Layer]                       
           |                                   |                                     
           v                                   v                                     
 +---------------------------------------------------------------------------------+ 
 |                     COMET TIER (Stateless Connection Gateways)                   | 
 | - Written in Go with raw epoll network loops (gnet/gev)                          | 
 | - Holds 1.2M persistent TCP/WebSocket connections per 64-core node               | 
 | - Maintains in-memory Room Buckets & Ring Buffers                                | 
 +---------------------------------------------------------------------------------+ 
           ^                                   ^                                     
           | (Internal gRPC Stream)            | (Internal gRPC Stream)              
 +---------------------------------------------------------------------------------+ 
 |                       JOB TIER (Message Fan-Out Engine)                         | 
 | - Consumes from Kafka Partition Streams                                         | 
 | - Groups broadcast batches by Room ID & Target Comet Nodes                       | 
 | - Pushes multi-cast messages via high-throughput gRPC batches                    | 
 +---------------------------------------------------------------------------------+ 
           ^                                                                         
           | (Kafka Ingest Stream)                                                   
 +---------------------------------------------------------------------------------+ 
 |                     LOGIC TIER (Moderation, Antispam & DB)                      | 
 | - Sensitive keyword filtering (DFA trie matching in < 50 microseconds)           | 
 | - AI Toxicity Classifier (BERT/RoBERTa quantized on Triton Inference Server)      | 
 | - Asynchronous persistence to TiDB / ScyllaDB for on-demand playback VOD         | 
 +---------------------------------------------------------------------------------+ 
           ^                                                                         
           | (HTTP/3 / gRPC Ingestion)                                               
 [Sender Client Submitting Danmaku]

A. The Epoll Network Loop in the Comet Gateway

Standard Go net/http or WebSocket libraries spawn one goroutine per connection. At 1,000,000 connections, runtime goroutine stack memory alone (minimum 2KB to 4KB per stack) consumes 4GB of RAM before application buffers are allocated, leading to severe GC pause times.

Bilibili replaces runtime-scheduled goroutines with non-blocking Linux epoll event loops (similar to Nginx or Netty). A worker thread pool equal to physical CPU cores manages thousands of file descriptors simultaneously, reading binary frames into ring buffers without dynamic heap allocation:

// Go Reference: Ring-Buffered Epoll Connection Pool
type Connection struct {
    fd         int
    roomID     int64
    readBuf    []byte
    writeQueue *RingBuffer
}

func (c *CometNode) BroadcastRoom(roomID int64, payload []byte) {
    c.mu.RLock()
    roomConns := c.rooms[roomID]
    c.mu.RUnlock()

    // Zero-allocation batch write across all active room descriptors
    for _, conn := range roomConns {
        conn.writeQueue.Push(payload)
        c.epoll.ModWrite(conn.fd) // Arm EPOLLOUT event
    }
}

3. Client-Side Spatial Layout & Collision Avoidance Algorithms

Once Danmaku packets arrive at the browser, they must be rendered cleanly. Bilibili splits the video canvas into horizontal flight channels (tracks). The height of each track corresponds to the font size plus vertical padding:

Number of Tracks = floor( Canvas_Height / (Font_Size + Track_Padding) )

When a new rolling comment enters track k from the right edge, two collision conditions must be avoided:

Condition 1 (Entry Collision):
The tail of the preceding comment must fully cross the right screen border before 
the new comment enters the track.

Condition 2 (Chase Collision):
If the new comment travels faster than the preceding comment (because longer text 
is assigned higher velocity to cross the screen in the standard 5-second duration), 
it must not overtake and collide with the preceding comment before the predecessor 
exits the left border.

The client-side track allocation engine calculates the flight trajectories using linear kinematic equations:

Velocity_1 = (Screen_Width + Text_Length_1) / Duration
Velocity_2 = (Screen_Width + Text_Length_2) / Duration

Time_Catchup = (Screen_Width - Tail_Position_1) / (Velocity_2 - Velocity_1)

If Velocity_2 > Velocity_1 and Time_Catchup < Time_Until_Exit_1:
    COLLISION_DETECTED -> Try Next Track or Throttle Velocity

4. "Smart Danmaku": WebAssembly & WebGPU Silhouette Occlusion Masking

A major historical critique of Danmaku was that bullet comments obscured the faces and bodies of video creators, dance performers, or gaming interfaces. In response, Bilibili pioneered Smart Danmaku (智能防挡弹幕).

Instead of performing heavy server-side video re-encoding, Bilibili ships an AI segmentation pipeline directly to the user's browser using WebAssembly and WebGPU:

[Raw Video Stream] ──► [HTML5 Video Element]
         |
         ├─► [WebGPU Texture Sampler (Every N Frames)]
         │         |
         │         v
         │   [MobileNetV3 / U-Net AI Segmentation Model]
         │   (Compiled to WebAssembly / WebGPU Compute Shader)
         │         |
         │         v
         │   [8-Bit Alpha Silhouette Mask Texture]
         │
         v
[Danmaku Canvas Layer] ──► Applies CSS 'mask-image' or WebGL Stencil Buffer
         |
         v
[Final Composited Viewport: Danmaku travels behind creator automatically]

For high-efficiency desktop and mobile browsers, the model outputs a low-resolution (e.g., 320x180) 1-channel alpha mask. The graphics engine interpolates the mask using bicubic hardware texture filtering and binds it to the Danmaku WebGL layer as a stencil test mask:

// GLSL Fragment Shader: Danmaku Silhouette Occlusion
precision mediump float;
uniform sampler2D u_danmakuTexture;
uniform sampler2D u_personMaskTexture;
varying vec2 v_texCoord;

void main() {
    vec4 danmakuColor = texture2D(u_danmakuTexture, v_texCoord);
    float personAlpha = texture2D(u_personMaskTexture, v_texCoord).r;

    // Discard danmaku pixels if a human is detected in the foreground
    if (personAlpha > 0.5) {
        discard;
    }

    gl_FragColor = danmakuColor;
}

5. Binary Protocol Optimization: Slashing Serialization Overhead

A naive JSON payload for a single Danmaku message requires extensive metadata:

// Inefficient JSON Format (~260 Bytes)
{
  "room_id": 1049281,
  "timestamp": 1732349012841,
  "user_id": 9928172,
  "user_name": "tech_master_2026",
  "content": "AWS Lambda cold starts are solved!",
  "color": "#00FFCC",
  "font_size": 25,
  "mode": 1
}

At 500,000 messages per second, broadcasting raw JSON would burn 130 MB/sec of network bandwidth purely on stringified JSON keys. Bilibili compresses this into a strict 16-byte fixed binary header followed by a Protocol Buffer payload:

+---------------------------------------------------------------------------------+
|                       BILIBILI BINARY PACKET FRAME SPEC                         |
+---------------------------------------------------------------------------------+
| Offset | Size   | Field Type   | Description                                     |
+--------+--------+--------------+-------------------------------------------------+
| 0x00   | 4 Byte | uint32 (BE)  | Total Packet Length (Header + Body)             |
| 0x04   | 2 Byte | uint16 (BE)  | Header Length (Default: 16 Bytes)               |
| 0x06   | 2 Byte | uint16 (BE)  | Protocol Version (0=Plain, 2=Zlib, 3=Brotli)    |
| 0x08   | 4 Byte | uint32 (BE)  | Operation Code (2=Heartbeat, 5=Danmaku, 7=Auth) |
| 0x0C   | 4 Byte | uint32 (BE)  | Sequence ID                                     |
| 0x10   | Var    | Binary Data  | Protobuf Message Body                           |
+---------------------------------------------------------------------------------+

By packing multiple comments into a single Brotli-compressed WebSocket chunk, Bilibili reduces per-message network footprint from 260 bytes to just 18 bytes, achieving an astonishing 93% bandwidth reduction.

6. Production Reliability: Graceful Shedding & Density Control

During unexpected traffic floods, no client device can render 50,000 text elements simultaneously without frame rate degradation. Bilibili implements a 3-tier backpressure and degradation system:

  • Server-Side Downsampling: When room ingress exceeds 5,000 msgs/sec, the Job tier samples messages based on user privilege tiers (e.g., VIP members and coin donors receive priority transmission, while anonymous comments are sampled with a 20% acceptance filter).
  • Client-Side FPS Governor: If the HTML5 canvas frame rate drops below 45 FPS, the client dynamically increases the collision rejection threshold, discarding low-priority bullet comments locally.
  • Keyword Clustering & Merging: If 500 users simultaneously send identical comments (e.g., "666" or "GG"), the client-side engine merges them into a single high-visibility combo bubble with a multiplier badge (e.g., "666 x 540").

7. Frequently Asked Technical Questions

How does Bilibili prevent epoll thundering herd problems when thousands of clients disconnect simultaneously?

Bilibili uses Linux SO_REUSEPORT socket options to allow multiple independent worker processes to bind to the same listening port. The Linux kernel automatically distributes incoming and disconnected socket notifications across worker epoll instances via 4-tuple hashing, eliminating lock contention and thundering herd wakeups.

Why does Bilibili use WebSockets rather than HTTP/3 Server-Sent Events (SSE) for Danmaku?

While SSE is efficient for unidirectional server-to-client streaming, WebSockets provide a full-duplex TCP/TLS pipeline. In Bilibili's architecture, clients send high-frequency heartbeat pings every 30 seconds to maintain connection routing state in edge gateways, while simultaneously submitting client-side telemetry (such as local rendering drop rates). A single bidirectional WebSocket connection avoids opening multiple TCP handshakes.

How does the WebAssembly AI segmentation model run smoothly on mobile devices without draining the battery?

The client does not execute the neural network on every video frame. Instead, it evaluates frames at a reduced cadence (e.g., 6 to 10 FPS) and uses lightweight optical flow vector tracking on the GPU to interpolate the silhouette mask across intermediate 60FPS frames. Furthermore, if the device reports low battery or thermal throttling via the Battery Status API, the client automatically falls back to standard rendering without AI masking.

How are Danmaku comments stored and synchronized for on-demand (VOD) playback?

For recorded videos, Danmaku comments are persisted in distributed NewSQL databases (TiDB) and partitioned into 6-minute chronological chunks. When a user streams a video, the client pre-fetches the binary Protobuf Danmaku segment corresponding to the current video playback offset and caches it in IndexedDB, matching comments to the exact millisecond timeline of the video element.

How does Bilibili perform sensitive content moderation at sub-second latencies?

Moderation is split into a multi-stage pipeline: First, an in-memory Deterministic Finite Automaton (DFA) / Aho-Corasick keyword trie evaluates banned phrases in under 50 microseconds. Second, suspicious comments pass to quantized transformer models (BERT) hosted on Triton Inference Clusters. Comments that pass both checks are pushed to Kafka in under 8 milliseconds.

What rendering backend is used for Danmaku: DOM elements, Canvas 2D, or WebGL?

Bilibili uses hardware-accelerated WebGL / Canvas 2D. Rendering hundreds of moving HTML DOM elements causes continuous browser reflow and layout recalculations. WebGL renders text using pre-rasterized glyph texture atlases, submitting all active flying comments in a single instanced draw call per frame.

How does Bilibili Kratos framework handle service mesh communication between Comet and Job nodes?

Kratos provides native gRPC streaming clients equipped with connection pooling, autonomous service discovery, and client-side load balancing via round-robin or P2C (Pick First of Two Choices) algorithms based on server latency feedback. This ensures that broadcast jobs distribute evenly across all active Comet instances.

Authored by Shiva Vinodkumar, Founder & Principal Software Architect at HelloAIHub. For further deep-dives into high-concurrency event streaming, explore our masterclasses on Event Streaming Architectures and Multi-Host SFU Live Streaming.

Up Next: Recommended Deep Dives

Continue Exploring Architecture Masterclasses