Mobile Networking Starts Before the HTTP Request

A user taps Send on a train. The phone shows Wi-Fi, but the captive portal has not been accepted. It switches to cellular while the server is processing the request. The app times out and retries. Did the message arrive once, twice, or not at all? The HTTP client alone cannot answer.

The useful mental model is a distributed system with an unreliable last mile and a lifecycle-controlled client. A request moves through UI state, a repository, local persistence, authentication, transport, the server, and back again. Each boundary has its own failure modes. A connectivity icon only tells you about a network interface; it does not prove that DNS, TLS, your API, or the user's session will work.

Follow one message end to end

Suppose a messaging app supports offline composition. A reliable flow looks like this:

// Persist the user's intent before depending on the network. Send -> local transaction: message + outbox event // A constrained worker sends a stable event ID over authenticated HTTPS. Outbox -> scheduler -> API -> server deduplication -> response // Reconcile the acknowledgement into the same local source observed by UI. Response -> local transaction -> sent / retry / conflict state 

The UI observes the local database. A pending badge means the intent is durable on the device; it does not claim the server received it. The server assigns authoritative state. After an acknowledgement, the repository updates the local record and removes or marks the outbox entry. If the process dies after the server commits but before the acknowledgement is stored, the next attempt uses the same event ID.

This is an architectural choice, not a requirement for every GET request. A stock quote may simply show stale cached data and refresh when possible. A payment must not be represented as complete merely because it was queued locally. Product semantics decide what “saved,” “sent,” and “completed” mean.

Timeouts are uncertainty, not proof of failure

DNS resolution, TLS negotiation, connection establishment, response headers, and body transfer can each fail or stall. Set an overall deadline appropriate to the interaction and understand the client library's connection and read timeouts. A timeout only means the caller stopped waiting. The server may already have committed the mutation.

Use a stable idempotency key for each logical mutation. Scope it to the authenticated user and operation on the server, store the result durably, and reject reuse with a different payload. This requires server support: a client-generated header alone does not create idempotency. For reads, retries are usually simpler, but still bound attempts and total time. Retry transient connection errors and selected 429/5xx responses using exponential backoff with jitter; respect Retry-After where applicable. Do not repeatedly retry invalid input or authorization failure. Refresh credentials deliberately and limit refresh attempts.

iOS: URLSession and connectivity

URLSession supports async operations and system network policy. The example makes a foreground request; a durable background transfer needs a separately configured background session and delegate handling.

// Fetch a small resource while allowing the caller to cancel its Task. func loadMessage(id: String, session: URLSession) async throws -> Data { // Build an HTTPS URL from a trusted base and validated identifier. let url = apiURL.appendingPathComponent("messages").appendingPathComponent(id) // Bound this request; configure resource-level deadlines separately as needed. var request = URLRequest(url: url, timeoutInterval: 15) request.httpMethod = "GET" // Await the native transport; cancellation and network failures propagate. let (data, response) = try await session.data(for: request) // Treat an HTTP error as a failure even when transport succeeded. guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { throw APIError.badResponse } return data } 

For a reusable session, configure waitsForConnectivity when waiting makes product sense. It applies to establishing a connection; a later connection loss still produces an error. Background sessions wait for connectivity regardless of that property. Apple URLSession connectivity.

Android: a lifecycle-aware repository

The following sketch uses an application-defined API and DAO. It keeps the durable mutation and outbox insert in one Room transaction; the scheduler is a separate step.

// Persist one logical send before requesting a network opportunity. suspend fun queueMessage(text: String) { // Use one stable identifier for local state and server deduplication. val eventId = UUID.randomUUID().toString() // Commit message and outbox together to avoid a half-written intent. db.withTransaction { messageDao.insertPending(eventId, text) outboxDao.insert(eventId) } // Schedule eligible persistent work; its timing belongs to the OS. syncScheduler.requestSync() } 

Call this from a lifecycle-owned coroutine and propagate CancellationException; handle actual database errors visibly. If the process dies between commit and scheduling, startup reconciliation must discover pending outbox rows and schedule again. WorkManager can constrain deferrable work, but a connectivity constraint does not guarantee your API is reachable. Android describes local-first reads, queued writes, and backoff as complementary techniques. Android offline-first architecture.

