Video Platform Login and Cross-Device Data Synchronization: A Practical Engineering Guide

    This article walks through the engineering behind a video platform's login flow and cross-device data synchronization. Starting from a simple sign-in prompt, it maps out a full identity–authorization–data–interaction–monetization pipeline, then dives into five core topics: account and token-based sessions, playback progress synchronization across devices, danmaku (bullet comments) and comments, content distribution, and membership entitlements. For each area it covers data models, API design, consistency and security considerations, and how to deploy and monitor the system on the cloud. A set of common pitfalls and an engineering checklist close the article to help teams ship a reliable "remember where I left off" experience across mobile, web, TV, and more.

    1. Introduction: What a Login Prompt Reveals About an Account System

    Most content platforms show a prompt like this when a user tries to play or interact with something: “Sign in to watch HD video for free, sync your watch history across devices, post danmaku/comments, and keep up with trending content. First time here? Sign up.” Those few lines actually map onto a complete user-growth and data architecture:

    • Identity layer: “Sign in” and “sign up” are the entry points to the user system.
    • Experience layer: “HD video” and “trending content” point to playback quality and content distribution.
    • Data layer: “Sync watch history across devices” requires cross-device data consistency.
    • Interaction layer: “Post danmaku/comments” involves high-concurrency writes and content governance.
    • Monetization layer: Premium membership benefits rely on reliable identity verification and entitlement delivery.

    In other words, a single login action sits on top of a complete chain: authentication → authorization → data → interaction → monetization.

    This article follows that chain and distills five core topics—the login system, playback progress synchronization, danmaku and comments, content distribution, and membership entitlements. For each, it presents practical engineering solutions from the angles of data models, API design, consistency, and security, and explains how to deploy and monitor them on the cloud. The approach applies to any content product that needs to “remember where the user left off,” including video, audio, comic reading, and live-stream replays.

    2. Overall Architecture: Five Layers and Two Key Paths

    2.1 Layered Design

    The system divides into five layers:

    1. Access layer: Multiple terminals—mobile apps, web, TV, and in-car systems—enter the backend through a unified access gateway. The gateway handles transport encryption, rate limiting, basic authentication, and request routing.
    2. Service layer: Split by business boundary into account service, entitlement service, content service, progress service, danmaku service, interaction service (comments, favorites, feed), and messaging service.
    3. Data layer: A relational database stores strongly consistent data such as accounts, orders, and entitlements. A document or key-value store handles high-frequency read/write data such as progress, danmaku, and comments. A cache absorbs hot data. Object storage holds unstructured data such as avatars, covers, and danmaku word-list files.
    4. Async layer: A message queue decouples services and smooths traffic spikes, carrying tasks such as progress persistence, danmaku moderation, interaction counter updates, and push notifications.
    5. Support layer: Logging, monitoring/alerting, and a configuration center keep the system observable and governable.

    2.2 Two Key Paths

    • Write path: The client produces events such as playback heartbeats, danmaku, and comments. These are first written to an in-memory cache or a message queue, then persisted asynchronously, and finally surfaced to other terminals through cache invalidation or change notifications.
    • Read path: A request first checks the cache; on a miss, it reads from the database and backfills the cache. Read-heavy, write-light data such as resume progress, danmaku, and trending lists is especially well suited to this structure.

    3. Identity Layer: Registration, Login, and Token Sessions

    3.1 A Unified Model for Registration and Login

    From an engineering standpoint, “registration” and “login” are two phases of the same identity model:

    • Registration solves “how an account is bound to a real person,” commonly via phone number plus verification code, email verification, or username plus password.
    • Login solves “how to prove you own the account.” Beyond a password, it can also support SMS codes, QR-code authorization, and so on.

    Regardless of the method, the server should generate a unified internal user ID, and all downstream business systems should depend only on that ID. This isolates downstream systems from changes such as phone-number reassignment or account merging. The account system also needs to support account merging and recovery: when one phone number is linked to multiple historical accounts, there must be a clear data-migration and notification strategy.

    3.2 Authentication Security Essentials

    • Password storage: Store only a salted, slow hash. Never store plaintext, reversible encryption, or a simple digest. The hash algorithm should have a tunable computational cost to keep pace with hardware improvements.
    • Brute-force protection: Set attempt-frequency thresholds per account, per IP, and per device. Once exceeded, require a CAPTCHA or behavioral challenge and temporarily lock the account.
    • Transport security: Encrypt login, registration, and password-change traffic end to end, and give verification codes a validity window and single-use restriction.
    • Privacy compliance: Collect personal data such as phone numbers under a “minimum necessary” principle. Mask all logs—for example, keep only the first three and last four digits of a phone number.

    3.3 Token Design: Access Tokens and Refresh Tokens

    After a successful login, the server typically issues two credentials:

    Credential Lifetime Storage Usage
    Access token Short (e.g., hours) Client memory, never persisted to disk Sent with every business request; server validates signature and expiry
    Refresh token Long (e.g., days to weeks) Client secure storage area Used only to obtain a new access token; rotated on every refresh

    The “short access token + long refresh token” approach rests on three considerations:

    1. A short access-token lifetime limits the impact if it leaks.
    2. Refresh tokens are used only by the refresh endpoint, making server-side rotation and revocation straightforward.
    3. Tokens can be designed as self-contained signed tokens (such as the widely adopted JWT format), so the server only needs to validate the signature and claims to let a request through, without querying the database on every request—well suited to high-concurrency, multi-device scenarios.

    One caveat: a self-contained token cannot be changed immediately after issuance. Requirements such as entitlement changes, bans, and forced logout therefore cannot rely on the token alone; they also need a session version number or a server-side blacklist.

    The sample code below illustrates the structure only; the specific algorithms and key management must follow security best practices:

    1. import time
    2. import secrets
    3. # Keys are issued by a key management service; never hardcode them in the repository
    4. ACCESS_SECRET = load_secret("access-token-key")
    5. REFRESH_SECRET = load_secret("refresh-token-key")
    6. def issue_tokens(user_id: str, device_id: str, member_level: int):
    7. now = int(time.time())
    8. # Access token: self-contained, carries user, device, and entitlement version
    9. access = sign_jwt(
    10. key=ACCESS_SECRET, alg="HS256",
    11. claims={
    12. "sub": user_id, # User ID
    13. "jti": secrets.token_hex(8), # Unique token ID for precise revocation
    14. "did": device_id, # Device identifier for multi-device session management
    15. "ver": member_level, # Membership entitlement version, incremented on upgrade
    16. "iat": now,
    17. "exp": now + 2 * 3600, # Example: access token expires in 2 hours
    18. },
    19. )
    20. # Refresh token: opaque random string, resolvable only by the server
    21. refresh = secrets.token_urlsafe(32)
    22. store_refresh_token(refresh, user_id, device_id) # Write to the server-side session store
    23. return access, refresh

    3.4 Multi-Device Session Management

    “Cross-device synchronization” presupposes that the server knows “which terminals the user currently has online.” Assign each device a stable device ID and maintain an association among the user, the device, and the session:

    • Device list: Users can view their signed-in devices in settings.
    • Per-device control: Support forcing a device offline by incrementing the session version number or directly deleting that device’s refresh token.
    • Limit policy: Set a reasonable cap on simultaneously online devices, prompting users to sign out older devices when exceeded.
    • Anomalous-login alerts: Notify users via the message center when a new device or a login from a new location appears.

    3.5 Sample Authentication API

    1. POST /api/v1/auth/login
    2. Content-Type: application/json
    3. {
    4. "account": "+1****0000",
    5. "password": "<password>",
    6. "device": { "deviceId": "d-9f2c", "platform": "web", "appVersion": "3.2.1" }
    7. }
    1. HTTP/1.1 200 OK
    2. {
    3. "accessToken": "eyJhbGciOiJIUzI1NiIs...",
    4. "refreshToken": "8f3c...e21a",
    5. "expiresIn": 7200,
    6. "user": { "userId": "u-10086", "memberLevel": 0 }
    7. }

    4. Authorization Layer: From “Signed In” to “Permitted”

    Login answers “who you are”; authorization answers “what you are allowed to do.” The recommended approach combines role-based access control (RBAC) with attribute-based access control (ABAC):

    • RBAC manages coarse-grained permissions: regular users, content creators, moderators, and operations admins have different sets of actions.
    • ABAC handles fine-grained conditions: for example, “can delete only comments you posted,” “members can watch early-access content,” “banned users cannot send danmaku.”

    All permission checks must happen on the server. Greying out buttons or hiding menus on the client is only a UX optimization and cannot replace backend validation. The backend should follow a “default deny” principle and validate identity and permissions uniformly at the entry point of every protected endpoint.

    5. Data Layer (1): Cross-Device Playback Progress Synchronization

    5.1 Problem Definition

    “Sync watch history across devices” means: a user watches 20 minutes on their phone, then switches to web or TV and resumes from the same spot. The challenges are:

    • Many playback terminals with widely varying network conditions;
    • High reporting frequency and large data volume;
    • The same content possibly playing on multiple devices at once;
    • Messages that may arrive out of order, duplicated, delayed, or even lost.

    5.2 Data Model

    Use “user + content” as the unique key and store one progress record:

    Field Description
    user_id User ID
    content_id Content ID; for series, can be refined to the episode
    position_ms Playback position (milliseconds)
    duration_ms Total content duration
    rate Playback speed
    device_id Device of the most recent report
    updated_at Server-side update time

    Two principles guide the structure:

    1. Store positions as millisecond integers to avoid floating-point precision errors and unit confusion.
    2. Use server time as the source of truth; never trust client time. An inaccurate client clock or a user manually changing the clock would break comparisons.

    5.3 Reporting Timing and Strategy

    Reporting timing combines scheduled heartbeats with events:

    • Scheduled heartbeat: report at a fixed interval (e.g., every 5–10 seconds) during playback.
    • Key events: report immediately on pause, seek, episode switch, backgrounding, and player close.

    On the client side, maintain a local queue of pending reports. When the network recovers or a timer fires, batch them into a single request to reduce request count and power consumption. On page unload, browsers can use the page-visibility event together with a “keepalive” request to send the final heartbeat.

    Capacity estimation example: Assume 10 million daily active users, each watching 2 hours per day, with a 10-second heartbeat interval—roughly 720 million progress events per day. At about 200 bytes per record, raw data is around 144 GB. After batching and hot/cold tiered storage, the actual load is manageable. The key point: progress reporting should not write directly and synchronously to the relational database, or database connections and writes become the bottleneck.

    5.3.1 Idempotency, Out-of-Order Handling, and Conflict Resolution

    Idempotency: When a device retries and produces duplicate requests, deduplicate on “user + content + device + request sequence number,” or simply use a “larger update time wins” rule for natural idempotency.

    Out-of-order handling: Due to network latency, an earlier report may arrive after a newer one. The server accepts a write only when its update time is strictly greater than the stored record; otherwise it drops it. This is essentially “last write wins” (LWW)—simple to implement and sufficient for resume needs:

    1. def save_progress(user_id, content_id, client_ts, position_ms, duration_ms, device_id):
    2. now = server_now_ms()
    3. key = f"progress:{user_id}:{content_id}"
    4. old = cache.get(key)
    5. # 1. Out-of-order/replay: ignore reports older than the current record
    6. if old and client_ts <= old["clientTs"]:
    7. return old
    8. new = {
    9. "userId": user_id,
    10. "contentId": content_id,
    11. "clientTs": client_ts,
    12. "positionMs": min(max(position_ms, 0), duration_ms),
    13. "durationMs": duration_ms,
    14. "deviceId": device_id,
    15. "serverTs": now,
    16. }
    17. # 2. Atomic compare-and-set to avoid concurrent overwrites
    18. cache.set_if_newer(key, new)
    19. # 3. Persist asynchronously, invalidate the read cache, and notify other devices
    20. mq.publish("progress.persist", new)
    21. return new

    The same account watching the same content on multiple devices at once would make progress “bounce back and forth” under the above strategy. Products typically handle this by:

    • Using the most recently active device as the source of truth and informing the user in the device-switch prompt;
    • For simultaneous playback on multiple signed-in devices, showing a notice in the interaction area and, when necessary, limiting the number of concurrent playback devices.

    5.4 Client-Side Conflict Handling

    A user may watch offline and come back online, at which point the local progress is newer than the server’s, requiring a two-way merge:

    1. After a successful login, the client fetches the server progress and compares it with the local record.
    2. It compares using the “client-generated playback timestamp,” and the newer one wins.
    3. Conflicting items are batch-reported to the server, and the user is prompted “Resume from where you left off?”

    5.5 Progress Query and “Continue Watching”

    The “Continue watching” list is essentially a query sorted by update time in descending order. To avoid full-table scans on a large table, build a composite index on (user_id, updated_at) and return only recent records. Also handle several edge cases:

    • Finished watching: When the remaining duration is too short (e.g., under 5%), do not show it under “Continue watching.”
    • Progress deletion: When a user manually removes a record, use a tombstone marker or physical deletion and clear the cache accordingly.
    • Unavailable content: Filter out delisted content.
    • Guest progress: Keep guest-mode progress locally and upload it under merge rules after login, to lower the barrier to signing in.

    6. Data Layer (2): Danmaku—A Timeline-Driven Stream of Events

    6.1 Characteristics of Danmaku

    Danmaku (bullet comments) are short texts anchored to a video timeline, with these traits:

    • High write volume, peaking at moments such as a stream going live or a key plot point;
    • Reads dominated by range queries on “content + time interval”;
    • Each record is small but there are many of them, so storage cost and query efficiency matter.

    6.2 Bucketed Storage

    Bucket a content’s danmaku along the timeline—for example, one bucket per 10 seconds:

    1. danmaku:{contentId}:{start_time // 10}

    The player uses the current playback time to fetch only the few buckets within a window a few seconds before and after, plus a buffer. Benefits:

    • Small read ranges, avoiding fetching all of a video’s danmaku at once;
    • Hot/cold policies can be set per bucket, moving expired buckets to cheaper storage;
    • Writes spread evenly by content and time, avoiding hot spots.

    6.3 Send Path and Content Governance

    The recommended danmaku send path is “synchronous validation + asynchronous moderation”:

    1. Synchronous validation: sign-in state, content status, send frequency (e.g., a per-interval count limit), length limit, and sensitive-word filtering.
    2. Asynchronous moderation: write to a message queue; a moderation service performs machine review and, where necessary, human review.
    3. Visibility state: set three states—pending, visible, blocked. Only approved danmaku become visible to other users, while the sender sees an immediate echo from their own perspective.
    4. Backlog governance: For live scenarios with strong real-time demands, danmaku can be shown first and governed asynchronously; for on-demand content with higher retention requirements, “review before publish” is more appropriate.

    Sample code:

    1. def send_danmaku(user_id, content_id, text, play_time_ms, color=16777215):
    2. if not check_permission(user_id, "danmaku:send"):
    3. raise Forbidden("No send permission")
    4. if not rate_limit(f"danmaku:{user_id}", limit=20, window=60):
    5. raise TooManyRequests("Sending too frequently")
    6. if text_sensitive(text):
    7. return {"status": "blocked"}
    8. msg = {
    9. "msgId": gen_id(), "userId": user_id, "contentId": content_id,
    10. "timeMs": play_time_ms, "text": text, "color": color,
    11. "status": "pending", "createAt": server_now_ms(),
    12. }
    13. # Write the author-visible "pending" danmaku first, for real-time echo
    14. bucket = f"danmaku:{content_id}:{play_time_ms // 10000}"
    15. cache.zadd(bucket, msg["msgId"], play_time_ms)
    16. mq.publish("danmaku.audit", msg) # Asynchronous moderation
    17. return {"status": "pending", "msgId": msg["msgId"]}

    6.4 Danmaku Query API

    1. GET /api/v1/contents/{contentId}/danmaku?start=600000&end=620000

    Returns the approved danmaku within the time range, sorted in ascending time order, for the player to render along the timeline.

    7. Interaction Layer: Comments, Favorites, and Feed

    7.1 Comment System

    • Hierarchy: Mainstream products use a two-level “top-level + nested replies” structure, showing at most a few replies with an “Show more” option—balancing readability against query complexity.
    • Sorting: Sort by hotness (a composite of likes, replies, and time decay) or by time; pinned items are set by operations.
    • Pagination: Use cursor pagination (a combination of the last item’s sort value and ID), which avoids the performance degradation and duplicate data that offset pagination suffers during deep paging.
    • Counter fields: Store counts such as comment and like counts separately from the detail data, accumulate them via asynchronous messages, and serve reads preferentially from the cache.

    7.2 Favorites and Feed

    • Favorites: Essentially a many-to-many relationship between users and content. The API must be idempotent (repeat favorites do not error) and support grouping (favorite folders). Favorite counts are a classic high-frequency counter scenario and likewise suit the counter/detail separation pattern.
    • Feed: In “read-heavy, write-light” scenarios, follow streams are primarily pull-based. For top creators, a “push + pull hybrid” works well—writing to followers’ inboxes while keeping pull as a fallback—so a super-large account’s write fan-out does not overwhelm the system.
    • Messages: Events such as a reply to a comment, a like on content, or a system notification are published by the business services to a message queue. The messaging service persists them centrally, maintains unread counts, and delivers them to clients over a long-lived connection or a push channel.

    8. Experience and Monetization: Content Distribution and Membership Entitlements

    8.1 How Login Improves Content Distribution

    The value of login goes beyond identity recognition: behavioral data can be connected across devices.

    • Behavior collection: Impressions, clicks, watch time, completion rate, and danmaku/comment interactions are reported in a unified way and joined by user ID as the primary key.
    • Content profiling: Build a tagging system for content (genre, duration, popularity, audience).
    • Recall and ranking: The recall stage combines trending, collaborative filtering, and content tags; the ranking stage jointly estimates predicted click-through rate, completion rate, and diversity control.
    • Cold start: New users rely on trending lists and localized content; returning users combine cross-device watch history (a derivative value of “cross-device watch-history sync”).
    • Trending lists: Aggregated from recent play and interaction volumes over a time window, with the cache refreshed periodically.

    8.2 Membership Entitlement System

    Common entitlements include ad-free viewing, higher resolution, early access, and multiple simultaneous online devices. Key implementation points:

    1. Entitlement model: Organize data as “user—plan—entitlement item—validity period,” expressing entitlement items as fine-grained permission points (e.g., “playback:quality:1080p”) to avoid hard-coding entitlements into business logic.
    2. Server-side validation: Resolution switching, early-access unlocking, and ad-free policies are all decided by the entitlement service, with results delivered via the token or the API response.
    3. Real-time state sync: Payment success, renewal, refund, and expiry all change entitlements. When the entitlement service’s state changes, it publishes an event, and online push or a token-refresh mechanism syncs it to all clients.
    4. Order consistency: Payment callbacks can be duplicated, so order state needs idempotent handling. Payment channels, orders, and entitlements should be reconciled periodically to prevent “paid but no entitlement” or “entitlement without an order.”
    5. Auto-renewal compliance: Give prominent notice before charging, and provide an easy cancellation entry and clear unsubscribe instructions.
    6. Gradual rollout and experiments: Roll out entitlement entry points, pricing, and copy via the configuration center with staged releases, and evaluate conversion using experiment data.

    9. Security and Compliance: Baseline Requirements Across the Whole Chain

    1. Endpoint authorization: All business endpoints require a valid token by default; periodically audit for unauthenticated endpoints.
    2. Broken-access-control protection: The server verifies resource ownership to prevent users from reading others’ favorites or progress, or deleting others’ comments, by tampering with IDs.
    3. Anti-abuse and risk control: Apply multi-dimensional rate limiting to login, danmaku, comment, and like endpoints, and use device fingerprints and behavioral signals to identify anomalous accounts.
    4. Data protection: Minimize personal-data collection, encrypt it in transit and at rest, and mask logs.
    5. User rights: Provide account deletion and data-erasure capabilities with clear processing-time commitments.
    6. Content compliance: Maintain a keyword library, machine review, and human review, and retain necessary logs for traceability.
    7. Key management: Manage token-signing keys and database credentials through a key management service with regular rotation; never hardcode them.

    10. Cloud Deployment and Observability

    The capabilities above can be built on the general product categories of Baidu AI Cloud, with each component serving its responsibility:

    Capability need General product category Role
    Service deployment Container platform Containerize stateless services, elastic scaling by traffic
    Static assets and video Object storage Store covers, avatars, video segments, etc.
    Content acceleration CDN Serve video from nearby edge nodes; supports playback authentication and anti-leeching
    Hot data Cache service Sessions, progress, danmaku buckets, trending lists
    Async decoupling Message queue Progress persistence, danmaku moderation, interaction counters, push notifications
    Structured data Cloud database Accounts, orders, entitlements, comments, etc.
    Observability Log service / monitoring & alerting Centralized log search and metrics alerting

    Take the evening peak as an example: traffic for progress reporting and danmaku writes can reach several times the daily average. Stateless services scale in and out using the container platform’s elastic scaling, while write requests are buffered by the message queue and persisted at a steady rate—preventing a sudden traffic burst from overwhelming the database.

    At the same time, build a monitoring metric system that covers each path:

    Path Key metrics Alert reference
    Login/authentication Login success rate, verification-code send success rate, refresh-token failure rate Success rate drops abnormally
    Playback progress Report success rate, progress-sync latency, conflict-drop rate Latency keeps climbing
    Danmaku Send success rate, moderation backlog, fetch latency Moderation backlog exceeds threshold
    Interaction Comment publish failure rate, counter drift Counter/detail divergence widens
    Entitlements Entitlement activation latency, order-reconciliation discrepancy count Reconciliation discrepancy appears
    Content distribution Recommendation impression CTR, average watch time per user Core metrics fluctuate significantly

    11. Common Pitfalls and an Engineering Checklist

    In practice, the following issues recur:

    • Progress stored only on the device, lost on a device switch;
    • Comparing progress directly with client time, causing out-of-order results;
    • Synchronously writing progress to the relational database, which the peak overwhelms;
    • Long-lived tokens with no revocation mechanism, so bans and logouts cannot take effect immediately;
    • Entitlements such as resolution and ad-free judged only on the client, creating a bypass risk;
    • Loading all danmaku or fetching the entire video’s danmaku at once, causing stutter and wasted bandwidth.

    The corresponding design checklist:

    • A unified internal user ID, with pluggable authentication methods;
    • Short-lived access tokens, rotated refresh tokens, and per-device revocation;
    • All permission checks done on the server, default deny;
    • Progress stored in milliseconds and based on server time, with idempotent writes resilient to out-of-order arrivals;
    • Progress written to cache plus message queue, then persisted asynchronously;
    • Danmaku bucketed by time, with clearly defined moderation visibility;
    • Cursor-based comment pagination, with counters separated from details;
    • Membership entitlements modeled as permission points, synced in real time on change;
    • Full-chain authentication, masking, auditing, and alerting in place.

    12. Conclusion

    Behind a single login prompt lies an entire engineering system of “identity—authorization—data—interaction—monetization.” Login establishes identity; tokens and sessions support multi-device use; progress synchronization and danmaku design determine the cross-device experience; comments and favorites build interaction; and membership entitlements close the value loop. By thinking through each layer’s boundaries, data models, and exception paths—then implementing them on general cloud capabilities such as container platforms, caches, message queues, logging, and monitoring—you can deliver a product experience that is “synced across devices, smooth to interact with, and reliable in its entitlements.”