Summary#
Most system design answers stop at the load balancer. Real users, though, sit behind a client: a browser tab, an iPhone on a train, an Android phone with 4% battery, a smart TV, a car. The client isn't a passive screen. It decides how often the backend is called, how big the responses must be, what happens when the network vanishes, and how fast the product feels. Good backend designs are shaped by their clients.
-
Clients shape the backend. Each client type has its own screen size, network, update cycle and capabilities, so the API, payload sizes, versioning, auth and realtime channels must fit them. A mobile app you shipped two years ago is still calling your API today, so backward compatibility is a hard requirement, not a nicety.
-
Mobile constraints. Mobile networks have high and variable latency (tens to hundreds of milliseconds of round trip), drop out in tunnels and lifts, and switch between Wi-Fi and cellular. The cellular radio is one of the biggest battery drains, and it stays in a high-power state for seconds after each transfer. So the rule is: fewer, larger, batched requests. The operating system also suspends background apps, which limits what you can do when the app isn't on screen.
-
Offline-first and sync. An offline-first app reads and writes a local database, so the UI works with no network. A sync engine pushes queued local changes (an outbox) and pulls server changes using a cursor. To make that safe you need:
- client-generated IDs;
- idempotency keys;
- tombstones for deletions;
- a conflict-resolution policy: last-writer-wins, field-level merge, server-authoritative, or CRDTs.
-
Push notifications. Apps can't hold their own connections in the background, so pushes go through the platform services: APNs (Apple Push Notification service) and FCM (Firebase Cloud Messaging), plus Web Push for browsers. Your backend stores device tokens, sends small payloads (about 4 KB), handles invalid tokens, and treats delivery as best-effort. An in-app inbox is the reliable record.
-
Client caching and pagination. Clients cache at several levels: in memory, on disk or in a local DB, in the HTTP cache (
Cache-Control,ETag) and in service workers, so repeat views are instant and cheap. Lists use cursor-based pagination, with page sizes and prefetching tuned for scrolling. -
Shaping APIs for mobile. A Backend-for-Frontend (BFF) is an API layer per client type that aggregates many service calls into one screen-shaped response, trims fields, and owns client-specific concerns. GraphQL is an alternative that lets the client ask for exactly the fields it needs.
-
Frontend performance metrics. The web measures user experience with Core Web Vitals:
- LCP (largest contentful paint, good ≤ 2.5 s);
- INP (interaction to next paint, good ≤ 200 ms);
- CLS (cumulative layout shift, good ≤ 0.1).
All three are judged at the 75th percentile of real users. Mobile apps track cold start time, frame drops, crash-free sessions and battery use.
-
Mobile and frontend interviews. If you're interviewing for a mobile or frontend role, the "system" is the client: its architecture, data layer, offline behaviour, caching, rendering and API contract. Backend boxes are drawn only as needed.
Why It Exists#
Backend-centric designs make an implicit assumption: the client is a thin, always-connected, always-up-to-date caller with a fast network. Each part of that assumption is false for a large share of real traffic:
- Not always connected. Phones go through tunnels, lifts, rural areas, planes and congested stadiums. Users still expect to read what they saw a minute ago, and to write messages or log runs that sync later. The reference material for this handbook uses Strava as the example: the app keeps run data on the device while offline and syncs it when the network returns.
- Not fast. A round trip over 4G is typically 30–100 ms in good conditions and far worse on a weak signal. A screen that needs five sequential API calls takes half a second or more before anything is drawn, so the backend API's shape decides the client's latency.
- Not up to date. Web clients update on every page load, but mobile apps update when users choose to, after app store review. At any moment, several app versions call your API, some of them years old. Breaking an API field breaks real users, and you can't hot-fix their binary.
- Not cheap to run. Every request costs the user battery and data, and many users are on metered plans. A chatty app gets uninstalled, and a heavy web page loses visitors on mid-range phones.
- Not in control of the backend. Data cached on the client can go stale, and the backend can't reliably reach in to invalidate it. The caching reference makes this point directly: for user-facing caches, you have limited control from the backend.
These realities change backend decisions:
- what the API returns, and how many calls a screen needs;
- how writes are made idempotent, so offline retries don't duplicate;
- how changes are fetched incrementally (sync cursors, change feeds);
- how the server reaches a sleeping device (push via APNs/FCM);
- how versions are managed (additive changes, feature flags, minimum supported versions);
- where caches live, and how their freshness is controlled.
The same thinking shows up in interviews. A design for WhatsApp, Uber, Instagram or Strava that ignores offline behaviour, push and payload size misses half the system, and a mobile or frontend interview is entirely about the client side.
How It Works#
How clients shape backend design#
Start any design by listing the clients and what each needs. A typical consumer product has a web app, an iOS app, an Android app, sometimes a TV or watch app, third-party API users, and internal admin tools. They differ in ways that matter to the backend:
| Client | Network | Update cycle | Background ability | Screen and data needs |
|---|---|---|---|---|
| Web (desktop) | Usually fast and stable | Every page load | Limited: service workers, Web Push | Large screen, rich pages |
| Web (mobile browser) | Variable | Every page load | Very limited | Small screen; bundle size critical |
| Native iOS / Android | Variable, metered, flaky | Users update when they choose; old versions linger | OS-controlled: suspended, background tasks, push | Small screen, local DB, offline |
| TV, watch, car | Variable; watch is often via phone | Slow, sometimes firmware-tied | Minimal | Tiny or remote-control UI, minimal payloads |
| Third-party API | Server-to-server | Their schedule; you need long deprecation windows | N/A | Stable, documented, versioned |
Each difference becomes a backend requirement:
- API shape and aggregation. One mobile screen may need a profile, three lists and some counters. If each is a separate call, the client pays several round trips on a slow network. The backend should offer screen-oriented endpoints (via a BFF or GraphQL), so one request returns what the screen needs.
- Payload size. Send only the fields the client uses, compress responses (gzip or Brotli), use compact formats where it helps (Protocol Buffers for internal or high-volume mobile APIs), and serve resized images per device instead of originals.
- Versioning and compatibility. Mobile clients are long-lived. Changes must be additive: new optional fields, never renamed or removed ones until usage is gone. Version through URL or header, keep a minimum supported version for forced upgrades, and gate new behaviour with server-side feature flags (API Design Best Practices).
- Idempotent writes. Flaky networks cause retries, and offline queues replay writes. Every mutating endpoint should accept an idempotency key, so a duplicate submission is recognised and ignored (Idempotency and Safe Retries).
- Incremental sync. A client that already has most data should fetch only what changed since its last sync. That calls for change feeds,
updated_atindexes and tombstones on the server. - Reaching the client. In the foreground, clients can hold a WebSocket or SSE connection. In the background they can't, so the backend needs a push path through APNs and FCM (Polling, Long Polling, SSE, WebSockets and Webhooks).
- Auth suited to the client. Browsers use cookies with
HttpOnly,SecureandSameSiteflags, or short-lived tokens. Mobile apps use OAuth 2.0 with PKCE, store refresh tokens in the Keychain or Keystore, and refresh silently (Authentication and Authorization). - Rate limits and abuse. Client code is public and can be reverse-engineered, so never trust it. Enforce limits and validation server-side, and use device attestation (App Attest on iOS, Play Integrity on Android) where abuse matters (Rate Limiting and Throttling).
Mobile constraints: battery, flaky networks and the operating system#
Network realities. Design for these properties of mobile networks:
- Latency is high and variable. Round trips range from ~20–50 ms on good 5G or Wi-Fi to hundreds of milliseconds on weak 4G or 3G, with occasional multi-second stalls. A new HTTPS connection costs DNS + TCP + TLS: one to three round trips before any data, or fewer with TLS 1.3, connection reuse and HTTP/3.
- Bandwidth varies and is often metered. Users on prepaid data plans notice heavy apps.
- Connectivity drops and switches. Moving from Wi-Fi to cellular changes the device's IP address, which breaks TCP connections. HTTP/3 over QUIC supports connection migration using connection IDs, so a session can survive a network change (TCP vs UDP (and QUIC)).
- Captive portals and middleboxes. Hotel Wi-Fi may intercept traffic, and some networks kill idle connections after tens of seconds. Long-lived sockets need heartbeats and reconnect with backoff and jitter.
Battery and the radio. The cellular radio has power states. After a transfer, it stays in a high-power state for a "tail" of several seconds before stepping down. So ten small requests spread across a minute keep the radio awake far longer than one batched request carrying the same bytes. Practical rules:
- Batch and coalesce. Send analytics in batches. Combine background syncs. Prefetch the next page while the radio is already awake.
- Avoid polling. A 30-second poll in the background keeps the radio warm constantly. Use push to trigger a sync instead.
- Defer non-urgent work until the device is on Wi-Fi and charging. The OS schedulers help here: WorkManager on Android and BGTaskScheduler on iOS.
- Keep sockets foreground-only. Hold a WebSocket only while the app is visible, and close it when the app goes to the background.
- Mind the other drains. GPS, camera and sensors drain the battery too. Location tracking should use the coarsest accuracy that meets the need, and significant-change APIs where possible.
The operating system is in charge. Mobile OSes aggressively manage background work to save battery:
- iOS suspends apps soon after they leave the screen. Background execution is limited to specific modes (audio, location, VoIP, background fetch, background processing tasks), and background refresh is opportunistic: the OS decides when, based on usage patterns and battery.
- Android has Doze mode and App Standby Buckets, which defer network access and jobs for idle apps. Manufacturers often add more aggressive battery savers.
- Both platforms throttle silent (data-only) pushes, so you can't rely on them as a precise wake-up timer.
The backend consequence is that the server cannot assume the client is running. Anything time-sensitive must go through user-visible push notifications. Data the user needs on opening the app should be fetched quickly on launch (one aggregated call) or prefetched opportunistically.
Device diversity. Android especially spans low-end phones with 2–3 GB of RAM and slow storage up to flagship devices. The same image-heavy feed may scroll smoothly on one and stutter on another. Backend levers include:
- serving smaller images to low-end devices or slow networks, using client hints or explicit size parameters;
- capping page sizes;
- avoiding huge JSON documents that are slow to parse on weak CPUs.
Release and update cycle. Shipping a mobile release involves several steps:
- Build and sign the app.
- Submit to app store review, which usually takes hours to a few days.
- Roll out in stages. Google Play supports percentage-based staged rollouts, and the App Store offers a phased release of automatic updates over seven days.
- Watch crash and performance dashboards.
Even after rollout, many users stay on old versions for months. That leads to standard practices:
- Server-driven configuration and feature flags, so behaviour can change without a new binary, including kill switches for broken features.
- Minimum supported version checks returned by the API, prompting or forcing an upgrade for versions with security or compatibility problems.
- Contract tests that run the current API against old client versions' expectations.
- Server-driven UI in some apps: the server sends a layout description (sections and component types) that the client renders. That allows UI changes without releases, at the cost of complexity and a less native feel.
Offline-first and sync#
Online-first vs offline-first. In an online-first app, the UI calls the API and shows a spinner, and with no network it shows an error. In an offline-first app, the UI talks only to a local database. The network is a background concern handled by a sync engine. Reads are instant (local), writes are instant (local, then queued), and the app works on a plane. The user sees data that may be slightly stale, with clear indications when something is still pending.
Not every app needs full offline-first. There's a spectrum:
| Level | What works offline | Typical apps |
|---|---|---|
| 0: Online only | Nothing; show an error | Banking transfers, live auctions, checkout |
| 1: Cached reads | Last-seen content is viewable | News, social feeds, catalogues |
| 2: Queued writes | Reads plus actions that sync later | Messaging, fitness logging, field-service forms |
| 3: Full offline-first | All features on a local DB, with background sync and conflict handling | Notes, task managers, document editors, field data collection |
Pick the level per feature, not per app. A chat app may queue outgoing messages (level 2) but require the network to create a group (level 0).
The core architecture.
How a write flows:
- The user creates a note. The app generates a client-side ID, a UUID or ULID (Unique ID Generation), so the record has a stable identity before the server ever sees it.
- The repository writes the note to the local DB and appends a mutation to the outbox,
{ id, op: "create", payload, idempotencyKey, createdAt }, in the same local transaction. That's the client-side version of the outbox pattern (Change Data Capture and the Outbox Pattern). - The UI updates immediately from the local DB and marks the note as "pending sync".
- When the network is available, the sync engine sends outbox entries in order, each with its idempotency key.
- The server applies each mutation once. A replay with the same key returns the original result. The server responds with the authoritative version: server timestamps, a version number, any server-computed fields.
- The client deletes the outbox entry and updates the local record with the server's version.
How a read sync flows:
- The client stores a sync cursor: an opaque token naming the last change it has seen (a sequence number, a log offset, or a server timestamp plus ID).
- It calls
GET /sync?cursor=abc, and the server returns changes after the cursor, each tagged with its new sequence position, plus a new cursor and ahasMoreflag. - The client applies the changes in a local transaction and stores the new cursor in the same transaction, so a crash can't lose or double-apply a batch.
- Deletes arrive as tombstones: records saying "ID 42 was deleted at sequence 9001". Without them, the client couldn't tell a deleted item from one it simply hasn't been told about. Servers keep tombstones for a retention window. Clients whose cursor is older than that window must do a full resync.
Outbox entry lifecycle.
Conflicts. A conflict happens when two devices (or a device and the server) change the same record while out of contact. To detect it, each record carries a version: a counter, an ETag or a timestamp. Each mutation sends the base version it was made against. If the server's current version differs, there's a conflict. Then there are several ways to resolve it:
- Last-writer-wins (LWW): keep the change with the latest timestamp. It's simple, but it silently drops the other change, and device clocks are unreliable (Time, Clocks and Ordering). Use server-assigned order where possible. LWW is acceptable for low-value fields like a "last opened" time or a preference toggle.
- Field-level merge: track versions per field, so editing the title on one device and the due date on another both survive. True conflicts only arise when the same field changes on both.
- Server-authoritative with rejection: the server rejects the stale write, and the client shows the latest version and asks the user, or re-applies its intent. This suits inventory, bookings and money, where silent merging would be wrong.
- Operation-based merge: send intents ("add item X to list", "increment counter by 1") instead of whole records, so many concurrent operations commute naturally. This is the idea behind CRDTs (conflict-free replicated data types), whose merge function always converges (Conflict Resolution, OT and CRDTs).
- Domain rules: for example, "the latest completed run wins, but distance is never reduced", or "a message is never lost, only reordered".
The idempotency requirement. Offline queues guarantee retries. The client may send a mutation, lose the response in a tunnel, and send it again. Without idempotency keys, the server creates duplicate orders, messages or runs. The server stores (userId, idempotencyKey) → result for a retention period, at least as long as the client's maximum retry window (often 24 hours to several days for offline apps), and returns the stored result on duplicates.
Ordering. Mutations from one device should be applied in the order they were made. That's natural if the outbox is sent sequentially, or if each mutation carries a per-device sequence number the server checks. Across devices there's no global order without the server. The server's change log provides the canonical order that all devices converge to.
Sync triggers. The sync engine runs:
- on app launch and on return to the foreground;
- on connectivity regained;
- on a silent push saying "something changed", which works best-effort since the OS throttles these;
- periodically through WorkManager or BGTaskScheduler, when the OS permits;
- immediately after a local write, if online.
Debounce and coalesce, so ten quick edits become one sync batch.
Initial sync and large datasets. A new device can't replay years of changes. Instead it does a bootstrap:
- Download a snapshot, or the most relevant subset (last 30 days, current projects), often as compressed files from object storage or a CDN.
- Switch to incremental sync from the snapshot's cursor.
Large or old data is loaded lazily on demand, and media (photos, attachments) is synced separately: metadata first, blobs lazily, and uploads resumable (Pattern: Handling Large Files and Blobs).
Local schema migrations. The local database has a schema that evolves with app versions. Migrations run on app upgrade and must handle every older version still in the wild, so test migrations from the oldest supported version. If the server's sync format changes, version it, and support old formats until old clients age out.
Security of local data. Data on the device can be read if the device is compromised or backed up insecurely:
- Store secrets in the Keychain (iOS) or Keystore (Android), never in plain preferences.
- Encrypt sensitive local databases (for example, with SQLCipher), and respect OS data-protection classes.
- Wipe local data on logout.
- On the web, localStorage is readable by any script on the origin, so don't store tokens there if XSS is a risk.
Push notifications (APNs, FCM and Web Push)#
Why you can't push directly. A server can't open a connection to a phone: phones sit behind carrier NAT, change IPs, and the OS suspends apps. Each app holding its own background socket would drain the battery. So each platform runs one shared, OS-managed persistent connection per device to its own push service, and all apps' notifications travel over it:
- APNs (Apple Push Notification service) for iOS, iPadOS, macOS and watchOS. Your server sends requests over HTTP/2 to Apple's gateway, authenticated with either a token-based key (a JWT signed with a key from your developer account) or a TLS certificate.
- FCM (Firebase Cloud Messaging) for Android, and also usable for iOS and web through Firebase SDKs. Your server calls the FCM HTTP v1 API authenticated with OAuth 2.0 service-account credentials. The older legacy FCM API has been retired in favour of HTTP v1.
- Web Push for browsers, built on the Push API and a service worker. The browser vendor runs the push service, and your server sends encrypted messages identified by VAPID keys.
The registration and send flow.
Things the backend must get right:
-
Device tokens are per app install, and they change. They change on reinstall, restore, and sometimes OS updates, so the app should send its token on every launch, and the server should upsert it. One user has many tokens (phone, tablet, web browsers). Store
(userId, deviceId, platform, token, appVersion, locale, lastSeenAt). -
Invalid tokens must be removed. APNs returns an error with HTTP status 410 (reason
Unregistered) for tokens that are no longer valid, and FCM returns anUNREGISTEREDerror. Delete those tokens. Sending to dead tokens wastes capacity and can hurt sender reputation. Also expire tokens not seen for a long time, for example months. -
Payloads are small. About 4 KB for both APNs alert notifications and FCM messages. Send what's needed to show the alert plus IDs, and let the app fetch details when opened. Never put sensitive data in the payload, since it may be shown on a lock screen. Use generic text ("New message from Alex") if privacy requires.
-
Notification vs data messages.
- Notification (alert) messages are displayed by the OS even if the app isn't running.
- Data (silent) messages wake the app to do work, but both OSes throttle them, and iOS may not deliver them at all if the user force-quit the app.
Use alert notifications for anything the user must see. Use silent pushes only as hints ("sync now"), never as the only path for important data.
-
Priority and collapsing. APNs uses
apns-priority(10 for immediate, 5 for power-friendly delivery). FCM has high and normal priority. Use high only for time-sensitive, user-visible alerts; platforms may deprioritise apps that abuse it. Collapse keys (apns-collapse-id, FCMcollapse_key) replace an earlier undelivered notification with a newer one, so a device coming online gets "Score: 3–2", not five stale score updates. -
Delivery is best-effort. Push services store and forward for a limited time. A notification can be delayed, collapsed, dropped (device off for too long, OS throttling, user disabled notifications) or arrive out of order. So:
- keep an in-app notification inbox (server-side list, synced) as the source of truth;
- include IDs, so the app can dedupe a notification it already displayed via the live socket;
- never rely on push for correctness, such as "the payment completed" state. Push is a nudge; the app fetches truth.
-
Badges. Badge counts are often wrong when computed client-side. Compute the unread count on the server and send it in the payload, or let the app compute it on open.
-
Permissions. iOS requires explicit user permission, and Android does too since Android 13. Ask at a meaningful moment, not on first launch. Users who deny it need in-app or email fallbacks.
-
Rich notifications. Images, actions, replies and grouping are supported by both platforms. Media is fetched by the device (iOS uses a notification service extension), so host it on a CDN.
-
Live, ongoing state. For live progress such as a ride arriving, a delivery or a sports score, platforms offer special surfaces: iOS Live Activities, updated through APNs, and Android ongoing notifications. These are still push-driven, rate-limited and small.
The backend notification service. At scale, sending notifications is its own system (Design a Notification System):
- Ingest: product services emit events ("message.created", "order.shipped") onto a queue (Asynchronous Processing and Message Queues).
- Decide: for each recipient, check preferences (channels, categories, quiet hours, time zone), frequency caps, and deduplication. Choose channels: push, email, SMS, in-app.
- Render: apply localized templates (Internationalization and Localization).
- Fan out: workers per provider (APNs, FCM, Web Push, email, SMS) send with connection pooling. APNs HTTP/2 connections multiplex many concurrent requests. Workers handle provider rate limits, retries with backoff, and token cleanup.
- Track: record sent, delivered (where reported), opened, and failed. Feed the results into analytics and into automatic suppression of unengaged devices.
Broadcast fan-out maths. A breaking-news push to 50 million devices that must go out within 5 minutes needs about 167,000 sends per second. Plan for it:
- Pre-compute the audience (segment → token list) ahead of time.
- Shard workers by token range.
- Use many HTTP/2 connections.
- Expect the "thundering herd" afterwards. Many recipients open the app within seconds, so a push can multiply read QPS on the backend. Stagger sends over a few minutes, and pre-warm caches for the content being pushed (Cache Failure Modes: Stampedes, Hot Keys and Penetration).
Foreground realtime vs background push. While the app is open, use a WebSocket or SSE connection for live updates: chat messages, typing indicators, live locations (Pattern: Pushing Realtime Updates). When the app goes to the background, close the socket and rely on push. On return, reconnect and sync from the last cursor to catch anything missed. That gives a robust three-path design:
- the live socket, for low latency;
- push notifications, to get attention;
- sync, for completeness.
Client caching and pagination#
Where clients cache. Caching on the client is the cheapest caching there is: a hit costs zero network, zero server load and zero battery for the radio. The handbook's caching pages describe four places to cache: client, CDN, an external cache like Redis, and in-process (Caching Fundamentals). Client-side caching means storing data close to the requester. On user devices, that's the browser's HTTP cache, browser storage, or a mobile app's memory and on-device storage.
The caching layers:
-
In-memory caches. Kept in the running app: decoded images, recently viewed objects, and normalized client stores that keep each entity once by ID, so an update to user 42 refreshes every screen showing them. Apollo Client and Relay do this for GraphQL. TanStack Query and SWR cache by request key with stale-while-revalidate behaviour. Memory caches are lost when the app is killed and must be bounded (LRU) on memory-constrained phones.
-
On-device persistent stores.
- Mobile: SQLite (often through Room on Android, or Core Data or GRDB on iOS), key-value stores for small settings, and an image disk cache.
- Web: IndexedDB for structured data, the Cache Storage API (via service workers) for responses, and localStorage only for small, non-sensitive strings. localStorage is synchronous, so it blocks the main thread, and it's limited to a few megabytes.
-
The HTTP cache. Browsers and mobile HTTP stacks (NSURLCache on iOS, OkHttp's cache on Android) obey HTTP caching headers. The server controls them (HTTP, HTTP/2, HTTP/3 and HTTPS):
Cache-Control: max-age=31536000, immutablefor content-hashed static assets (app.3f9c2.js). They never change, because a new version gets a new filename.Cache-Control: private, max-age=60for per-user API responses that may be reused briefly.privatekeeps shared caches like CDNs from storing them.Cache-Control: no-cachemeans "store, but revalidate before each use". It is not "don't cache".no-storemeans "don't store at all", for sensitive data.ETagandIf-None-Match(orLast-ModifiedandIf-Modified-Since) let the client ask "has this changed?". A 304 Not Modified reply carries no body, saving bandwidth even though it still costs a round trip.stale-while-revalidate=Nallows serving a stale copy while fetching a fresh one in the background, so the user sees content instantly.
-
Service workers (web). A script that sits between the page and the network and can implement strategies per request type:
- cache-first for static assets;
- network-first, falling back to cache for HTML and API calls, which gives offline support;
- stale-while-revalidate for content that can be slightly old.
Workbox is a common library for these. Service workers also receive Web Push messages and can run Background Sync to retry failed requests when connectivity returns.
-
Caches inside client libraries. "Client" doesn't only mean a user device. Any caller can cache metadata to avoid extra hops:
- Redis Cluster clients cache the slot-to-node map, so they send commands directly to the right node and refresh the map only when redirected (Redis in Practice).
- DNS resolvers and HTTP clients cache lookups and connections.
- Service-discovery clients cache endpoint lists.
- Database drivers cache prepared statements.
The same rule applies everywhere: cache what's read often and changes rarely, and know how staleness is detected and corrected.
Freshness is the hard part. The backend can't reach into a phone and delete a cached value. The client must decide when to revalidate, using one of these tools:
- TTL plus revalidation: short
max-ageplus anETag, so most checks are cheap 304s. - Versioned resources: content-hashed URLs for assets, and a
versionorupdated_atfield so the client can tell whether its copy is outdated. - Server-driven invalidation hints: a push or socket message ("profile 42 changed") that tells the client to refetch. That's best-effort, so keep TTLs as the safety net.
- Sync cursors: for offline-first apps, the sync feed is the invalidation mechanism. Changes arrive as data.
- Logout and account switch: clear all caches for the previous user. Leaking cached data across accounts on a shared device is a real privacy bug.
Pagination for clients. Lists are everywhere: feeds, messages, search results, orders. Pagination keeps responses small and fast.
- Offset pagination (
?offset=40&limit=20) is simple and supports "jump to page 7". But the database still scans and discards the skipped rows, so deep pages get slow. Insertions also shift items, causing duplicates or gaps while the user scrolls: a new post at the top pushes item 20 down into page 2, and the client sees it twice. - Cursor (keyset) pagination (
?after=eyJ0IjoxNzAwfQ&limit=20) encodes the position of the last item, for example(created_at, id), in an opaque token. The queryWHERE (created_at, id) < (:t, :id) ORDER BY created_at DESC, id DESC LIMIT 20uses an index and stays fast at any depth (Database Indexing). New items don't shift the window. This is the default for feeds and infinite scroll. You lose random page access, which feeds rarely need. - Bidirectional cursors suit chat. A conversation opens at the latest message and the user scrolls up for older ones (
before=cursor), while new messages arrive at the bottom (after=cursor, or via the socket). Deep links to an old message open a window around it. - Page size. On mobile, size the first page to fill the screen plus a little: 10–25 items for a feed. Then prefetch the next page when the user is a few items from the end, so scrolling never hits a spinner. Larger pages mean fewer round trips but bigger first-load latency and parse cost. Balance them by measuring time-to-content.
- Counts are expensive. "Showing 1–20 of 12,483" requires a count query that can be slow on big tables. Prefer "has more" flags, approximate counts, or caching the count.
- Render only what's visible. List virtualization (RecyclerView on Android, UICollectionView or LazyVStack on iOS, virtualized lists on the web) renders only visible rows. That keeps memory and frame times stable over thousands of items. It's a client concern, but it lets the backend use reasonable page sizes without the client choking.
- Stable sort keys. Cursors need a unique, stable ordering. Add the ID as a tiebreaker to timestamps. For ranked feeds where scores change, snapshot the ranking for the session (a feed session ID), so pagination stays consistent.
Shaping APIs for mobile: Backend-for-Frontend and friends#
The problem. With fine-grained microservices, a home screen might need:
- the user's profile;
- unread counts from the messaging service;
- a personalized feed from the feed service;
- the hydrated posts behind that feed;
- an author record for each post;
- recommendations;
- feature flags.
Calling each from the phone means several round trips. Some calls are sequential (feed IDs, then posts, then authors), each costs 50–300 ms on mobile, and the radio stays awake throughout. Every service would also have to handle mobile auth, mobile versioning and mobile-specific trimming.
Backend-for-Frontend (BFF). A BFF is a thin server-side layer owned by and shaped for one client experience (API Gateway and Backend-for-Frontend). The mobile BFF exposes GET /home. Inside the data centre, where round trips cost about a millisecond, it calls the services in parallel where possible, joins the results, drops unused fields, and returns one compact, screen-shaped response.
The BFF typically owns:
- aggregation and orchestration of downstream calls, with timeouts and partial responses: if recommendations time out, return the feed without them (Resilience Patterns: Timeouts, Retries and Circuit Breakers);
- client-specific shaping, such as the TV app getting only titles and artwork URLs;
- version adaptation, keeping old app versions working while services evolve;
- image sizing and URL signing for the device's resolution;
- client auth translation, exchanging the session or token for internal service credentials.
When a BFF helps. It helps with multiple client types that have different needs, a slow client network, a microservice backend, or separate client teams that want to ship screen changes without waiting on service teams. The pattern is commonly credited to SoundCloud's move away from a single general-purpose API, and was popularised by Sam Newman's writing on it.
When it hurts. A BFF can grow into a "second monolith" holding business logic. Keep domain rules in the services and only composition and presentation in the BFF. Several BFFs can also duplicate logic, which a shared library or a shared aggregation layer can address. And it's another hop and another service to run. With one client and a simple backend, just design a good API.
GraphQL as an alternative or a partner. GraphQL lets the client send a query naming exactly the fields and nested relations it needs. The server returns that shape in one round trip (API Styles: REST, gRPC, GraphQL and More). It was created at Facebook for its mobile apps and open-sourced in 2015.
- Strengths: no over-fetching or under-fetching; one endpoint for many screens; strong typing and schema introspection; client-side normalized caches.
- Costs:
- HTTP caching is harder, because queries are usually POSTs. Work around it with persisted queries: a hash maps to a registered query, which allows GET and CDN caching, and it also blocks arbitrary queries.
- Expensive queries are possible, so you need query cost limits and depth limits.
- N+1 resolver fan-out, so you need batching with DataLoader-style loaders.
- Field-level authorization takes care.
Many companies combine the two approaches: a GraphQL layer is their BFF, or each BFF exposes GraphQL.
Other API-shaping techniques for mobile:
- Sparse fieldsets and expansions in REST (
?fields=id,name,avataror?expand=author). - Batch endpoints (
POST /batchcarrying several operations) to cut round trips for clients that can't use a BFF. - Delta endpoints (
/sync?cursor=) for offline-first apps, instead of re-fetching whole lists. - Compression with gzip or Brotli. JSON text compresses well, often by 70–90%.
- Protocol Buffers or similar binary formats for high-volume or bandwidth-sensitive mobile APIs. They're smaller and faster to parse, but less debuggable.
- Long-lived connections: HTTP/2 or HTTP/3 with connection reuse, so requests share one TLS session.
- Server-sent configuration so the client fetches settings once per session, cached, not per screen.
- Mobile-friendly errors. Machine-readable error codes, clear retry guidance (
Retry-After), and distinguishing "retry later" from "don't retry", so offline queues behave correctly.
Frontend performance metrics#
What users feel is how fast content appears and how quickly the page responds, not server latency. The web standardised a set of user-centric metrics. Google's Core Web Vitals are the most widely used:
| Metric | What it measures | "Good" threshold | Common culprits |
|---|---|---|---|
| LCP: Largest Contentful Paint | When the main content (largest image or text block) is rendered | ≤ 2.5 s | Slow server response, render-blocking CSS and JS, unoptimised hero images, client-side rendering that waits for data |
| INP: Interaction to Next Paint | Responsiveness: delay from user input to the next visual update, at roughly the worst interaction | ≤ 200 ms | Long JavaScript tasks on the main thread, heavy re-renders, large hydration |
| CLS: Cumulative Layout Shift | Visual stability: how much content jumps around unexpectedly | ≤ 0.1 | Images or ads without reserved space, late-loading fonts, injected banners |
These thresholds are assessed at the 75th percentile of real page loads. INP replaced the older First Input Delay (FID) as a Core Web Vital in 2024.
Supporting metrics:
- TTFB (time to first byte): server and network latency, including redirects, DNS, TLS and backend processing. A CDN and edge caching attack this (Content Delivery Networks (CDN), Edge Computing and Edge Functions).
- FCP (first contentful paint): the first text or image drawn.
- TBT (total blocking time): a lab metric summing the blocking portions of long tasks, which are main-thread tasks over 50 ms.
- JavaScript bundle size: compressed transfer size and parse and execute cost. A megabyte of JS can take seconds to parse and run on a mid-range phone, even when the download is quick.
Mobile app equivalents:
- Cold start time: launch to first meaningful screen.
- Warm start time.
- Time to interactive on key screens.
- Frame rendering: at 60 Hz there's a 16.7 ms frame budget, less on 90 and 120 Hz screens. Track the percentage of slow or frozen frames, i.e. jank.
- ANR rate: "Application Not Responding" events on Android, when the main thread blocks for about 5 seconds.
- Crash-free sessions and crash-free users.
- App size, which affects install conversion.
- Battery and network usage per session.
Field vs lab measurement:
- Real-user monitoring (RUM) collects metrics from actual users' browsers and devices: the web-vitals library, platform analytics, or crash and performance SDKs. This is the truth, and should drive decisions.
- Lab tests (Lighthouse, WebPageTest, device farms) are reproducible and catch regressions in CI before release.
How the backend affects frontend metrics. Several levers sit on the server side:
- TTFB comes from the backend and CDN.
- Rendering strategy sets when HTML with content arrives. With server-side rendering (SSR) or static generation it arrives in the first response, which helps LCP. Client-side rendering (CSR) waits for JS download, execution, then API calls. Streaming SSR sends the page shell immediately and streams the data-dependent parts as they're ready.
- API aggregation (BFF or GraphQL) cuts data round trips after load.
- Image services that resize and transcode (WebP, AVIF) per device shrink the LCP image.
- Caching headers decide whether repeat visits hit the network at all.
- Prefetch and preconnect hints (
<link rel="preconnect">,<link rel="preload">) and HTTP 103 Early Hints start critical downloads sooner.
Performance budgets. Set explicit limits per page or screen, for example "≤ 170 KB of compressed JS on the critical path", "LCP ≤ 2.5 s at p75 on mid-range Android over 4G", or "cold start ≤ 1.5 s". Enforce them in CI. Budgets turn "be fast" into a reviewable requirement, like an SLO for the client (Observability: Logs, Metrics and Traces).
When you get a mobile or frontend system design interview#
Most system design interviews are product design or infrastructure design rounds: design Uber or a rate limiter, with servers, databases and queues. But companies also run mobile system design and frontend system design rounds for client engineers (Interview Expectations by Level and How to Prepare). You'll usually know from the recruiter or the role. Signs include:
- the role is "iOS Engineer", "Android Engineer", "Frontend Engineer" or "Web Platform";
- the prompt says "design the client" or "design the app";
- or it names a client-heavy product: "design the Instagram feed app", "design a photo-upload flow", "design an autocomplete component", "design a news feed web page", "design an offline notes app".
How the focus shifts. In a backend round, the client is one box at the top. In a client round, the client is the system, and the backend is a set of APIs you may design but don't need to scale in detail. Interviewers look for:
- Requirements from the user's perspective: offline needs, supported devices and browsers, accessibility, internationalization, low-end device performance, and the realtime expectations of each feature.
- Client architecture:
- layering (UI, state, domain logic, data and repository, networking, persistence);
- patterns such as MVVM, MVI or unidirectional data flow on mobile, and component and state management on the web;
- module boundaries for large teams.
- The API contract: endpoints or GraphQL schema, request and response shapes, pagination, error handling, auth, realtime channel, and versioning. Expect to justify REST vs GraphQL, and polling vs SSE vs WebSocket.
- The data layer: what's cached where, the local DB schema, the sync and offline strategy, conflict handling, and media handling.
- Performance:
- startup, scroll performance and image loading on mobile;
- LCP, INP, bundle size, code splitting, SSR vs CSR and virtualization on the web.
- Reliability and quality: retries and backoff, idempotency, crash and error reporting, feature flags, staged rollout and kill switches, plus testing strategy.
- Security and privacy: token storage, certificate pinning trade-offs, XSS and CSP on the web, and PII on device.
A delivery framework for client rounds. The six-step backend framework (The System Design Interview Framework) adapts well:
- Requirements (about 5 minutes). Functional: the core screens and user actions. Non-functional: offline, latency targets (for example, feed visible in under 1 s on 4G), supported platforms, accessibility, and scale only as it affects the client, such as feed size or media volume.
- Client architecture (5–10 minutes). The layer diagram above, adapted to the product. State where the source of truth lives.
- Data model and API (10 minutes). Client entities and local schema, then the endpoints with pagination, the realtime channel and push payloads. For frontend rounds, this is the "data model and interface" part of the RADIO framework popularised by GreatFrontEnd: Requirements, Architecture, Data model, Interface, Optimizations.
- Key flows (10 minutes). Walk through two or three concretely. Examples: "open app cold → render cached feed → refresh"; "post a photo while offline → queue → upload resumable → confirm"; "receive a message while backgrounded → push → tap → open thread synced".
- Deep dives and optimizations (10–15 minutes). Offline and conflict handling, image pipeline and caching, scroll performance, startup time, pagination edge cases, accessibility, and release strategy.
- Wrap-up. Monitoring (RUM, crash rates), testing, rollout, and what you'd do next.
Common client-round prompts and the depth expected:
| Prompt | What they really probe |
|---|---|
| News feed app or page | Pagination, cursor design, image loading and caching, prefetching, virtualization, optimistic likes, new-post indicators |
| Chat app | Local message store, outbox and ordering, delivery receipts, socket lifecycle, push for background, sync on reconnect |
| Photo upload / Instagram post | Resumable chunked upload, background upload tasks, compression on device, progress, retries, presigned URLs |
| Autocomplete / typeahead component | Debouncing, request cancellation, caching results by prefix, race conditions (stale responses), keyboard accessibility |
| Offline notes or tasks app | Local-first DB, sync protocol, conflicts, multi-device, schema migrations |
| Maps or ride-tracking screen | Location update frequency vs battery, map tile caching, socket vs push, smoothing |
| Video player | Adaptive bitrate streaming, buffer management, preloading, offline downloads with licences |
Deeper treatments are in Frontend System Design and Mobile System Design.
In backend rounds, a little client awareness goes a long way. Even in a pure backend interview, a sentence or two on client concerns lifts the design:
- "the mobile app caches the last feed page so it opens instantly";
- "writes carry idempotency keys because the client retries";
- "the app uses push to wake for new messages and syncs from a cursor";
- "we serve resized images via the CDN per device size".
These show that you understand the end-to-end system. Don't spend more than a minute or two on it unless the interviewer pulls that thread.
When to Use It#
Apply these client considerations deliberately, with concrete signals:
- Offline-first, or at least queued writes, when:
- users create data in places with bad connectivity: field workers, fitness, travel, warehouses;
- losing a user's input would be a serious failure (a written message, a logged run, an inspection form);
- the app is used briefly and often, where waiting 1–2 s for a spinner each time hurts retention.
- Push notifications when the user must learn about something while the app isn't open: messages, ride arrival, delivery updates, security alerts, reminders. Also as a sync hint to reduce polling.
- A BFF or GraphQL when:
- a screen needs data from three or more services;
- you serve two or more client types with different shapes;
- mobile round trips dominate screen load time;
- client teams need to iterate on screen data without changing core services.
- Aggressive client caching when:
- data is read far more often than it changes (profiles, catalogues, settings, static assets);
- repeat-view latency matters;
- users are on metered or slow networks.
- Cursor pagination when lists are long, append-heavy (feeds, chats, logs), or scrolled infinitely.
- Frontend performance budgets when:
- acquisition depends on landing pages loading fast (SEO, ads, e-commerce);
- many users are on mid-range Android over cellular;
- you've seen conversion or retention correlate with speed in your own data.
- Mobile- or frontend-focused interview answers when the role is a client role, or the prompt is a client-heavy product.
When NOT to Use It#
Pick something else instead when:
- The domain needs strong, immediate consistency. Payments, stock trading, seat booking and auctions shouldn't let users "complete" actions offline that might fail later. Use online-only flows with clear errors, or queue the intent and show it as pending, never as confirmed.
- Data is simple and always fresh online. Building a full sync engine with conflict resolution for a mostly read-only, always-online internal tool is wasted complexity. HTTP caching plus
ETags is enough. - You need precise timing or guaranteed delivery. Don't use push for these. It's best-effort and throttled. Use in-app state synced on open, email or SMS for critical messages, or a foreground socket.
- One client consumes the API and the backend is small. A BFF just adds a hop and a service to run, and a well-designed REST API suffices. A BFF holding business rules is also a smell; move them back into services.
- The schema is small and stable, and edge caching matters most. GraphQL can be overkill; plain cacheable REST may serve better.
- Data is sensitive, or must be revoked instantly. Avoid caching it on the device: credentials, highly confidential documents under strict policy, data a user may lose access to at any moment. Use
no-store, short sessions, and remote wipe. - Lists need random access ("go to page 50", sorted tables in admin tools). Use offset pagination, or a search index, instead of cursors.
- You're in a backend infrastructure interview (a rate limiter, a key-value store). Don't spend time on client architecture. Mention client behaviour only where it affects the server, such as retries and idempotency.
How to Implement It#
- Inventory clients and constraints. List the client types, minimum supported versions, network conditions, and offline needs per feature (levels 0–3 above). Write latency targets from the user's view, for example "feed visible ≤ 1 s at p75 on 4G".
- Design screen-shaped APIs. Add a BFF or GraphQL layer for aggregation. Use cursor pagination for lists, sparse fields, compression and per-device image URLs. Make changes additive only. Return a
minSupportedVersionand feature flags in a config endpoint. - Make every write idempotent. Use client-generated IDs and an
Idempotency-Keyheader. Keep a server-side dedupe table with a retention window that covers offline retry periods. - Build the local data layer. Add a repository over a local DB, with an outbox in the same transaction as local writes and a sync cursor stored atomically with applied changes. Define the conflict policy per entity.
- Add sync triggers. Sync on launch, on foreground, on connectivity regained, on a silent-push hint, on a periodic OS-scheduled task, and after local writes, all debounced.
- Add push. Register tokens on every launch, store them per device, and send through a notification service with preferences, collapse keys, priority rules and token cleanup. Use push as a nudge; data comes from sync.
- Set caching headers. Content-hashed immutable assets,
ETags on API responses,privatefor per-user data, andno-storefor sensitive data. Add a service worker for offline web if needed. - Measure the client. RUM for Core Web Vitals or app startup and frames, crash reporting, and per-release dashboards. Set performance budgets in CI, and ship with staged rollouts and kill switches.
A minimal sketch of a client sync engine with an outbox, idempotency keys and cursor-based pull:
// Runs on launch, on foreground, on connectivity regained, and after local writes (debounced).
async function syncOnce(db: LocalDb, api: SyncApi): Promise<void> {
// 1. Push local mutations in order; each carries a stable idempotency key.
for (const m of await db.outbox.pendingInOrder(50)) {
try {
const res = await api.mutate(m.op, m.payload, {
idempotencyKey: m.key, // replay-safe: server returns stored result on duplicates
baseVersion: m.baseVersion, // lets server detect concurrent edits
});
await db.tx(async (t) => {
await t.records.put(res.record); // authoritative server version
await t.outbox.delete(m.key);
});
} catch (e) {
if (isConflict(e)) { await resolveConflict(db, m, e.serverRecord); continue; }
if (isPermanent(e)) { await db.outbox.markRejected(m.key, e.code); continue; }
return; // transient: stop, keep order, retry later with backoff
}
}
// 2. Pull server changes since our cursor, applying each page atomically with the new cursor.
let cursor = await db.meta.get("syncCursor");
for (;;) {
const page = await api.changes({ cursor, limit: 500 });
if (page.resyncRequired) { await fullResync(db, api); return; } // cursor older than tombstone retention
await db.tx(async (t) => {
for (const c of page.changes) {
if (c.deleted) await t.records.delete(c.id); // tombstone
else await t.records.putIfNewer(c.record); // ignore stale versions
}
await t.meta.set("syncCursor", page.nextCursor);
});
cursor = page.nextCursor;
if (!page.hasMore) break;
}
}| Technology | Fits when |
|---|---|
| SQLite (Room on Android, Core Data or GRDB on iOS) | Structured local data with queries, offline-first apps, outbox tables |
| IndexedDB (often via a wrapper such as Dexie) | Structured offline data in web apps; large datasets beyond localStorage limits |
| Realm, or sync-capable stores such as Firebase / Firestore offline persistence | You want an object store with built-in sync and accept the vendor's conflict model |
| CRDT libraries (Automerge, Yjs) | Collaborative or multi-device editing where concurrent changes must merge automatically |
| APNs (HTTP/2, token auth) | Notifications to Apple devices; required for iOS background alerts |
| FCM (HTTP v1 API) | Notifications to Android, and optionally iOS and web, through one provider |
| Web Push (Push API, service worker, VAPID) | Browser notifications for web apps without a native app |
| WorkManager (Android) / BGTaskScheduler (iOS) | Deferrable background sync and uploads under OS battery rules |
| Service workers with Workbox | Offline web, asset caching strategies, Background Sync retries |
| GraphQL with Apollo Client or Relay | Many screens with varied data needs; normalized client cache; persisted queries for caching |
| TanStack Query / SWR | Web or React Native data fetching with request-keyed caching and stale-while-revalidate |
| A BFF on Node.js, Go or Kotlin | Screen-shaped aggregation per client type, owned by client teams |
| Image CDN or resizing service | Per-device image sizes and modern formats (WebP, AVIF), which is often the biggest LCP and data win |
| RUM and crash tools (the web-vitals library, Firebase Crashlytics, Sentry) | Measuring real-user performance, crashes and ANRs per release |
| Feature flag and remote config services | Changing client behaviour without releases; kill switches; staged feature rollout |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Online-only client | Simplest; always fresh; no sync or conflicts | Useless offline; spinner on every screen; feels slow on mobile | Strongly consistent domains (payments, bookings); always-online tools |
| Cached reads (stale-while-revalidate) | Instant repeat views; cheap; easy to add | Stale data visible briefly; no offline writes | Feeds, catalogues, profiles, news |
| Queued writes (outbox) | Writes never lost; works in tunnels; good UX | Idempotency needed; pending states in UI; retries can fail later | Messaging, logging, forms, likes and comments |
| Full offline-first with sync | Instant UI; full offline use; multi-device | Sync engine, conflicts, migrations, tombstones: real engineering cost | Notes, tasks, field apps, editors |
| LWW conflict resolution | Trivial to implement | Silently loses concurrent edits; clock issues | Low-value fields, single-device data |
| CRDT / operation-based merge | Automatic convergence; no lost edits | Complex; metadata overhead; not all semantics fit | Collaborative and multi-device editing |
| Push notifications (APNs/FCM) | Reach backgrounded apps; battery-friendly; OS-managed | Best-effort, throttled, small payloads, permission required | Alerts, nudges, sync hints |
| Foreground WebSocket / SSE | Low latency; bidirectional (WebSocket) | Battery; drops on network change; no background on mobile | Live chat, presence, live tracking while visible |
| Polling | Simple; works everywhere | Wastes battery and server capacity; latency equals the interval | Rare checks, simple dashboards, fallback |
| BFF per client | Screen-shaped responses; client team autonomy; one round trip | Extra service and hop; risk of duplicated or business logic | Multiple client types, microservices, slow networks |
| GraphQL | Exact fields; one endpoint; typed; normalized client caching | HTTP caching harder; query cost control; N+1 resolvers | Many screens with varied needs; fast-moving clients |
| Offset pagination | Random page access; simple | Slow deep pages; duplicates or gaps when data shifts | Admin tables, small stable lists |
| Cursor pagination | Fast at any depth; stable under inserts | No random access; cursor design needed | Feeds, chats, infinite scroll |
| SSR / static generation | Fast LCP; SEO-friendly; works without JS | Server cost (SSR); hydration cost; complexity | Content and landing pages, e-commerce |
| Client-side rendering (SPA) | Rich interactivity; cheap static hosting | Slow first load; SEO harder; large bundles | Logged-in apps, dashboards, tools |
Common Pitfalls#
- Chatty APIs. A screen that makes 8 sequential calls over 4G takes seconds. Aggregate them in a BFF or GraphQL, and parallelise what must stay separate.
- Breaking old app versions. Renaming a field or changing an enum breaks clients you can't update. Keep changes additive, use contract tests against old versions, and keep a minimum-version gate.
- Non-idempotent writes with retrying clients. These produce duplicate orders, double posts and repeated payments. Use client-generated IDs and idempotency keys on every mutation.
- Trusting the client. Validation, pricing, permissions and rate limits enforced only in the app are bypassed by anyone with a proxy. The server is the authority.
- Treating push as reliable delivery. Notifications are delayed, collapsed or dropped. Keep a synced inbox and sync on open.
- Never cleaning up device tokens. Dead tokens bloat sends and error rates. Delete them on
Unregisterederrors, and expire stale ones. - Polling in the background. It drains the battery and gets throttled by the OS anyway. Use push hints plus sync.
- Sync without tombstones. Deleted items reappear, or never disappear, on other devices. Send deletions as tombstones, and force a full resync for cursors older than tombstone retention.
- Cursor stored separately from applied data. A crash between applying a batch and saving the cursor causes skipped or duplicated changes. Save both in one local transaction.
- Over-caching sensitive data, or leaving the previous user's data after logout on shared devices.
- Offset pagination on live feeds. Users see duplicates and skip posts as new items arrive. Use cursors with stable sort keys.
- Huge JavaScript bundles and unoptimised hero images. These are the most common causes of poor LCP and INP. Code-split, lazy-load below-the-fold content, and serve modern formats at the right size.
- Measuring only in the lab. A fast developer laptop on office Wi-Fi hides the experience of p75 users on mid-range phones. Use RUM.
- Holding sockets in the background, or reconnecting without backoff and jitter. After an outage, millions of clients reconnect at once and knock the service down again (Resilience Patterns: Timeouts, Retries and Circuit Breakers).
Real-World Examples#
-
Fitness tracking (Strava-style). The handbook's caching reference uses this exact case: the app records a run entirely on the device, GPS points included, while offline, then uploads it when connectivity returns. The backend implications are:
- an idempotent upload keyed by a client-generated activity ID, so retries don't create duplicate runs;
- resumable uploads for large GPS files;
- processing asynchronously after upload (segments, leaderboards);
- a push notification when processing finishes or someone gives kudos.
-
Messaging apps. Chat clients typically:
- keep a local message database, so conversations open instantly offline;
- queue outgoing messages with client IDs, showing a "pending" tick until the server acknowledges;
- hold a socket while in the foreground;
- rely on APNs and FCM for background alerts;
- sync from a per-conversation or per-user cursor on reconnect.
Message ordering and delivery receipts are built on the server-assigned sequence. See Design a Chat System (WhatsApp).
-
Social feeds and photo apps. The pattern is:
- cached first page on launch, then background refresh;
- cursor pagination with prefetch;
- per-device image sizes from a CDN;
- optimistic likes, queued if offline;
- a "new posts" pill, instead of shifting the list under the user.
Uploads use presigned URLs and resumable or chunked transfers. See Design a Photo Sharing App (Instagram) and Design a News Feed (Facebook / Twitter).
-
GraphQL at Facebook. GraphQL was created inside Facebook to power its native mobile apps' data fetching, so news feed screens could request nested data in one round trip, and it was open-sourced in 2015. It's a canonical example of the backend reshaping its API around mobile clients.
-
File sync clients. Desktop and mobile sync clients watch local changes, queue them, upload in chunks, and pull remote changes via a cursor. They handle conflicts by keeping both versions as "conflicted copies" rather than losing data. See Design File Storage and Sync (Dropbox / Google Drive).
-
Ride-hailing and delivery apps. The driver app sends location updates every few seconds while on a trip, which is a battery-versus-freshness trade-off. The rider app shows them over a foreground socket, and push notifies of arrival when backgrounded. See Design a Ride-Hailing App (Uber).
-
Collaborative editors. Editors keep a local replica of the document, apply edits instantly, and merge concurrent edits with OT or CRDTs, so offline edits reconcile when reconnected. See Design a Collaborative Editor (Google Docs).
Case studies that use this pattern#
- Design a Chat System (WhatsApp)
- Design a Notification System
- Design a Fitness Tracking App (Strava)
- Design a Photo Sharing App (Instagram)
- Design a News Feed (Facebook / Twitter)
- Design File Storage and Sync (Dropbox / Google Drive)
- Design a Collaborative Editor (Google Docs)
- Design a Ride-Hailing App (Uber)
- Design Search Autocomplete (Typeahead)
In the Interview#
Common follow-ups:
- "What happens when the user is offline and taps Send?" The message is written locally with a client ID and queued in the outbox, and the UI shows it as pending. On reconnect, the sync engine sends it with an idempotency key. The server dedupes, assigns order and acknowledges, and the client marks it sent. If the server rejects it, the UI shows an error and a retry.
- "How does the phone get a new message when the app is closed?" The backend's notification service sends through APNs or FCM to the device token. The OS displays the alert. On tap, the app opens and syncs from its cursor to fetch the actual messages; the push itself is just a nudge.
- "Two devices edited the same note offline. What now?" Detect it via base versions on the server. Then merge per field, or with CRDTs for text. For high-stakes data, reject and ask the user. Explain why plain last-writer-wins loses data.
- "Why not just poll every 10 seconds?" Battery and server cost. At 1M active devices, a 10 s poll is 100k requests per second, mostly returning "nothing new". Push hints plus a foreground socket deliver faster at a fraction of the cost.
- "How do you change the API without breaking old apps?" Additive changes only, versioned endpoints or fields for breaking changes, a BFF adapting responses per app version, feature flags, a minimum-supported-version gate, and contract tests.
- "The feed loads slowly on Android in India. Where do you look?" RUM split by device class and network: TTFB, so use the CDN and regional edge; payload and image sizes, so serve per-device images and compress; round trips, so aggregate; client rendering, so check list virtualization, main-thread work and image decoding.
Deep Dive: Designing a correct sync protocol, and the local-first ideaShow
Choosing the cursor is the subtle part. The obvious cursor is "the latest updated_at I've seen". The client asks for rows with updated_at > T. That has three bugs at scale:
- Clock skew between app servers. If writes are timestamped by different machines' clocks, a later write can carry an earlier timestamp and fall behind the cursor forever.
- Equal timestamps. Many rows can share the same millisecond. If a page boundary falls inside a group of equal timestamps, rows are skipped. The fix is a compound cursor
(updated_at, id). - Late commits. This one is the most insidious. Transaction A gets timestamp 100 but commits after transaction B, which got timestamp 101. A client syncing between the two commits sees B, advances its cursor to 101, and never sees A.
Robust designs avoid wall-clock cursors:
- A per-scope change log with a monotonic sequence number assigned at commit, for example an append-only
changes(seq, scope_id, entity_id, op, version)table written in the same transaction as the data change. The client cursor is the lastseq. Because a sequence obtained mid-transaction can still commit out of order, the server either serialises sequence assignment per scope, or only serves changes up to a safe high-water mark: the lowest sequence that might still be in flight. - The database's own replication log position (a WAL or binlog position via change data capture) projected into per-user feeds. It's naturally commit-ordered (Change Data Capture and the Outbox Pattern).
- A "lag margin": re-read a small window behind the cursor and dedupe by version. That's a pragmatic patch when only timestamps are available.
Sync scopes. Clients rarely sync "everything". Define scopes: per user, per workspace, per conversation, per project. Each scope has its own cursor, so joining a new workspace bootstraps only that scope, and permission changes become scope membership changes. When a user loses access to a scope, the server sends a scope revoked event, and the client deletes the local copy. Otherwise revoked data lingers on devices.
Versions and merges. Every record carries a version that increases on each server-side change. Mutations include the client's base version:
- If base equals current, apply the change and increment the version.
- If base is older, apply the conflict policy for that entity type.
For field-level merge, store per-field versions, or compare the base snapshot, the client's change and the current server value (a three-way merge, like version control). Worked example: the base note is {title: "Trip", body: "A"}. Device 1 changes the title to "Paris trip". Device 2 changes the body to "A, B". The three-way merge sees no overlapping field changes and produces {title: "Paris trip", body: "A, B"}. Only if both changed body is there a true conflict. Then either merge text with a CRDT or OT, or keep both versions and ask the user.
Hybrid logical clocks. When ordering must respect causality across devices without trusting wall clocks, hybrid logical clocks combine a physical timestamp with a logical counter. They stay close to real time while guaranteeing that causally later events get larger timestamps. They were introduced in "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases" (Kulkarni, Demirbas and colleagues, 2014), and many sync and database systems use them for LWW that doesn't go backwards (Time, Clocks and Ordering).
CRDTs. Conflict-free replicated data types (Shapiro, Preguiça, Baquero and Zawirski, "Conflict-free Replicated Data Types", 2011) are data structures whose merge is commutative, associative and idempotent. Any replicas that have seen the same set of updates converge, regardless of order or duplication, which is exactly what offline devices produce. Counters, sets, maps, registers, lists and text all have CRDT forms. Costs include metadata growth (tombstones, per-element IDs) and the fact that not every business rule can be expressed as a merge. "Never oversell inventory" is a constraint, not a merge, and still needs a server-side check (Conflict Resolution, OT and CRDTs).
Local-first software. "Local-First Software: You Own Your Data, in Spite of the Cloud" (Kleppmann, Wiggins, van Hardenberg and McGranaghan, 2019) argues that apps should treat the local copy as primary and the cloud as a sync and backup peer. That gives instant response, offline work, multi-device collaboration and user ownership. CRDTs are the enabling technology. It's the far end of the offline spectrum, and it's practical today for documents, notes and design tools. For most consumer apps, a server-authoritative design with local caching and an outbox remains simpler.
Bandwidth arithmetic. Suppose a task app has 5,000 tasks per user at about 400 bytes each, so a full download is about 2 MB (about 400 KB gzipped). Users open the app 10 times a day, and about 20 tasks change per day.
- Full refresh on each open costs about 4 MB per day per user compressed.
- Delta sync costs about 20 × 400 B ≈ 8 KB per day plus request overhead, roughly 500× less.
Across 10M daily users, that's about 40 TB per day versus about 80 GB per day of egress, before counting server CPU and battery. Delta sync isn't an optimisation; it's what makes the product viable.
Testing sync. Sync bugs are rare, timing-dependent and data-corrupting. Test with:
- deterministic simulations that randomise network drops, duplicate deliveries, reordering and crashes between steps;
- property checks that all replicas converge;
- upgrade tests from every supported app version's local schema.
Deep Dive: Connections, reconnect storms and push at scaleShow
Heartbeats vs NAT timeouts vs battery. A foreground WebSocket must send keepalives often enough that carrier NATs and load balancers don't drop it as idle. Idle timeouts vary by network, commonly from tens of seconds to a few minutes. Each heartbeat wakes the radio, though, so it costs battery. Typical choices are 25–60 s heartbeats in the foreground and no socket in the background (rely on push). Servers should also enforce their own idle timeouts and detect dead peers, since a phone that lost signal won't send a TCP FIN.
Socket server sizing. Each idle connection costs kernel buffers plus application state, often tens of kilobytes. 10M concurrent connections at 20 KB is about 200 GB of RAM across the fleet. At 100k–500k connections per well-tuned server, that's tens of servers before any message traffic. The connection tier should be stateless about business data: it keeps a userId → connection map in a registry or routes through pub/sub, so any server can deliver to any user (Pattern: Pushing Realtime Updates).
Reconnect storms. When a socket tier restarts or a region fails over, every client reconnects. Without jitter, 10M clients retrying at 1 s, 2 s, 4 s and so on arrive in synchronised waves. With full jitter (wait a random time between 0 and the backoff ceiling), arrivals spread evenly.
Worked example: spreading 10M reconnects uniformly over 60 s gives about 167k connections per second, each with a TLS handshake. That's still a heavy burst, so:
- Pre-scale the tier before planned deploys.
- Drain gradually. Close connections in batches during deploys, not all at once.
- Make the server reject with
Retry-Afterwhen overloaded, and have clients honour it. - Make reconnect cheap. Use TLS session resumption and avoid an expensive full sync on every reconnect: resume from the cursor, which is small.
Push throughput and token hygiene.
- Store sizing. A token store for 100M users with about 1.5 devices each holds 150M rows of roughly 300 bytes each, about 45 GB. That fits a sharded key-value store or a well-indexed relational DB.
- Throughput. Sends are I/O-bound HTTP/2 calls. One worker process with many multiplexed streams can sustain thousands of sends per second, so a broadcast of 50M in 5 minutes (about 167k/s) needs roughly tens to low hundreds of worker processes, depending on provider latency.
- Retries. Retry transient errors with backoff. Don't retry invalid-token errors: delete the token.
- Fairness. Respect provider guidance on per-device message rates, and use collapse keys so bursts to one device don't pile up.
Exactly-once display. The same event can reach the device by socket and by push, or by two pushes after a retry. Give each notification an ID. The app keeps a short-lived set of displayed IDs, and the server's inbox is idempotent by event ID (Delivery Guarantees: At-Most, At-Least and Exactly-Once). Users perceive duplicates as bugs, and missed notifications as unreliability. The inbox-plus-sync design handles both.
Engagement and abuse controls. At scale, notification volume is a product risk: users disable notifications or uninstall the app when spammed. Mature systems:
- apply per-user frequency caps and quiet hours in the user's time zone;
- rank candidate notifications, sending only the best few per day;
- learn per-user send times;
- suppress devices that never open notifications.
These are policy layers in the notification service, not in each product team's code (Design a Notification System).
Deep Dive: The physics of client performance, with worked budgetsShow
Radio energy model. A simplified cellular radio has three states: high-power active, a "tail" at moderate power for several seconds after activity, and idle. Suppose the active state costs about 1 W and the tail lasts 10 s at about 0.5 W (illustrative but realistic magnitudes).
- One request every 30 s spends most of each 30 s window in transfer plus tail. That's roughly 5+ J per request, mostly tail energy, regardless of how few bytes were sent.
- Batching the same data into one request every 5 minutes cuts tail overhead by about 10×.
This is why analytics SDKs batch events, why sync coalesces, and why "send a tiny ping often" designs are battery-hostile even with tiny payloads.
Cold-start budget over 4G. Target: home feed visible in 1.5 s at p75 on a mid-range phone with a 100 ms RTT.
| Step | Typical cost | Lever |
|---|---|---|
| Process start and app init | 300–600 ms | Lazy-init SDKs, defer non-critical work, smaller binary |
| Render cached feed from local DB | 50–150 ms | Keep the last page on disk; render before the network |
| DNS + TCP + TLS 1.3 to API | ~200–300 ms (2–3 RTTs) | Connection reuse, preconnect on start, HTTP/3 with 0-RTT where safe |
GET /home via BFF (server time ~80 ms) | ~180 ms (1 RTT + server) | One aggregated call, not five |
| Download about 40 KB compressed JSON | ~50 ms on decent 4G | Sparse fields, compression |
| First images (thumbnails from CDN) | 100–300 ms | Per-device sizes, CDN edge, progressive formats |
With a cached feed on disk, the user sees content after roughly 0.5–0.7 s, and fresh content follows. Without the cache and with five sequential calls, they'd wait an extra 0.5–1 s, mostly in round trips.
Web LCP budget. For LCP ≤ 2.5 s at p75 on mobile:
- TTFB about 0.6–0.8 s on mobile networks, including connection setup. A CDN-served or edge-rendered HTML response helps.
- Render-blocking CSS about 0.2–0.3 s.
- The LCP image, discovered early via
preloador in the HTML, and sized correctly. A 1.2 MB original hero image is about 2 s on a 5 Mbps connection, while a 100 KB AVIF version takes about 0.16 s.
Most LCP failures are an unoptimised or late-discovered hero image, or client-side rendering that waits for JavaScript and then for data before showing anything.
JavaScript cost. Compressed transfer size understates JS cost. A 300 KB gzipped bundle may be about 1 MB uncompressed, and parsing, compiling and executing it on a mid-range Android CPU can take on the order of a second or more of main-thread time. During that time input is blocked, which hurts INP. Levers:
- route-based code splitting;
- removing unused dependencies;
- deferring third-party scripts;
- server components or partial hydration, so less JS ships;
- moving heavy work to web workers.
Why the 75th percentile? Averages hide the slow tail where many users actually live. Core Web Vitals use p75 as a balance: it covers most users while staying robust against extreme outliers. Backend teams use p99 for server latency because each server call is one of many per page. For client experience metrics, p75 per page per device class and country is the actionable view. Always segment, because a global p75 can look fine while low-end Android in one market is failing.
Images dominate bytes. On most content-heavy pages and feeds, images are the majority of bytes. So:
- serve
srcset/ sizes on the web, and request per-density sizes on mobile; - use modern formats (WebP, AVIF);
- lazy-load below the fold;
- use blurred placeholders or dominant-colour boxes, which also prevent layout shift.
An image CDN that resizes on the fly with caching usually gives the single largest performance and data saving for client-heavy products (Content Delivery Networks (CDN)).
Key Takeaways#
-
Design for the real client. Clients are slow, flaky, battery-limited, OS-constrained and long-lived across versions, so APIs must be compact, screen-shaped, additive and idempotent.
-
Mobile constraints:
- batch requests to respect radio tail energy;
- avoid background polling;
- hold sockets only in the foreground;
- assume the OS will suspend the app;
- plan for network switches and reconnect with backoff and jitter.
-
Offline-first:
- the local DB is the UI's source of truth;
- an outbox of idempotent mutations;
- cursor-based delta sync with commit-ordered sequences;
- tombstones;
- a conflict policy per entity: LWW, field merge, server-authoritative, or CRDTs.
-
Push (APNs, FCM, Web Push):
- register tokens every launch;
- delete invalid tokens;
- keep payloads small (about 4 KB) and private;
- use priority and collapse keys.
Push is a best-effort nudge. The synced inbox is the truth.
-
Client caching:
- in-memory, on-device and HTTP caches;
- immutable hashed assets;
ETagrevalidation;privateandno-storewhere appropriate;- clearing caches on logout.
Paginate lists with cursors and stable sort keys, and prefetch the next page.
-
BFF or GraphQL turns many service calls into one screen-shaped round trip. Keep business logic in services.
-
Frontend metrics: LCP ≤ 2.5 s, INP ≤ 200 ms and CLS ≤ 0.1 at p75, plus mobile cold start, frames, ANRs and crash-free rate. Measure with RUM and enforce budgets in CI.
-
In interviews: in client rounds, lead with client architecture, the data layer, API contract, performance and release safety. In backend rounds, a few sentences on client behaviour (idempotent retries, push plus sync, per-device images) show end-to-end thinking.