Account Login and Cross-Device Progress Sync Architecture for Multi-Platform Content Services
A practical guide to architecting account login and cross-device state synchronization for multi-platform content services. It covers a layered account model, token issuance with refresh-token rotation, device-scoped session management, and login hardening; how to keep favorites, playback progress, and messages consistent across browsers, mobile devices, and smart TVs; how to scale real-time danmaku and comments under high concurrency; how to build personalized feeds and rankings; and how adaptive-bitrate streaming, consistency trade-offs, canary rollout, and deployment round out the design.
1. Reading the architecture from a single portal page
On a mature content-consumption platform, the home page and channel pages are usually built from three kinds of elements: content entry points (vertical channels such as series, sports, live events, and comics), identity entry points (login, registration, and premium membership), and state entry points (messages, activity feed, and favorites). The first two serve acquisition and conversion; the third directly determines the quality of user retention.
The third category is where the hidden complexity lives, and it deserves a developer’s attention. Features that look simple—“favorites,” “messages,” “activity”—are at their core user-centric, stateful data. They require the system to present a consistent view of a user no matter which device they switch to: browser, mobile, smart TV, and so on. This is the central problem of multi-platform content architecture: how to keep one logical “user” in a consistent state view across multiple physically separate devices.
So a page’s technical breakdown reduces to four tightly coupled subsystems: identity and authentication, user-state synchronization, real-time interaction, and content delivery and recommendation. Each is covered below.
2. Unified identity: login, registration, and session management
2.1 A layered account model
A content platform typically needs to support several login methods: account and password, phone number with a verification code, and authorization via external social accounts. Good practice is to decouple the identity identifier from the identity credential:
- Principal: the platform’s internal unique user ID, independent of any login method.
- Identity: phone number, email, an external platform’s open identifier, and so on. One principal can bind multiple identities.
- Credential: password digest, verification-code state, third-party authorization token, and so on.
The value of this layering is that when a user changes their phone number or unbinds a social account, the internal principal stays the same, so all associated favorites, progress, and history are naturally preserved. If you use the phone number directly as the primary key, that kind of change triggers a disastrous data migration.
2.2 Token mechanism and refresh strategy
After a successful login, the server should not query the database to validate the session on every request. Instead, it should issue a time-limited access token together with a refresh token that has a longer lifetime. An illustrative implementation:
def issue_tokens(user_id: str, device_id: str) -> dict:access_ttl = 900 # Access token: 15 minutesrefresh_ttl = 30 * 86400 # Refresh token: 30 daysaccess = {"sub": user_id,"did": device_id,"iat": now_ts(),"exp": now_ts() + access_ttl,"jti": uuid4(), # Used for server-side revocation}refresh = {"sub": user_id,"did": device_id,"exp": now_ts() + refresh_ttl,"rotate": True, # Invalidate the old token after each refresh}return {"access_token": sign(access),"refresh_token": sign(refresh, stored_server_side=True),"expires_in": access_ttl,}
Two key design points. First, refresh tokens must be server-lookupable, so the system can support “log out all devices” and force sign-out after anomalous logins. Second, refresh tokens should use a rotation mechanism: each refresh issues a new refresh token and invalidates the old one. If a previously invalidated refresh token is ever reused, it means the token has leaked, and the user’s entire session chain should be revoked immediately.
2.3 Device-scoped session isolation
A typical scenario for a content platform is “watch halfway on the phone, then continue on the TV at home,” alongside “signed in on an internet-cafe PC earlier and want to sign out remotely afterward.” Session management must therefore carry a device dimension:
| Capability | Implementation |
|---|---|
| Multi-device coexistence | The token carries a device ID; the server maintains a user→device mapping. |
| Single sign-out (kick) | Clear historical tokens for the same device type after sensitive operations. |
| Device list | Record device model class, first-login time, last-active time, and login location. |
| Risk detection | Trigger step-up verification for logins from unfamiliar locations or from multiple devices in a short window. |
2.4 Hardening the login path
The login endpoint is the platform’s primary attack target. Defense should be layered at both the gateway and the service: rate-limit by failure count per user and per IP; escalate the challenge gradually after consecutive failures (image captcha → slider → SMS); store passwords with a salted slow-hash algorithm; and batch-detect credential-stuffing patterns (the same IP range trying the same weak password against a large number of accounts). These measures belong in the gateway so that individual business services do not each reimplement them.
3. Cross-device state sync: consistency of favorites, progress, and messages
3.1 Choosing a sync model
There are three common cross-device sync models, and they differ sharply in where they fit:
- Full overwrite: the client uploads a complete snapshot and the server replaces its state outright. Simple to implement, but it means heavy upload traffic on mobile, a high failure rate on weak networks, and mutual overwrites under concurrent multi-device writes.
- Incremental operation log: the client reports only the change actions (favoriting a video, deleting a history entry) and the server replays them in order. Clear semantics and low traffic, but it must handle out-of-order arrival and duplicate submissions.
- Merge-based sync (CRDT-style): assign each record comparable version information and merge conflicts automatically by rule. Well suited to set-like data such as favorites.
In practice, a hybrid of incremental reporting + version merging is common: the client reports changes, the server maintains each record with a monotonically increasing version number, and a cursor pulled at read time performs incremental reconciliation.
3.2 Handling playback progress specially
“Resume playback” is the highest-pressure sync scenario, because of the tension between reporting frequency and business value: report every 5 seconds and a two-hour viewing session produces thousands of writes; report only on exit and an abnormal exit loses the progress.
The recommended approach is a layered strategy:
class ProgressReporter:LOCAL_FLUSH_INTERVAL = 10 # Local persistence interval (seconds)REMOTE_FLUSH_INTERVAL = 30 # Remote reporting interval (seconds)FORCE_FLUSH_EVENTS = {"pause", "seek", "ended", "app_background"}def on_tick(self, pos_ms: int):self.local_store.save(pos_ms) # Cheap local writeif now() - self.last_remote >= self.REMOTE_FLUSH_INTERVAL:self.flush_remote(pos_ms)def on_event(self, event: str, pos_ms: int):self.local_store.save(pos_ms)if event in self.FORCE_FLUSH_EVENTS:self.flush_remote(pos_ms) # Force report on key eventsdef flush_remote(self, pos_ms: int):payload = {"user_id": session.user_id,"video_id": self.video_id,"position_ms": pos_ms,"device_id": session.device_id,"client_ts": now(), # Client timestamp for conflict resolution"event_id": uuid4(), # Idempotency key}retry_with_backoff(lambda: api.report_progress(payload))
Three details that must not be dropped. First, event_id acts as an idempotency key, preventing network retries from causing duplicate writes and skewed statistics. Second, the report carries the device ID and client timestamp, so that “watching the same video on multiple devices at once” can be resolved by last-active time. Third, the progress service should be an independent, high-throughput write service that persists asynchronously through a message queue and never blocks the main playback path.
3.3 Idempotency and out-of-order handling
Every write interface should be designed to be idempotent. Take favorites: the server should model “favorite” as an insert into a relationship table and rely on a unique index for deduplication, rather than maintaining a counter that is incremented and decremented:
-- Favorite relationship table: the unique index handles idempotencyCREATE TABLE user_favorite (user_id BIGINT NOT NULL,target_id BIGINT NOT NULL,target_type TINYINT NOT NULL, -- 1: video, 2: channel, 3: usercreated_at TIMESTAMP NOT NULL,UNIQUE KEY uk_user_target (user_id, target_id, target_type));
Un-favoriting is simply deleting the corresponding row. This way, even if the client submits twice or requests arrive out of order (un-favorite arrives first, favorite later), the final state strictly reflects the last operation—provided the server compares by client_ts before deciding whether to apply a change.
3.4 Incremental pull and cursor pagination
On startup, the client should not pull the full history. The right approach is a cursor-based incremental interface:
GET /api/v1/sync/changes?cursor={last_version}&limit=200Response:{"changes": [ { "type": "favorite.add", "target_id": 10086, "version": 8842 } ],"next_cursor": 9041,"has_more": true,"server_ts": 1730000000}
Compared with traditional page-number offsets, a cursor has two advantages: under continuous writes it neither skips nor duplicates reads, and query cost is independent of offset depth. The client persists next_cursor locally and sends it on the next launch, achieving “pull only the changes.”
4. Real-time interaction: carrying comments and danmaku at high concurrency
4.1 What makes danmaku special
Danmaku (scrolling bullet comments) have a very different technical profile from ordinary comments: comments are a persistent tree structure that can be searched and paginated, whereas danmaku are one-off streaming data bound to the playback timeline. A danmaku’s useful lifetime is usually only tens of seconds—after that point it no longer matters to the current viewer, yet it may still have value for someone who watches the same video later.
Danmaku therefore suit tiered storage: hot data (recent danmaku) lives in an in-memory cache for real-time fetching, while the full dataset is written asynchronously to persistent storage for later playback loading. On the loading side, there is no need to fetch everything at once; instead, shard by the timeline and pull neighboring ranges on demand.
4.2 Delivering and sampling danmaku
When tens of thousands of danmaku cluster around the same timestamp of a popular piece of content, delivering all of them is both unnecessary and enough to bog down rendering. The industry-standard approach is server-side downsampling + client-side density control:
- The server keeps counts per (video, time slice) and, above a threshold, samples randomly by weight.
- High-upvote danmaku are preferentially retained (weighted), except those matching a user’s custom blocklist, to preserve quality.
- The client applies a second layer of density control based on screen width and scroll speed, avoiding unreadable overlaps.
4.3 Content safety and write peak-shaving
All user-generated content (danmaku, comments, activity) must pass through an asynchronous moderation pipeline. Synchronous blocking moderation directly raises interface latency, while “publish first, review later” carries compliance risk. The compromise is a tiered policy: for low-risk users and low-risk content, show first and review asynchronously afterward; for high-risk cases, review before showing; and for content that hits the sensitive-word library, block it immediately and downgrade it to “visible only to the author.”
On the write side, everything should be peak-shaved through a message queue. The danmaku surge at the moment a popular piece goes live can reach dozens of times its normal volume, so moderation, counting, persistence, and recommendation-feature updates should all run asynchronously on consumers. The write interface itself only does parameter validation and enqueueing, which keeps response times stable.
5. Content delivery and personalized feeds
5.1 The home “activity” feed and subscription relationships
The “activity” feed is essentially the propagation of subscription relationships: a user follows a creator, and when the creator publishes new content, it needs to be pushed into every follower’s feed. This is a classic trade-off:
- Push model (write fan-out): on publish, write the content into each follower’s inbox. Reads are extremely fast, but one post from a large account produces massive write amplification.
- Pull model (read fan-out): at read time, aggregate the recent content of followed accounts in real time. Writes are cheap, but read cost grows with the number of accounts followed.
Large-scale platforms typically use a hybrid model: ordinary creators use the pull model; accounts whose follower count exceeds a threshold use the push model and push only to active followers; inactive users catch up via the pull model on their next visit. When the follower count falls in the middle range, the mode can switch dynamically based on activity.
5.2 The read path for rankings and feeds
Ranking-style features (trending, leaderboards) should avoid real-time aggregate computation. A workable approach is to compute ranking snapshots offline or near-real-time, refresh them at minute- or hour-level granularity, cache them in memory, and have the read interface serve the snapshot directly. This decouples the read performance of the ranking from the underlying data volume.
For category channel pages (such as sports or live-event channels with an explicit time attribute), the sort order should follow a clear rule: in-progress content first, upcoming content next, and finished content ordered by popularity. These business rules should be fixed on the server, avoiding inconsistent ordering across clients that would show different sequences to different users.
6. Adaptive bitrate and content delivery
Behind “free high-definition video” lies multi-bitrate transcoding and adaptive bitrate streaming: after content is ingested, a transcoding cluster generates multiple resolution tiers and multiple bitrate slices, and the client switches among them dynamically during playback based on real-time bandwidth and buffer level. Three things matter architecturally:
- Origin-fetch control: when an edge node misses, it fetches from origin; hot content needs active pre-warming to prevent a burst of traffic from converging on the origin and overwhelming it.
- Authorization and anti-leeching: slice URLs for high-definition or paid content should use time-limited signed URLs, signed by the server and validated at the edge node, to prevent the URLs from being shared and abused directly.
- Observability: startup latency, stall ratio, first-frame time, and switch count are the core quality metrics. They should be reported by client-side instrumentation and flow into a unified monitoring and alerting system, with drill-downs across content, region, and terminal type.
7. Implementation and engineering safeguards
7.1 Layering and boundaries
A suggested service layering: the access layer handles TLS termination, rate limiting, and pre-authentication; the business layer is split by domain into a user domain, a content domain, an interaction domain, and a sync domain; the data layer is chosen by access pattern—a strongly consistent relational store holds accounts and orders, an in-memory cache holds sessions and hot snapshots, object storage holds media slices, a logging service holds audit and behavioral telemetry, and a message queue handles asynchronous decoupling and peak-shaving.
7.2 Consistency and availability trade-offs
Cross-device sync does not need to pursue global strong consistency. A reasonable goal is consistency within a single user’s session and eventual consistency across devices, keeping sync delay at the seconds level. In implementation, you can use a “write the primary, then asynchronously replicate to read replicas” pattern, and on the client distinguish “synced” from “syncing” states so users do not repeat operations because of a brief inconsistency.
7.3 Canary rollout and disaster recovery
Core paths like login and sync should support percentage-based canary rollout and fast rollback for any change. Changes to token-issuance logic and sync-merge rules that affect data compatibility must ensure that the new code version can read old-version data and support a dual-write transition period. Identity services should also have a degradation design: when non-core services such as recommendation and danmaku are unavailable, login and playback should remain unaffected.
7.4 Deployment and operations
Use containerized deployment with elastic scaling to handle traffic peaks and troughs. Baidu AI Cloud’s container platform, object storage, logging, and monitoring and alerting capabilities can serve as the standard building blocks for an operations system. Configuration and secrets should be distributed through a configuration center and a key-management service, and must never be hard-coded in code or images. Every interface should carry a unified trace identifier for cross-service problem diagnosis.
8. Conclusion
Back to that original page: login answers “who am I,” favorites and activity answer “what have I watched and what do I care about,” and membership and messages answer “what can I get.” The technical cores of these three questions are, respectively, revocable, rotatable identity credentials, incremental state sync centered on idempotency and versioning, and tiered content delivery with business rules fixed in place.
The key trade-off in architecture design is not which specific technology to choose, but accurately judging which data must be strongly consistent, which can be eventually consistent, which writes must be peak-shaved, and which reads must be cached. Draw those boundaries clearly, and the remaining technology choices usually become straightforward engineering decisions.
