Real-Time and Streaming System Design Questions
Designing client-facing, always-on live delivery systems: real-time communication transports (WebSockets, server-sent events, long-polling, WebRTC, MQTT), connection lifecycle and scaling for millions of persistent connections, presence, pub/sub fan-out to online users, chat and notifications, live feeds and tickers, real-time collaboration (CRDT vs OT, offline sync and reconciliation), and live and on-demand video delivery (ingest, transcoding, adaptive bitrate, CDN delivery, low-latency protocols, playback entitlement and content protection). Covers latency budgets, per-client ordering, delivery guarantees across disconnect and reconnect, per-client backpressure, capacity estimation for connection fleets, authentication, authorization, and revocation for real-time channels and premium content, and operational readiness (SLOs and error budgets, observability and incident response, rate limiting, safe rollout, and load and chaos testing) for live-delivery platforms. Data-pipeline stream processing (Kafka or Flink jobs, windowed aggregation, exactly-once pipelines, real-time analytics ingestion) is out of scope.
Design the notification strategy for offering drivers new ride requests in a large-scale dispatch platform. Compare push (server-initiated) and pull (driver-initiated polling) delivery, weighing latency, battery and network cost, and scalability, and address the risk that a push-heavy strategy can systematically over-expose offers to the same subset of drivers. Propose a hybrid delivery approach and explain when each mode should be used.
Sample Answer
Direct answer
Offers should be pushed to drivers who are online, available and have a healthy connection, because a ride offer is time-critical and polling fast enough to match push wastes battery and server capacity. Pull stays as a safety net: the app asks "anything for me?" when it comes to the foreground, after a reconnect, and on a slow timer only while its push channel looks unhealthy. The fairness risk is real but it comes from who the dispatcher chooses to push to, not from push itself: if the offer always goes to the top-ranked few drivers, the same drivers are pinged again and again while others nearby wait. So the hybrid needs an exposure policy (who is eligible for the next offer) alongside the transport policy (how the offer travels).
Terms used below
- Push (server-initiated): the server sends the offer down an open connection (a WebSocket or similar long-lived link) or via the phone's platform push service (APNs, Apple Push Notification service, on iOS; FCM, Firebase Cloud Messaging, on Android), which can wake a backgrounded app.
- Pull (polling): the app asks the server at intervals. Long polling is a variant where the server holds the request open until something arrives or a timeout passes.
- Offer: a time-limited proposal ("pickup 4 min away, accept within 15 s"). An offer is useless once it expires.
- Over-exposure: some drivers receiving a disproportionate share of offers, which also means they decline more (fatigue) and other drivers see too few.
Push vs pull on the three named axes
| Push (persistent connection) | Pull (polling every T seconds) | |
|---|---|---|
| Latency | Network time only, typically well under a second on a healthy link | Average extra wait of T/2 (a 5 s poll adds 2.5 s on average, up to 5 s), a big slice of a 15 s accept window |
| Battery and network | Idle socket plus a small heartbeat; the radio wakes only when there is traffic. OS push services batch wake-ups across apps | Every poll wakes the cellular radio, which then stays in a high-power state for a while after each request; frequent polling keeps it there, and almost every response is empty |
| Scalability | Cost is in holding connections (memory per socket, connection registry, reconnect storms after a deploy) | Cost is in request rate: 500,000 online drivers polling every 5 s is 500,000 / 5 = 100,000 requests per second, nearly all returning "nothing" |
| Failure behaviour | A half-dead connection can look alive; offers silently vanish unless acknowledged | Naturally self-healing: the next poll works even after a network change |
That last row is why pure push is not enough: mobile connections die silently in tunnels, on network handoffs and when the OS suspends the app.
The hybrid design
flowchart TB
D[Dispatcher: ranks candidates] --> X[Exposure policy: fairness band, caps, cooldowns]
X --> S{Driver connection healthy?}
S -->|yes| WS[Push offer on live socket]
S -->|app backgrounded| OS[Platform push to wake app]
WS --> ACK{Delivery ack within 2 s?}
ACK -->|no| OS
OS --> P[App wakes and pulls pending offers]
When each mode is used:
- Push over the live connection: the default for drivers who are online, available and whose last heartbeat is fresh. Every offer carries an ID and an expiry; the app sends a delivery ack (a short "received" message) immediately, separate from accept/decline.
- Platform push (APNs/FCM): when the app is backgrounded or the socket is down. It is best-effort and can be delayed, so it carries only "you have an offer, open the app", not the offer itself.
- Pull: on app foreground, immediately after any reconnect, and as a fallback timer (for example every 10 s) that runs only while the socket is unhealthy. The pull endpoint returns any unexpired offers held for this driver, so a push that was lost is recovered within one pull.
- Server-side reconciliation: if no delivery ack arrives within 2 s, the dispatcher sends a platform push, and if the offer is still unacknowledged when half its window has passed, it withdraws the offer and moves on, so a rider is not kept waiting on a driver who never saw it.
Idempotency: accepts carry the offer ID, and the server accepts the first valid accept for a ride and rejects the rest, so a driver who receives the same offer by push and by pull cannot be double-booked.
The over-exposure problem, and the fix
A push-heavy dispatcher usually ranks drivers by pickup time and sends to the best one, or broadcasts to the best few. Drivers parked near a hotspot, or with consistently good connections (who ack fastest and so rank well on responsiveness), win almost every ranking. They get offers they decline, while drivers slightly further away sit idle. It also skews the data: the system learns from the few who are over-offered.
Mitigations, in the order I would add them:
- Fairness band: treat all drivers whose pickup time is within a small margin of the best (say 60 s) as equivalent, and choose among them by fewest recent offers, not by rank.
- Exposure caps and cooldowns: at most K offers per driver per rolling window; a driver who just declined gets a short cooldown before the next offer.
- Sequential rather than broadcast offers: one driver at a time with a short window, instead of pinging the top three at once, which triples exposure per ride.
- Monitor exposure distribution: share of offers going to the top 10% of drivers, offers per driver-hour, decline rate by exposure level.
A small simulation of the effect
This simulation isolates the ranking effect: 200 drivers fixed in a 10 km by 10 km city, 2,000 ride requests clustered around a hotspot, no acceptance modelled. These drivers are static points with no modelled speed, so the simulation approximates the fairness band by pickup distance instead of pickup time; a real system would calibrate the seconds-to-kilometres conversion from live ETAs, and here 1 km stands in for the 60 s margin described above, the same fairness-band idea in the units the simulation can compute directly. It compares broadcasting to the three nearest drivers against the exposure-cap mitigation in concrete form: one offer per request chosen from a 1 km fairness band, with the "K offers per driver per rolling window" cap set to K=5 over a window of the last 100 requests.
import random, math
def simulate(policy, seed=7, n_drivers=200, n_requests=2000, cap=None):
rng = random.Random(seed)
# drivers scattered over a 10 km x 10 km city; riders cluster near a hotspot at (2, 2)
drivers = [(rng.uniform(0, 10), rng.uniform(0, 10)) for _ in range(n_drivers)]
offers = [0] * n_drivers
recent = [] # driver ids offered in the last 100 requests
for _ in range(n_requests):
rx, ry = rng.gauss(2, 1), rng.gauss(2, 1)
ranked = sorted(range(n_drivers),
key=lambda d: math.hypot(drivers[d][0] - rx, drivers[d][1] - ry))
if policy == "push_top3":
chosen = ranked[:3] # broadcast to the 3 closest drivers
else:
best = math.hypot(drivers[ranked[0]][0] - rx, drivers[ranked[0]][1] - ry)
# eligible: within 1 km of the best pickup distance and under the exposure cap
band = [d for d in ranked[:15]
if math.hypot(drivers[d][0] - rx, drivers[d][1] - ry) <= best + 1.0
and recent.count(d) < cap]
band = band or ranked[:1]
chosen = [min(band, key=lambda d: (offers[d], rng.random()))]
for d in chosen:
offers[d] += 1
recent.extend(chosen)
recent = recent[-100:]
total = sum(offers)
top = sorted(offers, reverse=True)
share10 = sum(top[:n_drivers // 10]) / total
return total, share10, top[0], sum(1 for o in offers if o > 0)
for name, kw in [("push to 3 nearest", dict(policy="push_top3")),
("1 offer, fairness band + cap 5 per 100 requests", dict(policy="band", cap=5))]:
total, share10, mx, reached = simulate(**kw)
print(f"{name}: offers={total} top-10%-share={share10:.0%} max-per-driver={mx} drivers-offered={reached}/200")
Output:
push to 3 nearest: offers=6000 top-10%-share=67% max-per-driver=309 drivers-offered=69/200
1 offer, fairness band + cap 5 per 100 requests: offers=2000 top-10%-share=38% max-per-driver=39 drivers-offered=81/200
Reading it: broadcasting to the three nearest sends 6,000 offers for 2,000 rides, gives two thirds of them to the top 20 drivers, and one driver is pinged 309 times. The banded, capped policy sends only 2,000 offers, a third as many, yet the top 10% share falls to 38%, the maximum per driver falls to 39, and more drivers get at least one offer (81 versus 69). That last comparison, 81 versus 69, is not like-for-like on its own, since the banded policy had a third as many total offers to spread around; normalised per offer sent, it reaches a distinct driver about 3.5 times as often as broadcasting does (81/2,000 versus 69/6,000), which is the real size of the fairness gain, not just the raw head count. The model is deliberately simple (drivers do not move, nobody accepts), so the numbers show the direction and size of the ranking effect, not a production forecast; in a real system I would measure the same three statistics from offer logs.
Trade-offs and pitfalls
- A wider fairness band improves equity but costs pickup time: 60 s of extra pickup across millions of rides is real rider cost. Tune the band against rider wait, not in isolation.
- Polling "just to be safe" at a fast rate on every driver erases push's battery and server savings; poll only when the socket is unhealthy.
- Platform push is not a delivery guarantee and may be throttled or delayed by the OS; never put the only copy of a time-critical offer there.
- Counting an offer as "sent" when it was pushed, rather than when the app acknowledged it, hides delivery failures and makes exposure metrics wrong.
What would change the design: very low driver density (few candidates, so fairness bands are nearly empty and nearest-first is fine), or markets with poor connectivity where the pull fallback timer should be shorter and offer windows longer.
You are evaluating protocol choices for low-latency mobile notifications where devices are battery constrained. Compare WebSockets, MQTT, and HTTP/2 server push in terms of connection overhead, required keepalive frequency, and battery impact. Recommend a protocol and explain reasons and caveats (e.g., proxies, push services like APNs/FCM).
Sample Answer
Direct answer
For notifications to a battery-constrained phone I would not keep my own always-on socket at all when the app is in the background: I would deliver through the operating system's push service, APNs on iOS and FCM on Android, because the phone already keeps exactly one connection open to it for every app, and on iOS it is the only reliable way to reach a suspended app. While the app is in the foreground, I would use MQTT over TLS for the live channel (or WebSockets if the product is already web-stack and the message volume is modest). HTTP/2 server push is not an option: it was built to preload page resources, not to deliver application events, and Chrome disabled it by default in version 106.
The candidates in plain terms
- WebSocket: one long-lived TCP connection upgraded from HTTP; either side can send framed messages at any time.
- MQTT (Message Queuing Telemetry Transport): a lightweight publish/subscribe protocol designed for constrained devices and flaky networks. Clients connect to a broker, subscribe to topics, and the broker forwards messages. It has built-in delivery levels called QoS, quality of service (QoS 0: at most once, QoS 1: at least once, QoS 2: exactly once) and persistent sessions, where the broker queues messages for a client that is briefly offline.
- HTTP/2 server push: lets a server send extra responses (for example a stylesheet) alongside the one the browser asked for, into the browser's cache. Application code cannot listen for it as an event stream.
- APNs (Apple Push Notification service) and FCM (Firebase Cloud Messaging): the platform push services. Your server sends a message to them; they deliver it over the single connection the OS maintains.
- Keepalive: a small message sent periodically so that middleboxes (carrier NAT gateways, firewalls) do not forget an idle connection. NAT (network address translation) devices drop idle mappings after a timeout, and after that the server can no longer reach the phone.
Comparison on the three asked axes
| WebSocket | MQTT | HTTP/2 server push | |
|---|---|---|---|
| Connection overhead | HTTP upgrade handshake plus TLS; per-message frame header 2 to 10 bytes, plus a 4-byte mask on client-to-server frames | TCP plus TLS plus a small CONNECT; fixed header as small as 2 bytes; a ping is 2 bytes each way | Rides an HTTP/2 connection the client already has open; no separate channel |
| Keepalive frequency | Not in the protocol at the application level: you send ping frames on a timer you choose, short enough to beat the shortest NAT or proxy idle timeout | Negotiated in CONNECT as a keepalive interval in seconds; the broker disconnects a client that is silent for 1.5 times that interval | Governed by the HTTP/2 connection's idle timeout; nothing to keep alive for events because it does not deliver them |
| Battery impact | Each ping wakes the cellular radio; cost is driven by ping frequency, not bytes | Same physics, but smaller packets and QoS plus persistent sessions let you tolerate a longer interval and brief drops | Not applicable for notifications |
| Caveats | Some corporate proxies strip the Upgrade header; background execution limits (iOS and Android suspend an app's process and close its network sockets soon after it leaves the foreground, to save battery) kill the socket | Needs a broker; TCP port 8883 may be blocked on some networks, so offer MQTT over WebSockets on 443 as a fallback; same background limits | Disabled by default in Chromium since version 106; server push was never an API for app messages |
Why the radio, not the bytes, drains the battery
A cellular radio that wakes to send even a 2-byte ping moves to a high-power state and stays there for a "tail" period (seconds, carrier-dependent) before dropping back to idle. So the battery cost of a keepalive scheme is roughly number of wake-ups per day times tail duration, almost independent of how small the ping is.
Worked example with an illustrative 5-second tail (the real figure varies by carrier and radio technology, so measure it rather than trust this number):
| Keepalive interval | Wake-ups per day (86,400 s / interval) | Radio-on time per day at 5 s each |
|---|---|---|
| 30 s | 2,880 | 14,400 s = 4 hours |
| 5 min | 288 | 1,440 s = 24 minutes |
| 29 min | about 50 | about 250 s = about 4 minutes |
This is why every app running its own background socket is a bad idea: ten apps each pinging every 30 s would keep the radio awake for hours a day. APNs and FCM exist precisely to share one connection, with one keepalive schedule tuned by the OS vendor, across every app on the phone.
Recommendation and caveats
- Background: APNs and FCM. Send a notification (or a silent data message, a push payload with no visible banner or sound, meant to wake the app briefly to fetch fresh data in the background) through them. On iOS a suspended app cannot keep its own socket alive, so this is not optional. Caveats: delivery is best-effort, the platforms may throttle or coalesce silent or low-priority messages, and payload size is limited, so send an ID and let the app fetch details.
- Foreground: MQTT over TLS on port 8883, with MQTT over WebSockets on 443 as the fallback. Use QoS 1 plus a persistent session so a message sent during a brief tunnel or elevator drop is queued by the broker and delivered on reconnect. Set the keepalive as long as the carrier NAT timeout allows (start around a few minutes and tune from field data); a shorter interval buys faster dead-connection detection at a direct battery cost.
- WebSocket instead of MQTT is reasonable if you already run a WebSocket gateway for the web app and the mobile traffic is low; you then build the per-message acknowledgements and offline queue yourself, which MQTT gives you for free.
- Proxies: any channel on a non-standard port can be blocked on corporate or hotel Wi-Fi; TLS on 443 is the most likely to survive, and a WebSocket through a proxy that strips the Upgrade header will fail until you fall back.
- Deduplicate across channels: the same event may arrive via push and via the live channel. Give every notification an ID and have the app ignore one it has already shown.
Pitfalls
- Recommending HTTP/2 server push because the name sounds right.
- Minimising bytes instead of minimising wake-ups.
- Forgetting that a notification you cannot deliver in time should expire (a "your driver is here" alert is useless an hour later); both push services let you set an expiry.
Compare WebSockets, Server-Sent Events (SSE), long polling, and regular polling for real-time client-server communication. For each transport explain: connection model (half/full-duplex), typical latency characteristics, browser/proxy support, server resource implications, and common use-cases (e.g., collaborative editing, live notifications, stock tickers). Conclude with recommended transport(s) for (a) a live chat app and (b) a server-to-many broadcasting system.
Sample Answer
Direct answer
All four transports answer the same question: how does the server tell the client something changed? Regular polling asks on a timer, long polling asks and lets the server hold the request open until there is news, Server-Sent Events (SSE) keeps one HTTP response open and streams events down it, and WebSockets upgrade one connection into a two-way message pipe. For (a) a live chat app I would pick WebSockets, because both sides send frequently. For (b) a server-to-many broadcast I would pick SSE, because traffic is one-way and SSE is plain HTTP with reconnection built in. Polling stays as the fallback tier, not the primary design.
The four transports in plain terms
- Regular (short) polling: the client sends
GET /updates?since=...every N seconds. Most responses are empty. Simple, works everywhere, wasteful. - Long polling: the client sends the same request, but the server does not answer until an event arrives or a timeout (say 25 seconds) passes. The client immediately re-requests after each response. Near-real-time over ordinary HTTP.
- SSE: the browser's
EventSourceAPI opens one HTTP request whose response never ends; the server writesdata: ...lines as events happen. One direction only (server to client). The client sends anything upstream with normal HTTP requests. - WebSocket: starts as an HTTP request with an
Upgrade: websocketheader; after the server answers101 Switching Protocols, the same TCP connection carries framed messages in both directions at any time.
Two terms the comparison needs. Full-duplex means both sides can send at the same moment on one connection (WebSocket). Half-duplex means one direction at a time: each HTTP request/response exchange is effectively half-duplex, so polling and long polling are half-duplex, and SSE is a one-way (simplex) stream.
Comparison across the five asked axes
| Axis | Regular polling | Long polling | SSE | WebSocket |
|---|---|---|---|---|
| Connection model | New request per interval (or reused keep-alive connection); half-duplex | One held request at a time; half-duplex | One long-lived HTTP response; server to client only | One upgraded TCP connection; full-duplex |
| Typical latency | Average delay is about half the interval plus one round trip (5 s interval: about 2.5 s average, up to 5 s) | About one round trip when an event arrives; an extra round trip if a second event lands while the client is re-requesting | One-way network latency | One-way network latency, lowest framing overhead per message |
| Browser / proxy support | Universal | Universal; some proxies time out held requests, so keep the hold below their idle timeout | All modern browsers; response-buffering proxies can delay events (disable buffering); on HTTP/1.1 browsers cap around 6 connections per origin, so use HTTP/2 | All modern browsers; some corporate proxies and old intermediaries block the Upgrade; load balancers need idle timeouts above your heartbeat |
| Server resources | No held connections, but request rate is high and mostly wasted | One held connection per client, plus a full request cycle per event | One held connection per client; cheap per message | One held connection per client; cheap per message; state (auth, subscriptions) lives with the connection |
| Common use cases | Low-urgency dashboards, status pages, fallback | Legacy real-time, environments where streaming is blocked | Live notifications, stock tickers, sports scores, log tails | Chat, multiplayer games, collaborative editing, anything with frequent client-to-server traffic |
A keep-alive connection (in the Connection model row) is a single TCP connection reused across several sequential requests instead of opening a new one each time; it still carries one request at a time, so reusing it does not make polling any less half-duplex.
Push versus pull, and who pays for it
Polling is pull: the client decides when to ask, so cost scales with the number of clients times the poll frequency, whether or not anything happened. SSE and WebSockets are push: cost scales with connection-time and with the number of real events. Long polling sits between (push semantics, pull mechanics).
This matters for the bill and for the network:
- Per-request pricing. Many managed gateways and load balancers charge per request or per processed unit. Polling generates requests even when there is no news; push generates billable messages only for real events plus heartbeats.
- Per-connection pricing. Managed WebSocket services typically charge for connection-minutes as well as messages. For clients that are connected all day but rarely receive anything, a long poll interval can be cheaper than a held connection. Run both numbers for your own traffic shape.
- Mobile radio and battery. Every poll wakes the cellular radio, and the radio stays in a high-power state for a while after each transfer. Frequent polling from a phone drains the battery far more than the tiny payloads suggest.
Worked cost example (1 million connected clients)
Assume an empty poll costs about 800 bytes of request plus response headers (an estimate; measure your own), and a WebSocket heartbeat (a small ping message either side sends on a timer, answered with a pong, so both sides know the connection is still alive) ping/pong pair costs about 100 bytes on the wire including TCP/IP overhead (also an estimate).
- Polling every 5 s: 1,000,000 / 5 = 200,000 requests per second, mostly empty. 200,000 × 800 B = 160 MB/s, which is 160 MB/s × 86,400 s ≈ 13.8 TB per day of overhead.
- Polling every 30 s: 1,000,000 / 30 ≈ 33,333 requests per second, with an average staleness of 15 s. That is 33,333 × 800 B ≈ 26.7 MB/s, which is 26.7 MB/s × 86,400 s ≈ 2.3 TB per day.
- WebSocket with a 30 s heartbeat: 1,000,000 / 30 × 100 B ≈ 3.3 MB/s, about 288 GB per day, and events arrive within one network latency.
The push option carries roughly 48 times less idle overhead than 5 s polling (13.8 TB vs 0.288 TB), but that comparison mixes a 5 s interval against a 30 s heartbeat, so do not read 48x as the inherent push-versus-pull gap. At the same 30 s interval, push still wins by roughly 8 times (2.3 TB vs 0.288 TB), because a heartbeat (about 100 bytes) is far smaller than a full HTTP poll's headers (about 800 bytes); push's real extra advantage on top of that is not needing a short interval at all, a WebSocket does not trade staleness for cost the way polling does. The price of push is a million held connections, which you must be able to run.
Worked hybrid: an intermittently connected mobile fleet
Consider a delivery-driver app for a globally distributed, intermittently connected fleet: drivers work worldwide, often on weak cellular signal and often with the app in the background. No single transport fits, so use three tiers that all feed one sync mechanism.
- OS push for battery-efficient wake. When the app is backgrounded, the OS suspends its sockets. Use the platform push service (Apple Push Notification service, APNs, or Firebase Cloud Messaging, FCM) to send a small "you have a new job offer" signal. The OS delivers it on a connection it already maintains, so the app pays no battery for its own connection.
- One pooled WebSocket when foregrounded and connected. When the app is in the foreground with a usable network, open a single WebSocket shared by every feature (job offers, chat with dispatch, route changes). "Pooled" here means one multiplexed (many independent logical streams of messages sharing one physical connection) connection per app, not one per screen.
- Adaptive-interval polling as the fallback. If the WebSocket cannot connect (a proxy strips the Upgrade, or the network flaps too fast to hold a connection), poll with an interval keyed to device and network state: for example 5 s on Wi-Fi in the foreground, 15 s on cellular, 60 s in battery-saver mode, always with random jitter (a small random offset added to each client's timer so they do not all fire at the same instant) so a fleet does not poll in lockstep.
The design move that makes this safe: every tier is only a trigger; the source of truth is one sync(since=cursor) endpoint. (A cursor is a marker, often a timestamp or sequence number, for the last update the client already has, so the server returns only what is newer.) A push notification, a WebSocket message and a poll response all cause the client to fetch everything after its last cursor. Missed or duplicated triggers then cannot lose or double-apply data, and switching tiers mid-shift is invisible to the driver.
The two recommendations
(a) Live chat: WebSockets. Users send and receive constantly (messages, typing indicators, read receipts). A full-duplex connection avoids a separate HTTP request per sent message and keeps per-message overhead to a few bytes of framing. Keep long polling or SSE-plus-POST as the fallback for networks that block the Upgrade.
(b) Server-to-many broadcasting: SSE. Traffic is one-way, so WebSocket's upstream channel buys nothing. SSE is plain HTTP, so it passes through proxies, HTTP-aware load balancers and authentication middleware unchanged; EventSource reconnects automatically and sends a Last-Event-ID header so the server can resume. Serve it over HTTP/2 so many streams share one connection. If the same product already runs a WebSocket fleet, reusing it is a reasonable choice; the fan-out architecture behind the transport (how one update is copied to many connections) matters more than the transport.
Trade-offs and pitfalls
- Choosing by latency alone. SSE and WebSockets have the same latency; the real differentiators are direction of traffic, intermediary support and operational cost.
- Forgetting that held connections are state. Push transports move cost from request handling to connection holding: file descriptors (the OS handle each open connection consumes; a machine can run out of these before it runs out of memory), memory per connection, and reconnect storms (when a server or node dies, every client it was holding tries to reconnect within the same few seconds, spiking load on whatever takes over). Plan for those.
- Polling in lockstep. A fleet that polls on the minute creates self-inflicted traffic spikes; always add jitter.
- Treating the transport as the delivery guarantee. Every transport drops messages across disconnects. Resumable cursors or sequence numbers, not the socket, are what make delivery reliable.
Design an offline-first synchronization architecture for a mobile client (for example a CRM app) that allows creating and editing records offline, supports conflict detection and resolution, and syncs efficiently across varying bandwidth, including partial syncs when bandwidth is limited. Describe data models, client change queues, batching thresholds, retry/backoff policies, the server-side reconciliation algorithm, and how you would present merges to users.
Sample Answer
Direct answer
The client treats its local database as the source of truth for the UI and records every user change in an outbox: a durable, ordered queue of operations waiting to be sent. A sync engine drains the outbox in batches when there is connectivity and pulls server changes since a cursor (a saved marker, such as a sequence number, recording exactly how far the last pull got, so the next pull resumes from there instead of re-fetching everything). The server applies each operation with a field-level three-way merge ("three-way" because it compares three values per field: the client's base version before it edited, the server's current version, and the client's new value), so edits to different fields never conflict and only same-field edits need a rule. Low-stakes fields resolve automatically; high-stakes fields (deal amount, stage) become a visible conflict the user resolves. On poor bandwidth the engine syncs in priority tiers: small, important changes first, large attachments last.
Offline-first means the app is designed to work fully without a network and treats the network as an optimisation, rather than bolting offline caching onto an online app.
Requirements I am designing to
- Sales reps create and edit accounts, contacts and opportunities offline for up to several days.
- Two people can edit the same record while one of them is offline.
- Networks range from office Wi-Fi to a weak 2G signal; sync must make progress even in short windows of connectivity.
- No edit is ever silently lost.
Data model
On the client (SQLite on the device):
| Table | Key columns |
|---|---|
records | id (a UUID generated on the device, so new records need no server round trip), type, fields (JSON), base_version (server version this copy came from), dirty flag |
outbox | op_id (UUID), client_seq (monotonic counter per device), record_id, op (create / update / delete), changed_fields with old and new values, base_version, attempts, priority |
sync_state | pull_cursor per record type, last successful sync time |
conflicts | record, field, local value, server value, who changed it |
On the server: each record has a version (increments on every committed change) and per-field field_version plus updated_by; a change log indexed by a global sequence gives pull cursors; an idempotency table keyed by op_id remembers operations already applied, so a retried batch is not applied twice.
Sync flow
sequenceDiagram
participant UI
participant DB as Local DB and outbox
participant Sync as Sync engine
participant API as Sync API
UI->>DB: edit field, append op to outbox
Sync->>DB: read next batch by priority
Sync->>API: push batch (op_ids, base versions)
API-->>Sync: per-op result: applied, merged, conflict
Sync->>DB: remove applied ops, store conflicts
Sync->>API: pull changes since cursor
API-->>Sync: changes and new cursor
Sync->>DB: apply changes, rebase pending ops
Push before pull, and rebase. "Rebase" here means: after pulling, any operations still in the outbox are re-applied on top of the fresh server data locally (the way you would redo your own edits on top of a document after fetching someone else's newer version), so the UI shows "server state plus my pending edits" without flicker.
Batching thresholds
Flush the outbox when any of these is true:
- 50 operations queued, or 64 KB of payload (keeps each request small enough to finish on a weak link);
- 5 seconds since the oldest unsent operation (bounded staleness when online);
- connectivity changes from offline to online, or the app is about to go to the background.
Each batch is atomic per operation, not per batch: the server returns a result for every op_id, so one bad operation does not block the other 49.
Retry and backoff
- Exponential backoff with full jitter: wait a random time between 0 and min(cap, base x 2^attempt), with base 1 s and cap 5 minutes. The jitter stops thousands of devices that lost signal together (say, a subway line) from retrying in lockstep when it returns.
- Retry only retryable failures: timeouts, 5xx (a server-side error status code, meaning the failure was the server's fault and retrying may succeed), and 429 ("too many requests", with a Retry-After header telling the client exactly how many seconds to wait before trying again). A 4xx (a client-side error, meaning the request itself was invalid) validation error goes to a "needs attention" state on that record instead of retrying forever.
- Retries are safe because each operation carries its
op_idand the server's idempotency table answers "already applied" for duplicates. - Reset backoff on any successful request, and trigger an immediate attempt on an OS connectivity-change event.
Partial sync when bandwidth is limited
Classify work into tiers and let the engine measure throughput (bytes per second of the last few requests) to decide how far down the list to go:
- Tier 1, always: outbox pushes of record fields, and pulls of records assigned to this rep changed since the cursor. Kilobytes.
- Tier 2, when throughput allows: other records in the rep's territory, activity history, related contacts.
- Tier 3, Wi-Fi or strong signal only: attachments, images, full history. Download as metadata first (name, size, thumbnail) and fetch content on demand.
Pulls use field projection (only the columns the mobile screens show) and compressed responses. Pagination by cursor means an interrupted pull resumes where it stopped rather than restarting.
Server-side reconciliation algorithm
For each incoming operation, in client_seq order per device:
-
If
op_idis in the idempotency table, return the stored result. -
If
base_version == current version, apply directly (the common case: nobody else touched the record). -
Otherwise, for each changed field: if the server's
field_versionfor that field is not newer than the client's base, apply the change (someone else edited a different field). If it is newer, it is a same-field conflict:- auto-resolve fields tagged low-stakes (notes append, phone number) with last-writer-wins by server receive time, keeping the loser in the audit history;
- flag high-stakes fields (amount, stage, close date, owner) as a conflict: keep the server value, store the client's value, and return
conflictfor that field.
Concrete trace: record
acmeis at serverversion12, withfield_version{phone: 12, stage: 10}. A rep's client last synced atbase_version12 (so its local base for every field is 12) and, while offline, editsstage. Meanwhile a colleague's earlier online edit already bumped the server'sstagefield_versionto 13. When the rep's queued op reaches the server withbase_version: 12: forstage, the server'sfield_version(13) is newer than the client's base (12), so this is a same-field conflict and the rep'sstagechange is flagged. If the rep had instead editedphone(serverfield_versionstill 12, unchanged since the rep's base), the server'sfield_version(12) is not newer than the client's base (12), so that change applies directly with no conflict. -
Deletes vs edits: an edit to a record deleted on the server returns
conflict: deletedand the client offers "restore with my changes" or "discard". -
Record the result under
op_id, bump version and field versions, append to the change log.
Presenting merges to users
- Non-conflicting merges are silent; the rep sees the colleague's changes appear with a small "updated by Priya, 10:42" note.
- Conflicts show a badge on the record and a side-by-side card: "You set Stage to Negotiate (offline, 9:10). Priya set it to Closed Lost (10:02)." Buttons: keep mine, keep theirs, edit.
- A sync status indicator ("3 changes waiting to sync") so reps trust that offline work is saved.
Worked example: a rep back from a site visit
The rep made 500 field edits offline over two days, each operation about 300 bytes as JSON.
payloadat 50 kbit/s (weak 2G)at 1 Mbit/s=500×300=150,000 bytes=150 KB=50,000150,000×8=24 s=1,000,000150,000×8=1.2 sAt 50 operations per batch that is 10 requests of 15 KB (about 2.4 s each on the weak link). If the signal drops after batch 6, 300 operations are safely committed and the next window resumes at batch 7. Compressing JSON typically shrinks it several-fold, so the real transfer is smaller; the batch size is what keeps each request short enough to finish.
Of those 500 edits, suppose 12 touched records a colleague also changed. Field-level merge resolves most of them automatically because the fields differ; only same-field edits on high-stakes fields reach the conflict card.
Trade-offs and pitfalls
- Whole-record last-write-wins is the classic data-loss bug: the rep's phone-number fix is overwritten by a colleague's stage change. Field-level merge fixes it cheaply.
- Server-assigned IDs break offline creation (the child contact cannot reference an account that has no ID yet). Device-generated UUIDs avoid the remapping problem.
- CRDTs would auto-merge everything but are the wrong tool for business fields like "deal amount", where a merged value is meaningless and a human decision is required. They fit free-text notes if collaborative editing is needed.
- Unbounded offline windows make the pull cursor and idempotency table grow; define a maximum (for example 30 days), after which the device does a full resync and its unsent operations are replayed against fresh data.
Draft a reconnection strategy for mobile clients connecting to a WebSocket real-time service that enforces server rate limits and must minimize battery usage. Include exponential backoff with jitter, maximum retry windows, progressive decay, fallback strategies to polling, and metrics to determine when to escalate or notify users.
Sample Answer
Direct answer
Reconnect with capped exponential backoff with full jitter (wait a random time between zero and a limit that doubles each failure), because it spreads a crowd of clients out so they do not all hit the server at once. Always obey the server's rate-limit signal (Retry-After) as a floor. Retry aggressively only for the first couple of minutes, then decay progressively to long intervals, and stop active retrying while the app is backgrounded or the OS says there is no network, relying on platform push to wake it. Reset the backoff immediately on real events (network change, app foregrounded, push received). If the network works but WebSockets keep failing, fall back to polling and probe back periodically. Measure time-to-reconnect, attempts per successful connect, and fallback share so you know when to tell the user and when to page someone.
Key terms
- Exponential backoff: after each failure, wait longer (1 s, 2 s, 4 s, ...), capped at a maximum.
- Jitter: randomness added to the wait. Full jitter picks uniformly between zero and the backoff limit.
- Thundering herd: many clients retrying in lockstep, for example after a server deploy disconnects them all at once.
- Rate limit: the server accepts at most N new connections per second and rejects the rest (HTTP 429 during the handshake, often with a
Retry-Afterheader saying how long to wait).
1. Backoff with jitter
For the n-th consecutive failure (starting at 0), with base 1 s and cap 60 s:
delayn=uniform(0, min(60, 1⋅2n)) seconds waitn=max(delayn, RetryAfter)- The server's
Retry-Afteralways wins if larger: the server knows its own load. - A deploy that deliberately closes connections should send a close reason telling clients to spread their reconnect over a window (for example "reconnect within 30 s"), so even the first attempt is jittered.
2. Maximum retry windows and progressive decay
| Phase | Condition | Behaviour |
|---|---|---|
| Fast | First 2 minutes of disconnection, app in foreground | Backoff as above, cap 60 s |
| Decay | 2 to 30 minutes | Cap raised to 5 minutes |
| Dormant | Over 30 minutes, or app backgrounded | No timed retries; reconnect only on a trigger |
| Offline | OS reports no network | No attempts at all until connectivity returns |
Why these particular cutoffs: most transient drops (a Wi-Fi to cellular handoff, a brief tunnel or elevator, a cell-tower handover) resolve in well under two minutes, so it is worth retrying hard during that window. A disconnection that outlasts 30 minutes is more likely a real outage, a backgrounded app, or the user out of range for a while, so retrying every 60 seconds and spending battery on mostly-failed guesses stops paying for itself; stretching the interval to 5 minutes still reconnects within a bounded time if no trigger ever fires, while costing far less battery over a long dormant stretch. These are starting points to tune from the metrics in section 4, not fixed constants.
Triggers that reset backoff to attempt 0: the OS reports a network change, the app comes to the foreground, a push notification arrives (APNs, the Apple Push Notification service, or FCM, Firebase Cloud Messaging), or the user taps retry. These are moments when success is actually likely, so they are worth a battery wake-up; a timer firing in a tunnel is not.
Battery reasoning: each attempt wakes the cellular radio, which then stays in a high-power state for a few seconds. The design minimises attempts that are likely to fail (offline, backgrounded, server shedding load) and concentrates attempts where success is likely.
3. Fallback to polling
- If attempts fail while ordinary HTTPS requests to the same host succeed (for example the handshake is rejected or the socket never delivers the first server message), the network is probably blocking WebSockets rather than being down.
- After 3 such failures, switch to long polling (repeatedly issuing a plain HTTP request that the server holds open until it has something to send, then the client immediately opens the next one) or SSE (Server-Sent Events, a one-way stream of events over a single long-lived HTTP response) for the session, and send client messages as
POSTs. Carry over the same sequence-number resume logic used on WebSocket reconnect: every message the server would have pushed also carries a per-connection sequence number, so on reconnect, or on a switch to a fallback transport, the client reports the last number it saw and the server resumes from there instead of replaying everything or leaving a gap. - Probe WebSocket again every 10 minutes in the background while in fallback, and remember the verdict per network so the next launch on that network does not pay the detection cost again.
- Do not fall back when the failure is a 429 or 503: that means the server is overloaded, and switching to polling adds more requests.
4. Metrics, and when to escalate or notify
Client-side metrics (sampled, sent when connected):
- Time from disconnect to reconnect (p50, p99: 50th and 99th percentile).
- Attempts per successful connection.
- Share of sessions in fallback mode, by network type and carrier.
- Rate-limit responses received.
- Radio wake-ups per hour attributable to reconnect logic.
Notify the user (in the foreground only):
- Show a quiet "Reconnecting..." indicator after 3 s disconnected, not immediately (most drops heal in a second or two).
- After 30 s, show "Offline. Messages will send when you're back online" and queue outgoing messages locally.
- Never show a modal error for connectivity.
Escalate to the on-call engineer (fleet-wide server alerts):
- Reconnect success rate across all clients drops below a threshold for 5 minutes.
- p99 time-to-reconnect exceeds its SLO (service-level objective).
- Fallback share jumps (a new network or proxy is blocking WebSockets).
- 429 volume stays elevated after a deploy has finished, meaning clients are not spreading out.
Worked example: why jitter matters
This runnable simulation models 100,000 clients disconnected at the same instant by a server deploy, with the server accepting at most 5,000 handshakes per second (so 20 s is the theoretical best).
import random, heapq
from collections import Counter
def simulate(strategy, clients=100_000, capacity_per_s=5_000, base=1.0, cap=60.0, seed=7):
"""All clients lose their connection at t=0 (e.g. a server deploy).
The server accepts at most capacity_per_s handshakes in each 1-second window;
extra attempts are rejected (HTTP 429) and the client schedules a retry."""
rng = random.Random(seed)
def delay(n): # n = number of failed attempts so far
if strategy == "fixed_1s":
return 1.0
exp = min(cap, base * 2 ** n)
if strategy == "exp_no_jitter":
return exp
if strategy == "exp_full_jitter":
return rng.uniform(0, exp)
events = [(delay(0), i, 0) for i in range(clients)] # first attempt
heapq.heapify(events)
per_second = Counter()
accepted = Counter()
attempts = 0
connected = 0
t_99 = None
while events:
t, cid, fails = heapq.heappop(events)
sec = int(t)
per_second[sec] += 1
attempts += 1
if accepted[sec] < capacity_per_s:
accepted[sec] += 1
connected += 1
if t_99 is None and connected >= 0.99 * clients:
t_99 = t
else:
heapq.heappush(events, (t + delay(fails + 1), cid, fails + 1))
return max(per_second.values()), attempts, t_99
for s in ["fixed_1s", "exp_no_jitter", "exp_full_jitter"]:
peak, attempts, t99 = simulate(s)
print(f"{s:16s} rejected handshakes={attempts - 100_000:7d} "
f"attempts per client={attempts / 100_000:.2f} 99% connected at t={t99:.1f}s "
f"peak attempts in one second={peak}")
Output:
fixed_1s rejected handshakes= 950000 attempts per client=10.50 99% connected at t=20.0s peak attempts in one second=100000
exp_no_jitter rejected handshakes= 950000 attempts per client=10.50 99% connected at t=903.0s peak attempts in one second=100000
exp_full_jitter rejected handshakes= 307225 attempts per client=4.07 99% connected at t=38.2s peak attempts in one second=124571
How to read it:
- Fixed 1 s retries recover in the theoretical minimum time but make each client try 10.5 times on average: 950,000 wasted handshakes the server must reject, and 10 radio wake-ups per phone.
- Exponential backoff without jitter is the worst of both: clients stay in lockstep, so each retry round is again 95,000 clients hitting a server that admits 5,000, and the rounds drift further apart as the delay grows. It takes 903 s to reconnect 99%.
- Full jitter reconnects 99% of clients in about 38 s with about 4 attempts per client and a third of the rejected handshakes of the other two.
The printed peak column gives a sharper, slightly counter-intuitive finding: full jitter's busiest single second (124,571 attempts) is actually higher than either lockstep strategy's (100,000 each). Every strategy's entire first wave of 100,000 clients tries within about a second of the disconnect either way, spread across [0 s, 1 s) with full jitter, or bunched at exactly t = 1.0 s with no spread at all when there is no jitter, since that delay is then a fixed number, not a random one. Jitter does not shrink that unavoidable first wave. What it changes is whether the wave re-forms: the two lockstep strategies give every rejected client the exact same next delay, so the roughly 95,000 clients turned away in round one all land on the same later second and get rejected together again, rebuilding a wave close to 100,000 on every round; full jitter spreads that same 95,000 thinly enough across a widening window that no later round ever rebuilds a wave anywhere near that size, which is the real reason it reaches 99% connected in 38 s instead of 903 s. The practical conclusion still holds: the server should spread the disconnects itself during a deploy rather than rely on client backoff alone to smooth that first, unavoidable wave.
Pitfalls
- Backoff that never resets, so a user returning to good coverage waits minutes.
- Retrying while offline or backgrounded, burning battery for nothing.
- Falling back to polling when the server is overloaded, which increases load.
- Treating every close as a failure: a server-initiated close with a reason should drive behaviour (for example "go to another region" or "reconnect in 20 s").
Unlock Full Question Bank
Get access to all 8 Real-Time and Streaming System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.