Multi-Device Playback Synchronization and Real-Time Interaction: System Design Practices
This article presents a practical system design for multi-device playback synchronization and real-time interaction in content consumption products. It covers requirement classification, service layering, playback record modeling and conflict handling, segmented danmaku storage, session and entitlement validation, unread counts, activity feeds, favorite idempotency, reliability, observability, testing, and canary rollout.
1. Requirements Breakdown and Problem Definition
Content consumption products usually include a set of related capabilities: account login and registration, multi-device playback record synchronization, danmaku and comments, membership entitlements, message notifications, activity feeds, and favorites. These features may look independent from a user experience perspective, but technically they share the same identity system and data infrastructure.
Before design, three classes of questions need to be clarified:
- Consistency requirements: Playback progress may tolerate brief inconsistency, but data such as favorites and membership entitlements must not be wrong.
- Real-time requirements: Danmaku needs millisecond-to-second push latency, while favorites and messages can tolerate second-level or minute-level latency.
- Scale characteristics: Danmaku has an extremely high read/write ratio, playback progress is written frequently but each record is small, and favorites are written less often.
Designing layers around these three requirements avoids using one storage system and one synchronization strategy for all data, which reduces overall system complexity.
2. Overall Architecture
The following layered structure is recommended:
- Access layer: A unified gateway handles authentication, rate limiting, and routing, and dispatches client requests to the corresponding services.
- Identity and session service: Handles login, registration, token issuance and refresh, and device session management.
- Playback progress service: Receives playback heartbeats and key events, writes progress to storage, and provides resume-playback queries.
- Interaction service: Handles sending, review, segmented storage, and retrieval of danmaku and comments.
- Entitlement service: Maintains membership status and entitlement configuration, and provides validation interfaces to other services.
- Message and feed service: Handles in-site message delivery, unread counts, and generation and reading of activity feeds.
- Favorite service: Manages user favorite collections and ensures add and remove operations are idempotent.
- Infrastructure layer: Includes relational databases, key-value caches, message queues, object storage, logging, and monitoring systems.
Services communicate through explicit interfaces and avoid directly accessing each other’s databases.
3. Multi-Device Playback Record Synchronization
3.1 Data Model
The core fields of a playback record are as follows:
PlaybackRecord {user_id : user identifiercontent_id : content identifierepisode_id : episode identifier (can be empty for single-episode content)position_ms : playback position in millisecondsduration_ms : total content duration, used to calculate completiondevice_id : device identifier that produced this recordversion : monotonically increasing version numberupdated_at : server-side write timestamp}
The recommended primary key is (user_id, content_id, episode_id), and each user keeps only one latest record per episode. If historical traces need to be retained, they should be placed in a separate log table so that they do not affect read efficiency of the main table.
3.2 Reporting Strategy
Frequent reporting increases server load, while insufficient reporting causes other devices to read stale progress. A common approach combines three trigger types:
- Periodic heartbeat: Report once at a fixed interval during playback. The interval can be 10 to 30 seconds, with the exact value adjusted based on actual load.
- Event trigger: Report immediately on pause, seek, episode switch, or page exit.
- Throttling and merging: Keep only the last event from the same device within a short period to reduce write volume.
When the network is unavailable, the client should temporarily store progress in a local queue and replay it in chronological order after the network recovers.
3.3 Conflict Handling
The same account may play on multiple devices at the same time, so the server needs to decide which record takes precedence. Two common methods are:
- Optimistic update based on version number: The client submits the version number read last time, and the server writes only when the version matches. Otherwise, it returns the latest record and lets the client decide.
- Last-write-wins: Use the server receive time as the basis, and a newer record overwrites an older one.
For playback progress, last-write-wins is usually sufficient because users care about “where I last watched.” During implementation, note that the client clock is unreliable, so ordering must be based on server timestamps.
Example server write logic:
def upsert_progress(store, record):current = store.get(record.user_id, record.content_id, record.episode_id)if current is None or record.updated_at >= current.updated_at:record.version = (current.version + 1) if current else 1store.put(record)return record# Discard older reports and return the current record for client correctionreturn current
3.4 Resume Playback
When a user opens content, the client requests the latest progress for that content. The server should return both the progress position and the source device that updated it, so the client can prompt “continue from another device.” To reduce first-screen wait time, progress data can be cached in a key-value store and fall back to the database on cache miss.
4. Real-Time Interaction for Danmaku and Comments
4.1 Differences Between the Two Data Types
Danmaku and ordinary comments look similar, but their technical characteristics differ significantly:
| Dimension | Danmaku | Comments |
|---|---|---|
| Time association | Bound to a specific playback timestamp in the video | Bound to the content itself and sorted by time |
| Read/write pattern | Many reads at the same timestamp, short and concentrated writes | More reads and relatively dispersed writes |
| Presentation | Real-time scrolling push | Paginated loading |
Therefore, danmaku needs to be organized and stored by time segment, while comments are better suited to a list structure sorted by topic and time.
4.2 Time-Segmented Storage
Split the content duration into fixed-length time segments, for example one segment every 60 seconds. Danmaku is written to the corresponding segment based on its timestamp, and the client can pull adjacent segments based on the current playback position without loading all danmaku at once.
def segment_index(position_ms, segment_ms=60_000):return position_ms // segment_msdef fetch_danmaku(store, content_id, position_ms, window=1):idx = segment_index(position_ms)result = []for i in range(idx - window, idx + window + 1):if i >= 0:result.extend(store.list_by_segment(content_id, i))return sorted(result, key=lambda d: d.position_ms)
Prefetching adjacent segments can reduce blank waits when users seek through the progress bar.
4.3 Send Path
A danmaku message usually goes through the following steps from sending to display:
- Access validation: Check login status, send frequency, and content length.
- Content filtering: Use keywords and rules for synchronous filtering to block obviously violating content.
- Asynchronous review: Send suspicious content to a review queue, write back the review result, and then decide whether to deliver it.
- Persistence: Write to segmented storage and record the sender, timestamp, and review status.
- Push: Broadcast to online viewers of the same content through a long-lived connection.
Synchronous filtering ensures response speed, while asynchronous review ensures coverage. Combining the two is a common practice.
4.4 Push Channel
When there are many online viewers, polling generates a large number of invalid requests. A long-lived connection is a more suitable choice. The server can divide rooms by content identifier, maintain a set of connections for each room, and broadcast danmaku only to the corresponding room when it arrives. After a connection is disconnected, the client resubscribes with the last received message sequence number and fills in the missing part.
5. Accounts, Sessions, and Membership Entitlements
5.1 Login and Tokens
A short-lived access token combined with a long-lived refresh token is recommended. The access token is used for daily API authentication and has a short validity period, reducing risk after leakage. The refresh token is stored on the server and supports active revocation.
5.2 Multi-Device Session Management
Each login generates a session record containing the device identifier, login time, and last active time. Users can view all online devices in settings and can log out an individual device. The logout operation should also invalidate the refresh token for that session.
5.3 Membership Entitlement Validation
The core requirements for entitlement validation are accuracy and speed. It is recommended to cache entitlement status in the gateway or local service, with an expiration time recorded in the cache. When entitlements change, notify each service through a message queue to refresh the cache. If the entitlement service is temporarily unavailable, a conservative strategy should be adopted: deny access to high-value entitlements, allow degraded access for ordinary functions, and record degradation events in logs.
6. Messages, Feeds, and Favorites
6.1 Unread Counts
Unread counts are a read-heavy and write-heavy scenario. A common approach is to store the count in a key-value store, increment it when a new message arrives, and clear it when the user reads. To avoid inconsistency between the count and actual messages, the count can be periodically corrected using the real number of records in the message table.
6.2 Activity Feeds
There are two ways to generate activity feeds:
- Write fan-out: When a user publishes an activity, actively write it to all followers’ inboxes. Reads are fast, but write overhead is high when there are many followers.
- Read fan-out: When a user reads, merge the latest activities from followed objects in real time. Writes are simple, but read-time computation is heavy.
In practice, systems often use write fan-out for ordinary users and read fan-out for accounts with a large number of followers, combining the two approaches.
6.3 Idempotency of Favorite Operations
Favorite and unfavorite operations may be executed multiple times due to network retries. Designing operations to be idempotent avoids duplicate data. For example, the favorite table uses (user_id, content_id) as a unique key and uses “ignore if exists” semantics on insert; unfavoriting directly deletes the corresponding record, and repeated execution produces no side effects.
7. Reliability and Observability
7.1 Rate Limiting and Degradation
- Set user-level and device-level rate limits for high-frequency endpoints such as danmaku sending and progress reporting.
- When the interaction service is overloaded, temporarily disable real-time danmaku push and retain only historical danmaku retrieval, ensuring that playback itself works normally.
- When progress reporting fails, the client saves it locally without affecting playback.
7.2 Key Metrics
At minimum, monitor the following metrics:
- Progress reporting success rate and average latency
- End-to-end latency from danmaku sending to push
- Login API error rate and token refresh failure rate
- Message queue backlog length
- Cache hit rate
Alert thresholds should be set based on historical baselines rather than fixed values.
7.3 Logs and Privacy
Logs must not record sensitive information such as tokens or passwords. User behavior data should be desensitized before being used for analysis, and the principle of data minimization should be followed by retaining only business-required fields and necessary retention periods.
8. Testing and Launch
8.1 Test Focus
- Concurrency testing: Simulate the same account reporting progress from multiple devices at the same time and verify that the final state is correct.
- Weak network testing: Verify the replay order and deduplication results of the offline queue.
- Danmaku load testing: Simulate instantaneous danmaku peaks on popular content and observe segment hotspots and push latency.
- Compatibility testing: Verify that older client versions can still correctly parse data returned by new APIs.
8.2 Canary Release
Release the new version to a small percentage of users first, observe key metrics, and gradually expand the scope after confirming there are no anomalies. When data format changes are involved, first make the server compatible with both old and new formats, then upgrade the client, and finally clean up the old logic.