Flutter: cancellation and platform boundaries

This is an application-level abstraction, not a specific package API. The repository owns durable state; the native networking and scheduler plugins own platform integration.

// Save a send intent even if the screen closes before sync completes. Future<void> sendMessage(String text) async { // Generate once so every retry represents the same logical mutation. final eventId = idGenerator.newId(); // Commit both records atomically in the local database. await database.transaction(() async { await messages.insertPending(eventId, text); await outbox.insert(eventId); }); // Native scheduling remains subject to Android and iOS policies. await syncBridge.requestEligibleWork(); } 

A Dart Future.timeout limits how long the caller waits but does not necessarily cancel the underlying request. Use a client with explicit cancellation when needed, and keep the mutation idempotent even after cancellation. Check mounted before updating a widget after awaiting work. Stream large media from a file instead of buffering it into Dart memory.

React Native: do not confuse bridge state with durable state

This TypeScript example delegates database and scheduling operations to application adapters backed by native implementations.

// Queue one message independently of this component's lifetime. async function sendMessage(text: string): Promise<void> { // Reuse this identifier across retries and process restarts. const eventId = idGenerator.newId(); // Persist the message and its outbox entry as one transaction. await db.transaction(async () => { await messages.insertPending(eventId, text); await outbox.insert(eventId); }); // Ask the native platform to schedule work when constraints allow it. await nativeSync.requestEligibleWork(); } 

For a foreground fetch, connect an AbortController to screen ownership and clean it up on unmount. Aborting stops the local request where supported; it cannot undo a server operation that already committed. Do not place secrets in AsyncStorage or URL query strings; use platform-backed secure storage for credentials and send them over HTTPS.

Conflict, ordering, and the outbox

Offline writes introduce conflicts. Two devices can edit the same record before either syncs. Include a server revision or ETag and decide whether to merge fields, reject with a conflict screen, or apply a documented last-writer policy. A timestamp from an untrusted device clock is not automatically a safe ordering source.

Outbox ordering matters when operations depend on each other. Creating a message before editing it may require per-entity sequencing, while unrelated messages can upload concurrently. Bound concurrency, queue length, and payload size. A permanently invalid event should be surfaced or moved to a review state rather than blocking every later operation forever.

Battery, privacy, and large payloads

Batch nonurgent requests and avoid polling when a push hint plus foreground refresh is enough. Respect low-data and metered-network choices. Reuse connections and compress when the CPU/bandwidth trade-off is beneficial; Apple documents batching and URLSession policies for expensive and constrained networks. Apple networking power guidance.

Store only the minimum required payload locally, encrypt sensitive data according to the threat model, and keep credentials in Keychain or Keystore-backed storage. Never log authorization headers, message bodies, full URLs containing secrets, or raw media. For large uploads, use file-backed or streaming APIs and a resumable protocol where supported. Limit in-flight bytes and clean up temporary files after cancellation or acknowledgement.

Observability and failure tests

Measure outbox age, retry count by classified reason, request latency, timeout rate, bytes transferred, conflict rate, and successful server reconciliation. Provider acceptance is not the same as a user-visible outcome. Use an operation ID to correlate client and server logs without exposing personal content.

Test airplane mode, captive portal, DNS failure, TLS failure, expired credentials, network switching mid-upload, 429 with Retry-After, server commit followed by lost response, app kill before local acknowledgement, and logout with pending work. Include two-device conflicts and low-storage conditions. These cases expose the protocol boundaries that a happy-path emulator rarely exercises.

Senior interview takeaways

A strong design names the source of truth, explains local durability and server authority, distinguishes timeout from rollback, and makes retries safe across process death. It chooses a conflict policy, bounds resource use, respects OS background rules, and tests the lost-response case. Ask: what will the user see, what can be safely retried, and how will we know if work is stuck?

The network is a changing environment, not a boolean. Design around durable intent and explicit reconciliation, and the app can remain honest and useful when the connection is slow, absent, or uncertain.