skip to content

As an iOS lead, which URLSession instances should a transit app standardise on, and who owns their configurations, delegates and caches?

level: principalimportance: should knowfreq 32%

answer

  1. one owner, a few roles
  2. fail fast versus wait for a route
  3. delegates live until invalidation
  4. exactly one background identifier

basics

~20 s

Standardise on a few long-lived URLSession instances, each with a configuration set for a role (live data, ordinary API calls, media, background transfers, a private mode), created and owned by one networking module that also owns their caches and session delegates.

solid answer

~40 s

I would not let features build sessions ad hoc, and I would not push everything through `URLSession.shared`, which has no configuration or delegate to tune. Instead one networking module owns a handful of long-lived sessions by role: live departures with a short `timeoutIntervalForRequest` and no cache; ordinary API calls with `waitsForConnectivity` and a bounded `timeoutIntervalForResource`; media that skips Low Data Mode through `allowsConstrainedNetworkAccess`; exactly one background session with a fixed identifier; and an ephemeral session created and invalidated per private planner. That module owns the session delegates, so server-trust challenges and `URLSessionTaskMetrics` are handled once, sizes and clears each `URLCache`, and wipes them at sign-out. Features pass per-task delegates for progress. A small app may honestly need only the shared session plus one background session.

code

swift · 29 lines
swift
import Foundation

/// One owner for every URLSession the app keeps; features ask for a role, never build their own.
enum TransitSessions {
    /// Live departures and vehicle feeds: fail fast, never cache.
    static let live: URLSession = {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 10
        config.urlCache = nil
        config.requestCachePolicy = .reloadIgnoringLocalCacheData
        return URLSession(configuration: config)
    }()

    /// Ordinary API calls: wait out a dead zone instead of failing at once.
    static let api: URLSession = {
        let config = URLSessionConfiguration.default
        config.waitsForConnectivity = true
        config.timeoutIntervalForResource = 60
        config.urlCache = URLCache(memoryCapacity: 4 << 20, diskCapacity: 50 << 20, directory: nil)
        return URLSession(configuration: config)
    }()

    /// Images and map tiles: skip them on Low Data Mode.
    static let media: URLSession = {
        let config = URLSessionConfiguration.default
        config.allowsConstrainedNetworkAccess = false
        return URLSession(configuration: config)
    }()
}

go deeper

for a junior

Know that an app can have several URLSession instances with different configurations, and that URLSession.shared is the one you cannot configure.

for a middle

Explain which configuration properties differ between roles, such as timeouts, cache, waitsForConnectivity and Low Data Mode, and why sessions should be long-lived.

for a senior

Show how a central owner handles delegates, challenges and metrics once, avoids delegate leaks, and clears every cache and cookie store at sign-out.

for a principal

Argue the tradeoff between the shared session, a small set of owned roles and per-feature sessions, and name the concrete triggers that justify each step up.

## The decision Every iOS app ends up with some set of `URLSession` instances. Left alone, teams create them wherever they need one: a session per screen, a custom configuration copied from a forum, the shared session for everything else. The lead's call is how many sessions the app keeps, what each is for, and who owns their configuration, delegates and caches. There is no single right number; there are costs on both sides. ## Three ways teams standardise | Approach | Strength | Cost | |---|---|---| | `URLSession.shared` everywhere | zero setup | no delegate, no tunable configuration, every feature shares one cache and cookie store | | A few sessions by role, owned centrally | each role gets the right timeouts, cache and network rules | one module to maintain; features must ask for a role | | Sessions created by each feature | maximum local freedom | leaked delegates, inconsistent policies, duplicated caches, nobody can wipe state at sign-out | Apple's own guidance leans toward the middle row: create as few sessions as you need, store each as a long-lived property, and share one session among parts of the app that need the same configuration. ## Roles for a transit app Mapped onto URLSession's configuration properties, a city-transit app might standardise on: - **Live**: departures and vehicle feeds. A short `timeoutIntervalForRequest` (the default is 60 seconds), `urlCache = nil` or `.reloadIgnoringLocalCacheData`, and no `waitsForConnectivity`, so a dead zone fails fast and the screen shows its last known state. - **API**: ordinary account and trip calls. `waitsForConnectivity = true`, so a request made in a tunnel waits for a route instead of failing at once, with `timeoutIntervalForResource` lowered from its seven-day default so a waiting task does not hang for days. - **Media**: map tiles and images. `allowsConstrainedNetworkAccess = false` to respect Low Data Mode, and possibly `allowsExpensiveNetworkAccess = false` for prefetching, both iOS 13. - **Background**: exactly one session from `background(withIdentifier:)` with a fixed identifier, created at launch, for overnight timetable packs. Apple recommends one or very few, because the background rate limiter penalises repeated wake-ups. - **Private**: an ephemeral session created when the incognito planner opens and invalidated when it closes. These are configuration decisions, so they are made once. A session copies its configuration at creation, so a feature cannot quietly change a shared session's behaviour later; changing a role means building a new session. ## Who owns what 1. **Configurations.** The networking module creates every session; features request a role and never call `URLSession(configuration:)` themselves. Review rules can enforce that. 2. **Session delegates.** A session keeps its delegate strongly until invalidated, which is fine for app-lifetime sessions and a leak for per-screen ones. The owner implements the session-level callbacks once: authentication challenges, including the server-trust challenge, and `urlSession(_:task:didFinishCollectingMetrics:)` for `URLSessionTaskMetrics` (iOS 10), feeding one telemetry pipeline. What the trust evaluation should accept is a pinning design question covered with the system design material on transport trust. 3. **Per-task delegates.** Since iOS 15 the async methods take a `delegate:` argument and `URLSessionTask` has a `delegate` property, held until the task completes. Features use these for progress or a one-off challenge without owning a session. 4. **Caches and stores.** The owner sizes each `URLCache`, decides which roles cache at all, and at sign-out clears every cache with `removeAllCachedResponses()` along with the cookie and credential stores those sessions share. ## Where the boundaries sit - Interceptors, token refresh and retry policy are a request-pipeline design that sits above these sessions; that design is covered with the system design material on request pipelines. The session layer only supplies the configured transport. - A networking wrapper library, if the team adopts one, is still built on sessions like these, so the same ownership questions apply to whatever session it is given. ## When to stop at less A small app with a handful of GET requests can live on `URLSession.shared` plus one background session, and adding roles there is ceremony. The trigger for the fuller setup is concrete: a second set of timeouts, a private mode, a cache that must be cleared at sign-out, or metrics the team wants from every request.

  • A feature team wants waitsForConnectivity on the live departures session; what do you tell them?
    Waiting suits requests whose answer stays useful later, not a board that refreshes every few seconds. A waiting live request returns stale data minutes later, and its wait is bounded by `timeoutIntervalForResource`, seven days by default. The live role should fail fast with `URLError` `.notConnectedToInternet` and show its last known state.
  • When is URLSession.shared still the right choice in a larger app?
    For a simple GET from code that needs no delegate, no special timeouts and no isolation, for example fetching a static legal page. Once a call needs authentication handling, metrics, a private store or different network rules, it belongs on a role-specific session.

  • Every screen should create its own URLSession for isolation
  • URLSession.shared can be given a delegate to handle server trust
  • Several background sessions make background downloads run faster
  • waitsForConnectivity is the right default for every request
  • Changing a shared session's configuration object later updates every feature at once