Engineering Multi-Device Login and Playback Progress Sync

    This article explains how to keep login sessions and playback progress consistent when one account is used on phones, tablets, computers, and TVs. It covers session and token design, how to classify state by consistency needs, token renewal and revocation flows, conflict resolution for playback progress, offline queuing and retries, real-time notifications, security safeguards, and common troubleshooting steps.

    1. Background

    The same account is often used on phones, tablets, computers, and TVs at the same time. Users expect a consistent login state, watch progress, favorites, and message notifications on every device. To meet this expectation, the server side must solve three problems at once:

    1. How to issue, renew, and revoke identity credentials securely across multiple devices.
    2. How to synchronize state such as playback progress and favorites in a timely way while keeping a reasonable level of consistency.
    3. How to keep data from being lost, duplicated, or overwritten when the network is unstable.

    These problems are closely linked. The credential design affects how sync APIs authenticate requests, and the sync strategy affects the client’s caching and retry logic. The sections below break them down in that order.

    2. Core Concepts

    2.1 Sessions, Tokens, and Devices

    Multi-device login rests on a session model. A common approach splits each login into three parts:

    • Access token: short-lived, typically from a few minutes to a few hours. It authenticates API requests.
    • Refresh token: long-lived. It is used only to obtain new access tokens. The server stores a record of each refresh token so it can be revoked when needed.
    • Device ID: generated and persisted when a device first logs in. The server records sessions per account and device ID, including device type, login time, last active time, and login source.

    Access tokens should be stateless where possible so that gateways can validate them quickly. Refresh tokens must be stateful. Without server-side records, operations such as “sign out a specific device” cannot be implemented.

    2.2 State Classification

    Not all state needs the same consistency guarantees. Based on business impact, state falls into two categories:

    Category Typical data Consistency requirement Handling approach
    Strongly consistent state Login state, account permissions, membership validity Changes should take effect on all devices as soon as possible The server is the source of truth. Clients validate on every request, and the server pushes a notification when a change occurs.
    Eventually consistent state Playback progress, favorites order, browsing history Short-term differences are acceptable The client writes locally first, then reports asynchronously. The server merges the reports.

    Mixing both categories in one mechanism often leads to high latency for strongly consistent state or excessive write pressure for weakly consistent state. Separating them lets each category use tools and retry policies that fit it.

    3. Login State Management

    3.1 Token Renewal Flow

    When an access token expires, the client should obtain a new one silently instead of asking the user to enter the password again. A typical flow works as follows:

    1. The client sends a business request with the access token.
    2. The server returns 401, meaning the token is invalid or expired.
    3. The client requests a new access token with the refresh token.
    4. The server checks whether the session record for the refresh token is still valid. If it is, the server issues a new access token and rotates the refresh token. If not, the server returns a failure.
    5. The client retries the original request with the new access token. If the refresh fails, the client clears local credentials and guides the user to log in again.

    Pseudocode (language-agnostic):

    1. function requestWithAuth(apiCall):
    2. token = secureStore.getAccessToken()
    3. response = send(apiCall, token)
    4. if response.status != 401:
    5. return response
    6. // Concurrency control: allow only one refresh request in flight at a time
    7. acquireRefreshLock()
    8. newToken = refreshAccessToken(secureStore.getRefreshToken())
    9. releaseRefreshLock()
    10. if newToken is null:
    11. secureStore.clear()
    12. redirectToLogin()
    13. return failure
    14. secureStore.saveAccessToken(newToken.access)
    15. secureStore.saveRefreshToken(newToken.refresh)
    16. return send(apiCall, newToken.access)

    Two details are easy to miss. First, if several requests receive 401 at the same time and each starts a refresh, the refresh token may be consumed more than once. The server may then mistake this for token theft. Locking or queuing refresh requests prevents this. Second, refresh tokens should be rotated on every use, and the old token should become invalid immediately.

    3.2 Session Revocation

    When a user signs out on one device or removes a device on the account security page, the server must complete three steps:

    • Mark the corresponding session record as revoked.
    • Invalidate the refresh token linked to that session.
    • Notify other online devices so they sign out as soon as possible.

    Online devices can receive this notification over a persistent connection. Offline devices receive a 401 on their next request and handle it through the flow described in the previous section. Even if a notification is lost, the system still reaches the correct state.

    3.3 Device Session List

    To help users manage their devices, the server should provide a device list. Each entry should include at least the device type, last active time, and approximate login location. For location, only coarse information, such as city level, should be shown. Precise coordinates should not be recorded, which reduces privacy risk.

    4. Playback Progress Sync

    4.1 Client Write Strategy

    Playback progress is high-frequency write data. If every device reported progress every second, server load would be heavy, and weak networks would produce many failed requests. A common approach is:

    • Record the playback position locally in real time so the interface can resume instantly.
    • Report progress at a fixed interval, for example every 15 seconds.
    • Report immediately at key points, such as pausing, switching content, or exiting the app.

    Each report should contain enough information for the server to determine the order of records:

    1. {
    2. "user_id": "u_10086",
    3. "content_id": "ep_2048",
    4. "device_id": "tv_01",
    5. "position_ms": 734500,
    6. "local_seq": 17,
    7. "client_time": "2026-11-24T07:41:47Z"
    8. }

    local_seq is an incrementing sequence number that the client maintains for each device. It is more reliable than a timestamp because device clocks can drift.

    4.2 Conflict Resolution Rules

    When two devices produce different progress for the same content, the server must decide which record to keep. Three common rules apply:

    Rule Approach Advantages Disadvantages
    Last write wins Keep the most recent record by server receive time Simple to implement A delayed request from an old device can overwrite newer progress
    Merge by device sequence Each device accepts only higher sequence numbers Rejects out-of-order replays Cross-device conflicts still need extra logic
    Keep the larger progress Keep the larger playback position for the same content Users never appear to move backward Progress cannot be updated when a user intentionally rewinds

    In practice, a safer approach combines these rules. Within a single device, the server deduplicates by sequence number. Across devices, when records conflict, the server keeps the record with the newer receive time. It also writes each conflict event to the log for later investigation.

    Pseudocode:

    1. function mergeProgress(stored, incoming):
    2. if stored is null:
    3. return incoming
    4. // Discard stale requests from the same device
    5. if incoming.device_id == stored.device_id
    6. and incoming.local_seq <= stored.local_seq:
    7. return stored
    8. // Across devices: use the server receive time
    9. if incoming.received_at >= stored.received_at:
    10. return incoming
    11. return stored

    4.3 Reading and Display

    When a user opens content, the client should read the local progress first, then fetch the server progress asynchronously. If the two values differ, the app can ask whether to resume from the position on another device instead of overwriting silently. This prevents users from losing their most recent viewing position because of a background merge.

    5. Weak Network and Offline Handling

    5.1 Local Queue

    All progress reports go into a persistent local queue first. A background task then sends them. The queue must meet the following requirements:

    • Its contents survive when the app is force-closed.
    • It has a maximum length. When the limit is reached, the queue merges old records for the same content and keeps only the latest one.
    • Each record carries a unique identifier so the server can process it idempotently.

    5.2 Retry and Backoff

    Failed requests should use exponential backoff with random jitter. Fixed-interval retries cause many devices to reconnect at the same moment, which creates request spikes. Random jitter spreads these requests out.

    1. function retryDelay(attempt):
    2. base = 2 ^ attempt seconds
    3. capped = min(base, 300)
    4. return random(0, capped) // full jitter

    The retry count should have an upper limit. Records that exceed the limit can stay in local storage and be retried on the next app launch or when the network recovers. This avoids endless retries that drain battery and consume data.

    6. Real-Time Notification Design

    Events such as favorite updates, message reminders, and session revocation need to arrive quickly. The delivery channel depends on event frequency and reliability requirements:

    • Persistent connection push: low latency, suited to high-frequency events or events that need immediate feedback. After a disconnection, the client must actively pull the missed events.
    • Polling: simple to implement and suited to low-frequency events. Short intervals increase server load, and long intervals degrade the experience.
    • Event version numbers: each notification carries an incrementing version number. When the client detects a gap in versions, it requests the missing events in that range.

    With any of these approaches, notifications should be safe to receive more than once without side effects. The client deduplicates notifications by event ID to meet this requirement.

    7. Security Essentials

    Multi-device sync expands the attack surface, so the following areas need stronger protection:

    • Least privilege: an access token should carry only the permissions needed for the current request. A single token should not grant every capability.
    • Secure storage: tokens should be stored in the secure storage the operating system provides, not in plain configuration files or logs.
    • Rate limiting: limit login and refresh endpoints by account and source address to prevent credential guessing.
    • Anomaly detection: if a refresh token is reused, revoke all tokens in that session chain immediately and require the user to verify their identity again.
    • Log redaction: remove tokens, phone numbers, and precise location fields from request logs.

    8. Troubleshooting Common Issues

    Symptom Likely cause Where to look
    Users are signed out frequently Refresh token rotation logic is faulty, or concurrent refreshes are not locked Check the call count on the refresh endpoint, and confirm whether the same refresh token is used more than once
    Progress jumps back to an earlier position A delayed request from an old device overwrote a newer record Review the sequence comparison logic, and confirm that ordering uses server receive time rather than client time
    Progress stays out of sync for a long time The local queue is backing up, and the background task is not running Check queue length, retry counts, and the conditions that allow the background task to run
    The same notification appears more than once The client lacks event deduplication Confirm that event IDs are unique, and review the expiration policy of the deduplication cache
    A revoked device still has access The access token is still within its validity period Shorten the access token lifetime, or add session state checks at the gateway layer

    9. Pre-Launch Checklist

    • Access token and refresh token lifetimes are configured to meet security requirements, and token rotation has been tested.
    • Concurrent refresh scenarios have passed load testing, with no false positives for token theft.
    • Progress reporting intervals, key-point triggers, and merge rules have corresponding unit tests.
    • Weak network, offline, and force-closed app scenarios have passed regression testing.
    • After a session is revoked, both online and offline devices sign out within the expected time.
    • Logs contain no tokens, phone numbers, or precise location data.