Designing an Account System for Content Platforms: Identity, Cross-Device Playback Sync, and Safety Practices
A practical walkthrough of how a large content platform should design its account system: a unified identity model for anonymous and logged-in users, login and token strategies across desktop, mobile, and web, playback-progress synchronization with conflict resolution and offline support, login gating and moderation for danmaku and comments, decoupled membership entitlements, notification delivery, layered architecture on cloud infrastructure, security and compliance controls, and the most common production failure modes with their fixes.
1. What the Login Prompt on a Homepage Tells Us About Account System Goals
The desktop homepage of a large content platform typically contains a handful of familiar elements:
- Top navigation: entry points for business lines such as the membership store, comics, and live events;
- Content area: long-form content such as currently airing anime series and films, presented as a “trending now” section;
- Client download prompt: a nudge to install the native app for a better viewing experience;
- Guest-state messaging: an explanation that signing in unlocks HD video, playback progress that follows the user across devices, and the ability to post danmaku or comments, together with a registration entry point;
- Post-login navigation: personalized entries such as premium membership, messages, feeds, and favorites.
Ordinary as these elements look, they sit on top of a complete account flow: a visitor browses content anonymously, enters an authenticated state by signing in or registering, unlocks interaction, membership, messaging, and favorites, and then expects consistent data across every device they own. From an engineering standpoint, that flow can be broken down into a capability matrix:
| Page element | Abstracted capability | Key challenge |
|---|---|---|
| Login and registration prompts | Identity and authentication | Reducing sign-in drop-off while keeping accounts secure |
| Trending content, client download | Content and client management | Consistent resources across devices; traffic spikes around releases |
| HD video | Membership entitlements and playback authorization | Mapping quality tiers to permissions; preventing link sharing |
| Cross-device playback progress | User state synchronization | Concurrent writes from multiple devices; weak networks and offline use |
| Danmaku and comments | Interaction and content safety | Guarding against anonymous abuse; moderation turnaround; danmaku floods |
| Premium membership | Entitlement system | Decoupling entitlements from business logic; consistent validity periods |
| Messages, feeds | Notification delivery and event-driven design | Delivery reliability; consistent unread counts |
| Favorites | User content organization | Paginating large lists; cross-device consistency |
The rest of this article works through these capabilities to describe an account system design that can actually be shipped.
2. Identity Model: Designing for Anonymous and Authenticated States Together
2.1 One Unified Expression of Both Identities
A guest and a logged-in user are the same person from the business’s point of view. The only difference is whether that person has declared an identity. The recommended approach is to define a single account identifier in the user service: it is created at registration time, and during the anonymous stage it is associated with a locally generated guest identifier. Once sign-in succeeds, that guest identity is bound to the account.
No business module should ever branch on “is this user logged in.” Instead, each module receives a uniform current-user context — the authenticated user ID, the guest identifier, and the client type.
The immediate benefit is that logic in features such as favorites and playback history is written once, against the “current user,” without a separate code path for the anonymous state. Anonymous data is inherited automatically after sign-in, so users never experience the feeling that their favorites vanished the moment they logged in.
2.2 Sign-In, Registration, and Multiple Entry Points
Showing sign-in and registration as two separate entry points on the page does not mean they belong to two different account systems. A “phone number plus one-time code” scheme unifies them: on the first verification, if the account does not exist, it is created automatically and the user is signed in immediately, eliminating an extra form redirect.
The desktop, mobile, and web clients should also converge on a consistent set of methods:
- Password sign-in: HTTPS encryption in transit, and on the server side storage of a salted strong hash only. Reversible encryption at rest and plaintext transmission are both unacceptable.
- One-time code sign-in: rate-limit sends per phone number and per device, and add behavioral verification to resist automated abuse.
- Federated sign-in: adapt to the standard protocols rather than coupling the account system to the details of any particular provider.
- QR-code sign-in: the mobile device displays a single-use QR code, and the desktop client polls for status or receives it over a persistent connection. The code needs a short expiry, must be usable only once, and the scanning device and the confirming device must be verified to belong to the same account so the code cannot be screenshotted and redeemed by someone else.
When the page prompts the user to download the client, the best practice is to generate download parameters that carry attribution information. The client can then identify the user’s origin on first launch, and when the user later signs in, that origin can be associated with the account, producing a traceable conversion path.
2.3 Tokens, Sessions, and Multi-Device Login Policy
After a successful sign-in, the authentication service issues tokens. The usual model is a short-lived access token paired with a long-lived refresh token:
- Access token: short validity. The API gateway verifies the signature and expiry and lets the request through without calling back to the authentication service.
- Refresh token: bound to a device and session, and revocable at any time.
- Sensitive operations: changing a password or rebinding a phone number requires a second verification step.
Video platforms usually need several devices online at the same time, so the multi-device login policy is a trade-off between security and experience. The options are:
- Unlimited concurrent devices;
- A cap on concurrent sessions per client type;
- Kicking older sessions offline when a new one appears;
- Requiring a second verification for new devices.
Whichever policy you choose, provide device management and a one-click sign-out-of-everywhere capability. Token verification logic should stay as centralized as possible:
// VerifyToken validates an access token and returns the user context for reuse by every business service.func VerifyToken(token string) (*UserContext, error) {// 1. Verify signature and expiry (for self-contained tokens).claims, err := parseAndVerify(token)if err != nil || claims.Expired() {return nil, ErrUnauthorized}// 2. Check whether the session has been revoked (sign-in from a new location, password change, explicit sign-out).if sessionRevoked(claims.SessionID) {return nil, ErrUnauthorized}// 3. Account state: reject outright if the account is banned or deactivated.if accountDisabled(claims.UserID) {return nil, ErrForbidden}return &UserContext{UserID: claims.UserID, Terminal: claims.Terminal}, nil}
3. Playback Progress: The Hard Core of Cross-Device Sync
“Playback progress that follows the user across devices” is one of the login benefits that best demonstrates the value of an account, and one of the easiest things to get wrong in engineering. Users watch a series on their phone during the commute and want to continue on the big screen when they get home. If synchronization lags by several minutes, the experience falls apart.
3.1 Data Model Design
Playback progress is essentially state data keyed by user and resource:
CREATE TABLE playback_progress (user_id BIGINT NOT NULL COMMENT 'User ID',resource_id VARCHAR(64) NOT NULL COMMENT 'Content resource ID (distinguishes individual episodes)',position_ms INT NOT NULL DEFAULT 0 COMMENT 'Playback position (milliseconds)',duration_ms INT NOT NULL DEFAULT 0 COMMENT 'Total content duration (milliseconds)',progress DECIMAL(6,4) NOT NULL DEFAULT 0 COMMENT 'Watched ratio',status TINYINT NOT NULL DEFAULT 0 COMMENT '0 = incomplete, 1 = finished',device_id VARCHAR(64) NOT NULL DEFAULT '' COMMENT 'Device of the most recent report',version BIGINT NOT NULL DEFAULT 0 COMMENT 'Version number, used for conflict resolution',updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (user_id, resource_id)) COMMENT 'Playback progress table';
Three design points matter here:
- The granularity is user × individual episode. A multi-episode series has to be tracked episode by episode; recording only at the series level loses the position when a user switches episodes mid-way.
- The unique key makes writes naturally idempotent. One user and one resource produce exactly one row, so repeated reports cannot create dirty data.
- Device and time information is retained. It provides the basis for later conflict resolution and device management.
Watch history is normally derived from the progress records: any row whose status is “finished” counts as history. You can also maintain a separate history table recording first-watched time, last-watched time, and watch counts. For platforms with very large data volumes, shard the database by a hash of the user ID, and index the history list on last-watched time for sorting.
3.2 Reporting Cadence and Traffic Shaping
The client cannot know when a user will switch devices, so it has to keep reporting — but the frequency must be controlled. The common approach is:
- Periodic heartbeat: report every 15–30 seconds while playing;
- Key events: report immediately on pause, seek, quality change, backgrounding, and player exit;
- Server-side completion detection: mark the item as finished when the position passes a threshold (for example 95%) and only a very short remainder is left.
On the night a popular series drops, millions of users watch at the same time and the report rate per second becomes extremely dense. A sound pipeline looks like this:
- The gateway handles authentication and rate limiting;
- The playback service writes the latest progress into an in-memory cache;
- Report messages are published to a message queue;
- Consumers aggregate by “user + resource,” reduce the frequency, and batch the writes to the database;
- A change event is emitted for cross-device push or for notifying the other clients.
This reflects a general rule for synchronization-heavy workloads: writes are high-frequency, persistence is low-frequency. Externally, updates appear to land within milliseconds; internally, a message queue flattens the write pressure.
3.3 Conflict Resolution and Cross-Device Consistency
Concurrency across devices is inevitable. A user reaches the 40-minute mark on a phone, pauses, and opens the desktop client. The stale desktop page may still show progress from two hours ago and may upload an outdated position. Handled carelessly, the phone’s newer progress gets pulled backwards. The following principles work well:
- Treat the server’s receive time as the authoritative clock. Client clocks can be tampered with and are never in sync, so they are only an auxiliary reference.
- Overwrite only when the progress differs significantly and the newer data is plausible — for example, a gap of more than ten seconds, or one side finished and the other not.
- Union the finished flag. If any device has watched it, it counts as watched, which avoids duplicate recommendations.
- Allow small backward moves. A user dragging back to the beginning to rewatch is normal behavior; ignoring backward moves pins the progress at the furthest point forever.
- Increment the version number on every accepted update and cache it alongside the change time so other devices can decide whether they need to refresh.
Illustrative code:
// MergeProgress merges playback progress reported from multiple devices and returns whether an update is needed.func MergeProgress(old *Progress, in *ProgressReport, serverNow int64) bool {if in.Status == StatusFinished {if old.Status != StatusFinished {old.Status = StatusFinishedreturn true}return false}// The server receive time must be newer than the existing record.if in.ReceiveTime <= old.UpdatedAt {return false}// Ignore tiny differences to avoid thrashing writes.if abs(in.PositionMs-old.PositionMs) < minUpdateGapMs {return false}// A backward move that conflicts with a finished record: ignore the position.if old.Status == StatusFinished && in.PositionMs < old.PositionMs {return false}old.PositionMs = in.PositionMsold.UpdatedAt = in.ReceiveTimeold.Version++return true}
The read path matters just as much:
- When a user starts playback on the web, the playback service returns the latest server-side progress in the same response, and the frontend decides whether to resume from the previous position or start over.
- For mobile and desktop clients, a lightweight notification can be pushed over a persistent connection when progress changes; the client then fetches the details.
- Compare relative position rather than absolute seconds across devices. When the same content plays on different clients, the beginning may differ by a few seconds. Using the watched ratio or the remaining time until the end as the reference avoids a systematic offset in the resume position.
3.4 Weak Networks, Offline Use, and Guest Data Inheritance
Mobile networks fluctuate constantly, so the synchronization path has to tolerate disconnects:
- The client persists the most recent playback position locally and re-reports when connectivity returns or playback resumes.
- Report requests carry a client-generated request ID, and the server deduplicates idempotently on it.
- While signed out, progress can be kept locally and submitted with the first request after sign-in, which implements guest progress inheritance.
4. Danmaku and Comments: Login Gating and Content Safety
The homepage lists posting danmaku and comments as a post-login capability, and that is no accident. Danmaku is highly sensitive to the playback timeline: a single malicious bullet comment affects every viewer watching that moment at once. Interactive features therefore have to put “trustworthy identity” and “controllable content” first.
4.1 Tiered Gates
For new and low-risk accounts, restrictions can be applied in stages:
- behavioral verification before a message is accepted;
- rate limiting by content density, for example one message per second, with identical content blocked from resending within a given window;
- an observation period for newly registered accounts, with a lower daily sending cap;
- a user trust score that adjusts permissions dynamically based on violation history.
Together these measures resist automated flooding while having almost no impact on normal viewing.
4.2 Moderation and Danmaku Floods
Danmaku is high-volume, real-time, and scattered across the timeline. The workable strategy is “automated screening first, human review as a backstop”: a general-purpose text content-safety service performs the initial filtering, hits are routed to a human review queue, and high-confidence risks are blocked outright. Comments can use either post-then-review or review-then-publish, chosen per scenario.
The harder problem is the danmaku flood: when a new episode drops or a pivotal scene arrives, a huge volume of bullet comments lands within seconds and exceeds what the rendering client can handle. Common mitigations are:
- Density-based sampling: show only a subset of danmaku within a given time window to keep the screen readable;
- Heat weighting: prioritize danmaku with more likes;
- Dynamic opt-out: provide toggles that hide danmaku by count or by keyword.
These content policies should be delivered as configuration so they can be adjusted without shipping a client update.
4.3 Server-Side Aggregation
Every client sees the same danmaku stream, so it must be generated and delivered by the server; clients must never generate it locally and maintain their own copies. A danmaku record typically carries the content ID, its appearance time on the timeline, the send time, the sender, the display mode, and the color. On delivery, the server paginates along the timeline and applies the necessary content-safety filtering to senders and content, which guarantees that different clients see the same result.
5. Premium Membership, Messages, Feeds, and Favorites
5.1 Decoupling Entitlements from Authorization
A premium membership is essentially a set of entitlements — higher playback quality, no ads, early access, exclusive cosmetics, and so on. The account system should only record whether a user holds a given entitlement, with a separate service computing it at runtime:
Entitlement = f(membership tier, validity period, business rules, additional conditions)
The playback service only asks “can this user play 1080P” and never asks why. Membership mechanics, promotional gifting, and bundled partner benefits can then change without touching the playback path. Every entitlement change should also be written to a ledger so it can be reconciled and audited.
Playback authorization has to cover distribution security as well: validate request legitimacy with a time-limited playback credential bound to the user identity, so resource URLs cannot be shared and reused.
5.2 Notification Delivery
The messages entry point carries system notifications, interaction notifications, and campaign notifications. It makes sense to split channels by business need:
- In-app inbox: persisted in the message center, with unread counts and pagination;
- Push notifications: for scenarios that need a strong prompt, respecting the user’s subscription preferences and operating-system constraints;
- Real-time channel: events that must be perceived immediately, such as playback-progress changes and interaction replies, delivered over a persistent connection.
Whichever channel is used, generate content from a unified message model plus template configuration, which makes multilingual and multi-client adaptation straightforward. Unread counts should use a dedicated counter updated in batches, rather than recomputing over the full list on every fetch.
5.3 Feeds and Favorites
A feed usually comes from the accounts a user follows or the series they subscribe to, which is a classic publish-subscribe scenario:
- when a series updates, publish a domain event and let the event system fan out to users subscribed to that series;
- reads and writes on the follow relationship need to balance timeliness against consistency, so a hybrid strategy of write fan-out as the primary mechanism with read fan-out as a supplement works well.
Favorites are a many-to-many relationship between users and content. A favorites collection typically has collections, entries, ordering, and tags, and it is read-heavy. Design for paginated queries along the user dimension, cache the favorites lists for popular content, and expose batch-operation APIs.
6. Overall Architecture and Cloud Infrastructure
6.1 Layered Architecture
The system divides into four layers:
- Access layer: content delivery network, load balancing, and the API gateway, responsible for TLS termination, routing, and basic rate limiting;
- Authentication and authorization layer: unified sign-in, token issuance and verification, risk control, and permission decisions;
- Business service layer: user, content, playback, interaction, entitlement, messaging, and favorites services;
- Data and middleware layer: relational databases, caches, message queues, object storage, search engines, and logging and monitoring.
A unified user context runs through every layer, so business services never reimplement login logic.
6.2 Principles for Using Cloud Resources
- Object storage: covers, transcoded video segments, and client installers;
- Content delivery network: serves content from the nearest edge location and reduces load on origin servers;
- Message queue: absorbs asynchronous traffic such as playback-progress reports and feed events;
- Container platform: hosts stateless business services and scales elastically around campaigns and new-episode releases;
- Monitoring and alerting: covers core metrics such as API success rate, latency, and queue backlog.
On Baidu AI Cloud, for example, developers can compose general-purpose cloud products such as object storage, message services, and containers to carry this kind of workload. What matters more, though, is the soundness of the architecture itself rather than any specific product choice.
6.3 Elasticity and Disaster Recovery
Traffic peaks at a new-episode launch or the start of a campaign can reach several times the daily norm. The countermeasures are:
- design core paths to be stateless so they can scale out quickly;
- route all static assets through the content delivery network;
- merge and rate-limit playback-progress writes to protect the database;
- configure circuit breaking and fallback for critical dependencies — for instance, allow playback at the default quality if the entitlement service is unavailable.
For disaster recovery, deploy across multiple availability zones, take regular backups of critical data such as accounts and playback records, and run failure drills on a schedule.
6.4 Observability
Around the account flow, the metrics worth watching closely are:
- sign-in success rate and the distribution of failure reasons;
- scan rate and confirmation rate for QR-code sign-in;
- volume of playback-progress reports and the persistence lag;
- notification delivery rate and deviation in unread counts;
- danmaku moderation block rate and backlog in the human review queue.
Distributed tracing should also be in place, tying a single playback request to its login session, entitlement decision, and progress update so problems can be localized quickly.
7. Security and Compliance Design
The account system is the core of platform security and needs protection across its whole lifecycle:
- Transport security: HTTPS end to end, with insecure protocols and weak cipher suites disabled;
- Authentication security: short-lived revocable tokens, salted password hashes, and a second verification step for sensitive operations;
- API security: rate limiting at the gateway along the user, device, and IP dimensions, with risk-control challenges for anomalous behavior;
- Data security: personal information such as phone numbers masked in the UI, and logs forbidden from recording passwords or full tokens;
- Content security: danmaku, comments, display names, and avatars all pass through content-safety moderation, with an audit trail of decisions;
- Account lifecycle: support for deactivation, data export, and deletion of personal information to meet compliance requirements.
It is also worth guarding against a sign-in storm. When a new version ships or a campaign begins, a large number of clients refresh tokens at once, so the authentication service needs either the capacity to verify them in bulk or a short-lived cache of token verification results.
8. Common Problems and Summary
Reviewing the whole design, the account system reduces to “one center, two flows, three lines of defense”:
- One center: a unified user identity, with anonymous and authenticated states sharing a single account model;
- Two flows: the authentication flow and the synchronization flow. Authentication prioritizes security and low drop-off; synchronization prioritizes timeliness and consistency.
- Three lines of defense: rate limiting and risk control at the access layer, authorization and idempotency at the service layer, and auditing and backups at the data layer.
A few recurring problems are worth restating:
- High synchronization lag: check reporting frequency, queue backlog, and consumer batching strategy first, rather than blindly scaling the database.
- Data loss after sign-in: verify the anonymous-data migration logic and request idempotency so repeated submissions cannot create dirty data.
- Inconsistent state across devices: always treat the server receive time as authoritative, and keep comparing relative position.
- Incorrect membership entitlements: consolidate entitlement computation in a dedicated service and let business modules consume only capability decisions.
Get the three main threads — identity, synchronization, and security — straight, and they will support a complete experience from anonymous browsing to seamless multi-device viewing.
