Authentication, Real-Time Danmaku, and Multi-Device Playback: Engineering Practices for Video and Content Platforms

    This article presents a practical architecture for video and content platforms that need to support login across devices, real-time interaction, and continuous playback. It describes a layered design, multi-session authentication, QR-code authorization, playback progress synchronization, danmaku and comment handling, entitlement checks, resilience, observability, and a phased delivery plan with measurable acceptance criteria.

    1. Problem Definition: Four Core Pressures in Content Platforms

    A typical content-consumption platform exposes three observable user behaviors: opening content, participating in interactions, and resuming playback across devices. These behaviors map to four technical challenges.

    1. Identity and login state: Users may be online simultaneously on phones, tablets, desktop clients, and browsers. The system must support one login usable across multiple devices, while also enabling single-device logout, login alerts for unusual locations, QR-code authorization, and risk-control interception.
    2. Interaction write peaks: Danmaku is a high-frequency append workload on a timeline, while comments are read-heavy with hierarchy and sorting. Their read/write ratios and consistency requirements are different.
    3. State synchronization: Playback progress must converge across devices and tolerate disconnections, out-of-order events, clock drift, and duplicate reports.
    4. Entitlement verification: Membership status, content classification, and concurrent-stream limits must be checked efficiently on the critical path without becoming a single point of failure.

    If these capabilities are coupled inside one monolithic service, any traffic fluctuation can amplify into a global failure. Therefore, the first step is not technology selection; it is splitting capabilities by change frequency and load characteristics.

    2. Layered Architecture Overview

    A five-layer structure with clear responsibility boundaries is recommended:

    Layer Responsibilities Key constraints
    Access layer Terminal adaptation, rate limiting, canary routing Stateless and horizontally scalable
    Authentication layer Session issuance and validation, risk control Validation cost must be low enough
    Business layer Progress synchronization, danmaku, comments, entitlements Split by domain and evolved independently
    Middleware layer Message queue, distributed cache, asynchronous tasks Peak shaving and eventual consistency
    Data layer Relational database, object storage, search and logs Hot/cold separation and auditability

    The architectural principle is: the synchronous path should perform only necessary decisions, while heavy work should be pushed into asynchronous processing. For example, sending danmaku can perform only identity validation and content safety checks on the synchronous path; persistence and distribution can be completed asynchronously through a message queue. Playback progress reporting can use a write buffer and batch persistence approach.

    3. Login Authentication and Multi-Device Session Design

    3.1 Session Model

    A session should not be just a long-lived token. It should be split into two layers:

    • Access credential: short-lived, carried with each request, used only for server-side validation, with a small exposure window;
    • Refresh credential: longer-lived, bound to device fingerprints, usable only on controlled endpoints, and capable of rotation and revocation.

    The key to multiple concurrent devices is “multiple sessions for the same user,” not “one global session.” A recommended data structure is:

    1. CREATE TABLE user_session (
    2. session_id VARCHAR(64) PRIMARY KEY, -- Session ID
    3. user_id BIGINT NOT NULL,
    4. device_id VARCHAR(64) NOT NULL, -- Device identifier
    5. terminal_type TINYINT NOT NULL, -- 1=App 2=Web 3=Tablet 4=Large screen
    6. login_mode TINYINT NOT NULL, -- 1=Password 2=Verification code 3=QR code
    7. created_at BIGINT NOT NULL,
    8. last_active_at BIGINT NOT NULL,
    9. revoked TINYINT NOT NULL DEFAULT 0,
    10. KEY idx_user_active (user_id, revoked, last_active_at)
    11. );

    Hot session data, such as validation results and entitlement snapshots, should be placed in a distributed cache. The database should serve as the authoritative store for auditing, while cache misses trigger reloading from the source to avoid hitting the database on every request.

    3.2 Optimizing the Validation Path

    Login-state validation occurs on every request and is a typical hot path. Available strategies include:

    1. Local gateway validation: Access credentials use asymmetric signatures, allowing the gateway to verify signatures offline with a public key without a source lookup;
    2. Local short-lived cache: Cache session status, such as whether a session is revoked, for milliseconds or seconds, accepting a very small state-delay window;
    3. Active revocation broadcast: Logout, ban, and similar actions publish invalidation events through a message queue. Gateway instances consume these events and immediately clear local caches.

    3.3 QR-Code Login and Risk Control

    QR-code login is essentially a one-time cross-device authorization handshake. A recommended implementation is:

    1. 1. The pending login device generates a qr_id, sets it to pending, and assigns an expiration time.
    2. 2. The pending login device polls the qr_id status: pending / scanned / confirmed / expired.
    3. 3. The logged-in device scans the QR code -> validates its login state -> sets qr_id to scanned.
    4. 4. The user confirms the authorization -> a new session is generated -> status becomes confirmed and credentials are returned once.
    5. 5. After receiving confirmed, the pending login device immediately invalidates qr_id to prevent replay.

    Related risk-control measures include: a maximum number of sessions per account, rate limiting by IP and device, detection of abnormal geographic locations and short-term multi-device logins, and fallback CAPTCHA or behavioral verification. All decisions should be recorded in a logging service to form an auditable evidence chain.

    4. Multi-Device Playback Progress Synchronization

    4.1 Reporting Data Model

    Progress is a mergeable state with a version, not an immutable record:

    1. CREATE TABLE playback_progress (
    2. user_id BIGINT NOT NULL,
    3. content_id BIGINT NOT NULL,
    4. position_ms INT NOT NULL, -- Playback position in milliseconds
    5. duration_ms INT NOT NULL,
    6. version BIGINT NOT NULL, -- Monotonically increasing version
    7. updated_at BIGINT NOT NULL,
    8. PRIMARY KEY (user_id, content_id)
    9. );

    4.2 Reporting Strategy

    • Throttle instead of reporting every frame: Clients should report at fixed intervals or on key events such as pause, episode switch, exit, or moving to the background, avoiding writes for every frame;
    • Idempotency key: Each report carries a triple of content_id + version + position_ms. The server uses this to deduplicate, ensuring duplicate delivery has no side effects;
    • Forward-only principle: By default, only updates with an increasing position are accepted. When users manually seek backward, an explicit flag allows the update;
    • Batch merging: The server first aggregates messages in the queue, merges by the same user_id key, and then writes to storage at a low frequency, significantly reducing database write pressure.
    1. def report_progress(user_id, content_id, position_ms, version, is_seek=False):
    2. # Idempotency check: discard old versions or duplicate positions
    3. if version <= cache.get(f"p:{user_id}:{content_id}:v"):
    4. return "duplicated"
    5. if not is_seek and position_ms <= cache.get(f"p:{user_id}:{content_id}:pos"):
    6. return "stale"
    7. cache.setex(f"p:{user_id}:{content_id}:pos", position_ms)
    8. cache.setex(f"p:{user_id}:{content_id}:v", version)
    9. # Persist asynchronously to avoid blocking the reporting request
    10. mq.publish("progress.sync", {
    11. "user_id": user_id, "content_id": content_id,
    12. "position_ms": position_ms, "version": version
    13. })
    14. return "ok"

    4.3 Cross-Device Convergence and Clock Issues

    Device clocks are untrusted, so all time semantics must be unified to server time:

    • Use the server receive time as authoritative during reporting; client time is only a reference;
    • When fetching progress, return position_ms + server_now + version, allowing the client to calculate local offset;
    • When multiple devices resume playback at the same time, prefer the larger version; if versions are equal, prefer the newer server time;
    • During disconnection, clients persist a pending reporting queue locally. After reconnection, they resend in version order, and the server absorbs duplicates idempotently.

    5.1 Read-Write Separation for Danmaku

    Danmaku has these characteristics: high-frequency append writes along a timeline and batch reads for second-level intervals.

    • Write: Clients submit fields such as content_id, timeline offset, text, and color/style. After login-state and content-safety checks on the synchronous path, messages are delivered to a queue, and consumers persist them in shards;
    • Read: Fetch danmaku in the [start_ms, end_ms] range. Popular ranges for a piece of content can be cached in a distributed cache’s sorted set, sorted by timeline offset, which naturally supports range queries:
    1. ZADD danmaku:{content_id} {offset_ms} {danmaku_id}
    2. ZREVRANGEBYSCORE danmaku:{content_id} {end_ms} {start_ms}
    • Degradation: When an interval contains too much data, sample and deduplicate by policy, such as merging identical text with a count, to maintain stable front-end rendering rhythm. Large content should be served through object storage and delivered nearby by a content delivery network to reduce origin pressure.

    5.2 Tree Structure of Comments

    Comments are suitable for relational database storage, with search engines supporting query capabilities:

    1. CREATE TABLE comment (
    2. comment_id BIGINT PRIMARY KEY,
    3. content_id BIGINT NOT NULL,
    4. parent_id BIGINT NOT NULL DEFAULT 0, -- 0 means top-level comment
    5. root_id BIGINT NOT NULL DEFAULT 0, -- Redundant root ID for whole-tree queries
    6. user_id BIGINT NOT NULL,
    7. body VARCHAR(1000) NOT NULL,
    8. like_count INT NOT NULL DEFAULT 0,
    9. status TINYINT NOT NULL DEFAULT 1, -- 1=normal 2=pending review 3=deleted
    10. created_at BIGINT NOT NULL,
    11. KEY idx_content_root (content_id, root_id, created_at)
    12. );

    Design points: limit nesting depth, typically showing two levels and collapsing deeper levels; use the redundant root_id to turn a multi-level tree into a one-dimensional query grouped by root; use cached counters plus scheduled reconciliation for likes and similar counts to avoid hot-row updates; use soft deletion with a status flag to preserve review and appeal capabilities.

    5.3 Content Safety

    Text-based interactions must pass safety checks before becoming publicly visible. Recommended practice: synchronously call lightweight rules and sensitive-word matching for pre-blocking; send high-risk content to a “pending review” state and asynchronously submit it to human or model review; retain logs for original text, review conclusions, and operator actions to satisfy compliance audit requirements.

    6. Membership Entitlements and Permission Checks

    The goal of entitlement checks is to be non-blocking on the main path and able to fall back quickly. Implementation recommendations:

    1. Entitlement snapshot: Cache user entitlements, such as membership level, content scope, and concurrent stream count, as versioned snapshots in the authentication layer. Changes are refreshed asynchronously through events;
    2. Unified decision API: Content requests carry content identifiers, and the entitlement service returns allow / deny / degrade. The degrade state can be used to lower resolution or bitrate instead of directly denying access, improving experience in weak-network and entitlement-boundary scenarios;
    3. Canary switch: All entitlement rules are delivered by a configuration center and support gray release by user buckets. If problems occur, new rules can be disabled within seconds;
    4. Reconciliation mechanism: Periodically compare entitlement snapshots with authoritative data to correct inconsistencies caused by lost events.

    7. Availability, Resilience, and Observability

    • Containerization and elasticity: Deploy the stateless access and business layers on a container platform, with automatic scaling based on metrics such as QPS, latency, and queue backlog to handle predictable traffic spikes such as live events and new content launches;
    • Rate limiting and degradation: The access layer applies rate limiting by user, device, and API dimensions. A recommended degradation order for core links is: danmaku sampling → non-critical comment fields → delayed progress persistence → delayed entitlement snapshot refresh, ensuring playback remains unaffected;
    • Peak shaving: All write-heavy scenarios pass through a message queue buffer. Consumers process in parallel by partition, using content_id or user_id as the partition key to preserve ordering for the same entity;
    • Observability: Metrics and alerting, logging, and distributed tracing must be integrated. Core metrics should include: login success rate and success rate by login method, session validation P99 latency, danmaku send success rate and end-to-end visibility latency, progress report idempotency hit rate, entitlement decision hit rate and degradation count, queue backlog, and consumption delay;
    • Alert design: Alerts should be tied to executable remediation actions and responsible owners to avoid alert floods that dilute attention.

    8. Launch Path and Acceptance Recommendations

    It is recommended to proceed in four phases, with each phase accepted based on quantifiable metrics rather than feature completion:

    1. Phase 1: Authentication foundation. Enable multi-device login, session issuance and revocation, and QR-code authorization. Acceptance focuses on login success rate, validation latency, and abnormal login interception rate.
    2. Phase 2: Progress synchronization. Complete idempotent reporting, batch persistence, and cross-device convergence. Acceptance focuses on report loss rate and cross-device consistency rate, meaning progress differences across devices for the same account remain within a threshold.
    3. Phase 3: Interaction pipeline. Implement danmaku writing and interval fetching, the comment tree, and review flows. Acceptance focuses on send success rate, visibility latency, and rendering smoothness after sampling.
    4. Phase 4: Entitlements and resilience. Implement entitlement snapshots and canary switches, rate-limiting and degradation plans, and full-chain load testing. Load testing should use shadow traffic close to production or an isolated test environment. Capacity baselines should be based on measured data rather than estimates, and scaling thresholds should be calibrated accordingly.

    9. Common Pitfalls

    • Treating session validation as a database query: This is an easily overlooked hotspot. It should be replaced with signature validation plus a local short-lived cache.
    • Writing danmaku directly to the database: High-frequency random writes can overload the primary database. Use queue buffering and sharded persistence.
    • Relying on client time for ordering: Both cross-device progress and danmaku timelines should use server time or a monotonically increasing version as the sole decision basis.
    • Tightly coupling entitlement checks with content services: Entitlements change frequently, so they should be snapshotted and asynchronous, with a degradation path.
    • Ignoring duplicate delivery: Any asynchronous pipeline must assume messages can be duplicated and out of order. Idempotency keys and version numbers are the minimum requirement.

    Overall, the stability of this type of platform does not depend on the performance limit of any single component. It depends on clear boundaries, thorough asynchrony, complete idempotency, and usable degradation. If these four aspects are implemented solidly, the system will exhibit predictable resilience under traffic spikes and fault injection.