<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by PRASHANT PANDEY on Medium]]></title>
        <description><![CDATA[Stories by PRASHANT PANDEY on Medium]]></description>
        <link>https://medium.com/@prashant5.manit?source=rss-5c79dc5fe4f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IjO4Ln8r0ZPaOJQg</url>
            <title>Stories by PRASHANT PANDEY on Medium</title>
            <link>https://medium.com/@prashant5.manit?source=rss-5c79dc5fe4f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:40:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prashant5.manit/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[System Design: Designing a
File Downloader
Library for iOS]]></title>
            <link>https://medium.com/@prashant5.manit/system-design-designing-a-file-downloader-library-for-ios-62f55aac7ff4?source=rss-5c79dc5fe4f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f55aac7ff4</guid>
            <category><![CDATA[urlsessions]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[file-io]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[PRASHANT PANDEY]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 09:03:29 GMT</pubDate>
            <atom:updated>2026-04-07T09:04:58.935Z</atom:updated>
            <content:encoded><![CDATA[<p>A deep-dive into building a production-grade, background-capable, concurrent file download library — from requirements gathering to real Swift classes and architecture diagrams.</p><p>Building a file downloader sounds deceptively simple. But designing one that handles background execution, pause/resume, concurrency limits, integrity verification, and crash recovery — while feeling like a polished public API — is a genuine system design challenge that separates senior iOS engineers from the rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OABeXjV0fJ2z7jTgReCDiQ.png" /></figure><h3>1. Gathering Requirements</h3><p>Before drawing any diagrams, a system design interview demands that you clarify the problem. The question is deliberately vague. Here’s how the conversation should go:</p><p>Interview tipAlways lead with functional requirements, then non-functional, then explicitly call out what’s out of scope. This shows structured thinking.</p><h3>Functional Requirements</h3><ul><li>Download any binary file from an HTTP(S) URL to local disk</li><li>Support pause, resume, and cancel on individual downloads</li><li>Support simultaneous concurrent downloads (with a configurable cap)</li><li>Provide progress callbacks during active downloads</li><li>Downloads must survive app termination and resume on next launch</li><li>Network constraint configuration: WiFi-only vs. allowing cellular</li><li>Optional checksum/integrity verification after download completes</li></ul><h3>Non-Functional Requirements</h3><h4>✅ Functional</h4><ul><li>Pause / Resume / Cancel</li><li>Progress reporting</li><li>Concurrent downloads</li><li>Persistence across crashes</li><li>Integrity checking (MD5/SHA)</li></ul><h4>⚙️ Non-Functional</h4><ul><li>Max parallel downloads: 4 (configurable)</li><li>No file size limit</li><li>Thread-safe internal state</li><li>Minimal battery impact</li><li>Clean, typesafe public API</li></ul><h3>Out of Scope</h3><ul><li>Authentication / OAuth</li><li>Resumable HTTP range requests (HTTP 206)</li><li>Upload tasks</li><li>Android implementation</li></ul><p>Why limit to 4 parallel downloads?Mobile network radios are expensive. Each TCP connection adds overhead. Too many parallel downloads saturate bandwidth, starve other app network calls (API requests, analytics), and drain the battery. 4 is a proven heuristic — 1 for cellular/low-battery, up to 4 for WiFi.</p><h3>2. Public API Design</h3><p>Designing the API <em>before</em> the internals forces you to think from the caller’s perspective. A clean, minimal API also constrains your implementation to what actually matters.</p><pre>Swift// ──── Entry Point ────────────────────────────────────────────<br>public final class FileDownloader {</pre><pre>    public static let shared = FileDownloader(config: .default)</pre><pre>    public init(config: FileDownloaderConfig)</pre><pre>    /// Enqueues a download. Returns immediately with a task handle.<br>    @discardableResult<br>    public func download(request: FileDownloadRequest) -&gt; FileDownloadTask</pre><pre>    public func pauseAll()<br>    public func resumeAll()<br>    public func cancelAll()</pre><pre>    public var activeTasks: [FileDownloadTask] { get }<br>}</pre><pre>// ──── Request ─────────────────────────────────────────────────<br>public struct FileDownloadRequest {<br>    public let sourceURL:   URL<br>    public let destination: URL       // full file path in sandbox<br>    public let constraints:  NetworkConstraints<br>    public let checksum:    Checksum?  // optional SHA-256 / MD5<br>}</pre><pre>// ──── Task Handle ─────────────────────────────────────────────<br>public final class FileDownloadTask {<br>    public let id: UUID<br>    public var state: DownloadState { get }<br>    public var progress: Double { get }   // 0.0 – 1.0</pre><pre>    public func pause()<br>    public func resume()<br>    public func cancel()</pre><pre>    /// Combine publisher for progress + state changes<br>    public var publisher: AnyPublisher&lt;DownloadEvent, Never&gt; { get }<br>}</pre><pre>// ──── Config ──────────────────────────────────────────────────<br>public struct FileDownloaderConfig {<br>    public var maxParallelDownloads:  Int    = 4<br>    public var sessionIdentifier:    String = &quot;com.app.FileDownloader.background&quot;<br>    public var isDiscretionary:      Bool   = false<br>    public var timeoutInterval:      TimeInterval = 60<br>    public static let `default` = FileDownloaderConfig()<br>}</pre><pre>// ──── Supporting Types ────────────────────────────────────────<br>public enum DownloadState: Codable {<br>    case queued, active, paused, completed, failed(Error), cancelled<br>}</pre><pre>public enum NetworkConstraints {<br>    case wifiOnly<br>    case wifiAndCellular<br>}</pre><pre>public struct Checksum {<br>    public enum Algorithm { case md5, sha256 }<br>    public let algorithm: Algorithm<br>    public let value:     String<br>}</pre><h3>3. High-Level Architecture</h3><p>The system has three conceptual layers. The Public API Layer is what developers interact with. The Coordination Layer manages state, queuing, and concurrency. The Transport Layer delegates to Apple’s URLSession background daemon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mZXYF-A3nrv794RJ8QfSw.png" /></figure><p>📦 <strong>FileDownloader (Entry Point)</strong></p><p>The single class developers interact with. Owns the URLSession, the queue, the task manager, and the persistence store. Implemented as a shared singleton but also supports custom instances for isolated download contexts (e.g. app extensions).</p><p>🗂️ <strong>DownloadQueue</strong></p><p>A priority-aware FIFO queue that gates active downloads against maxParallelDownloads. When a running task completes or is cancelled, the queue dequeues the next pending task and starts it automatically.</p><p>🗺️ <strong>TaskManager</strong></p><p>Maintains a bidirectional map between UUID (library task ID) and URLSessionTask.taskIdentifier. This is the bridge between the public API world and URLSession&#39;s integer-keyed delegate callbacks.</p><p>💾 Building a file downloader sounds deceptively simple. But designing one that handles background execution, pause/resume, concurrency limits, integrity verification, and crash recovery — while feeling like a polished public API — is a genuine system design challenge that separates senior iOS engineers from the rest.</p><h3>1. Gathering Requirements</h3><p>Before drawing any diagrams, a system design interview demands that you clarify the problem. The question is deliberately vague. Here’s how the conversation should go:</p><p>Interview tipAlways lead with functional requirements, then non-functional, then explicitly call out what’s out of scope. This shows structured thinking.</p><h3>Functional Requirements</h3><ul><li>Download any binary file from an HTTP(S) URL to local disk</li><li>Support pause, resume, and cancel on individual downloads</li><li>Support simultaneous concurrent downloads (with a configurable cap)</li><li>Provide progress callbacks during active downloads</li><li>Downloads must survive app termination and resume on next launch</li><li>Network constraint configuration: WiFi-only vs. allowing cellular</li><li>Optional checksum/integrity verification after download completes</li></ul><h3>Non-Functional Requirements</h3><h4>✅ Functional</h4><ul><li>Pause / Resume / Cancel</li><li>Progress reporting</li><li>Concurrent downloads</li><li>Persistence across crashes</li><li>Integrity checking (MD5/SHA)</li></ul><h4>⚙️ Non-Functional</h4><ul><li>Max parallel downloads: 4 (configurable)</li><li>No file size limit</li><li>Thread-safe internal state</li><li>Minimal battery impact</li><li>Clean, typesafe public API</li></ul><h3>Out of Scope</h3><ul><li>Authentication / OAuth</li><li>Resumable HTTP range requests (HTTP 206)</li><li>Upload tasks</li><li>Android implementation</li></ul><p>Why limit to 4 parallel downloads?Mobile network radios are expensive. Each TCP connection adds overhead. Too many parallel downloads saturate bandwidth, starve other app network calls (API requests, analytics), and drain the battery. 4 is a proven heuristic — 1 for cellular/low-battery, up to 4 for WiFi.</p><h3>2. Public API Design</h3><p>Designing the API <em>before</em> the internals forces you to think from the caller’s perspective. A clean, minimal API also constrains your implementation to what actually matters.</p><pre>Swift// ──── Entry Point ────────────────────────────────────────────<br>public final class FileDownloader {</pre><pre>    public static let shared = FileDownloader(config: .default)</pre><pre>    public init(config: FileDownloaderConfig)</pre><pre>    /// Enqueues a download. Returns immediately with a task handle.<br>    @discardableResult<br>    public func download(request: FileDownloadRequest) -&gt; FileDownloadTask</pre><pre>    public func pauseAll()<br>    public func resumeAll()<br>    public func cancelAll()</pre><pre>    public var activeTasks: [FileDownloadTask] { get }<br>}</pre><pre>// ──── Request ─────────────────────────────────────────────────<br>public struct FileDownloadRequest {<br>    public let sourceURL:   URL<br>    public let destination: URL       // full file path in sandbox<br>    public let constraints:  NetworkConstraints<br>    public let checksum:    Checksum?  // optional SHA-256 / MD5<br>}</pre><pre>// ──── Task Handle ─────────────────────────────────────────────<br>public final class FileDownloadTask {<br>    public let id: UUID<br>    public var state: DownloadState { get }<br>    public var progress: Double { get }   // 0.0 – 1.0</pre><pre>    public func pause()<br>    public func resume()<br>    public func cancel()</pre><pre>    /// Combine publisher for progress + state changes<br>    public var publisher: AnyPublisher&lt;DownloadEvent, Never&gt; { get }<br>}</pre><pre>// ──── Config ──────────────────────────────────────────────────<br>public struct FileDownloaderConfig {<br>    public var maxParallelDownloads:  Int    = 4<br>    public var sessionIdentifier:    String = &quot;com.app.FileDownloader.background&quot;<br>    public var isDiscretionary:      Bool   = false<br>    public var timeoutInterval:      TimeInterval = 60<br>    public static let `default` = FileDownloaderConfig()<br>}</pre><pre>// ──── Supporting Types ────────────────────────────────────────<br>public enum DownloadState: Codable {<br>    case queued, active, paused, completed, failed(Error), cancelled<br>}</pre><pre>public enum NetworkConstraints {<br>    case wifiOnly<br>    case wifiAndCellular<br>}</pre><pre>public struct Checksum {<br>    public enum Algorithm { case md5, sha256 }<br>    public let algorithm: Algorithm<br>    public let value:     String<br>}</pre><h3>3. High-Level Architecture</h3><p>The system has three conceptual layers. The Public API Layer is what developers interact with. The Coordination Layer manages state, queuing, and concurrency. The Transport Layer delegates to Apple’s URLSession background daemon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mZXYF-A3nrv794RJ8QfSw.png" /></figure><p>📦</p><h4>FileDownloader (Entry Point)</h4><p>The single class developers interact with. Owns the URLSession, the queue, the task manager, and the persistence store. Implemented as a shared singleton but also supports custom instances for isolated download contexts (e.g. app extensions).</p><p>🗂️</p><h4>DownloadQueue</h4><p>A priority-aware FIFO queue that gates active downloads against maxParallelDownloads. When a running task completes or is cancelled, the queue dequeues the next pending task and starts it automatically.</p><p>🗺️</p><h4>TaskManager</h4><p>Maintains a bidirectional map between UUID (library task ID) and URLSessionTask.taskIdentifier. This is the bridge between the public API world and URLSession&#39;s integer-keyed delegate callbacks.</p><p>💾</p><h4>PersistenceStore</h4><p>Serialises pending and in-progress tasks to disk on every state change. On app relaunch, reads persisted state and re-enqueues any non-terminal tasks. Uses SQLite (via GRDB or raw SQLite3) for robustness.</p><h3>4. Download State Machine</h3><p>Every FileDownloadTask is a finite state machine. Modelling this explicitly prevents impossible transitions and makes the code far easier to reason about.</p><p>idle queued active paused completed failed cancelled</p><p>Fig 2 — Download State Machine</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOO6wtWB8Td1iv3xpNcTIQ.png" /></figure><pre>Swift// Enforce valid transitions — crash fast on illegal ones in DEBUG<br>extension DownloadState {<br>    func canTransition(to next: DownloadState) -&gt; Bool {<br>        switch (self, next) {<br>        case (.queued,    .active):    return true<br>        case (.active,    .paused):    return true<br>        case (.active,    .completed): return true<br>        case (.active,    .failed):    return true<br>        case (.active,    .cancelled): return true<br>        case (.paused,    .queued):    return true   // resume()<br>        case (.paused,    .cancelled): return true<br>        case (.failed,    .queued):    return true   // retry<br>        default:                        return false<br>        }<br>    }<br>}</pre><h3>5. Core Implementation</h3><h3>5.1 DownloadManager — The Heart</h3><p>This is the actor-isolated internal engine. Using Swift’s actor model ensures all state mutations happen on a single serialised executor — no locks, no data races.</p><pre>Swiftactor DownloadManager: NSObject {<br>    private let config: FileDownloaderConfig<br>    private var urlSession: URLSession!<br>    private var taskRegistry: [UUID: FileDownloadTask] = [:]<br>    private var sessionTaskMap: [Int: UUID] = [:]  // taskIdentifier → UUID<br>    private var downloadQueue: DownloadQueue<br>    private let store: PersistenceStore</pre><pre>    init(config: FileDownloaderConfig, store: PersistenceStore) {<br>        self.config = config<br>        self.store  = store<br>        self.downloadQueue = DownloadQueue(maxConcurrent: config.maxParallelDownloads)<br>        super.init()</pre><pre>        let cfg = URLSessionConfiguration.background(<br>            withIdentifier: config.sessionIdentifier<br>        )<br>        cfg.isDiscretionary         = config.isDiscretionary<br>        cfg.sessionSendsLaunchEvents = true<br>        cfg.timeoutIntervalForRequest = config.timeoutInterval</pre><pre>        // IMPORTANT: URLSession must be created only ONCE per identifier.<br>        // Reconnecting returns the same session with the original delegate.<br>        self.urlSession = URLSession(<br>            configuration: cfg,<br>            delegate: self,<br>            delegateQueue: nil   // serial delegate queue managed internally<br>        )<br>    }</pre><pre>    func enqueue(_ request: FileDownloadRequest) -&gt; FileDownloadTask {<br>        let task = FileDownloadTask(request: request)<br>        taskRegistry[task.id] = task<br>        store.save(task)<br>        downloadQueue.enqueue(task)<br>        drainQueue()          // may start immediately if slot free<br>        return task<br>    }</pre><pre>    private func drainQueue() {<br>        while downloadQueue.hasCapacity, let next = downloadQueue.dequeueNext() {<br>            startURLSessionTask(for: next)<br>        }<br>    }</pre><pre>    private func startURLSessionTask(for task: FileDownloadTask) {<br>        let urlTask = urlSession.downloadTask(with: task.request.sourceURL)<br>        sessionTaskMap[urlTask.taskIdentifier] = task.id<br>        task.transition(to: .active)<br>        store.save(task)<br>        urlTask.resume()<br>    }</pre><pre>    func pause(_ id: UUID) {<br>        guard let task = taskRegistry[id], task.state == .active else { return }<br>        // cancelByProducingResumeData preserves partial download bytes<br>        urlSessionTask(for: id)?.cancel(byProducingResumeData: { [weak self] data in<br>            Task { await self?.handlePause(id: id, resumeData: data) }<br>        })<br>    }</pre><pre>    func resume(_ id: UUID) {<br>        guard let task = taskRegistry[id], task.state == .paused else { return }<br>        task.transition(to: .queued)<br>        downloadQueue.enqueue(task)<br>        drainQueue()<br>    }</pre><pre>    private func urlSessionTask(for id: UUID) -&gt; URLSessionTask? {<br>        guard let taskId = sessionTaskMap.first(where: { $0.value == id })?.key else { return nil }<br>        return urlSession.allTasks.first(where: { $0.taskIdentifier == taskId })   // sync access OK from actor<br>    }<br>}</pre><h3>5.2 URLSession Delegate Extension</h3><p>Because completion handler closures are not supported in background sessions, <em>all</em> notifications must flow through the delegate. Three delegate methods cover 95% of needs:</p><pre>Swiftextension DownloadManager: URLSessionDownloadDelegate {</pre><pre>    // ① Progress callback — fires continuously during download<br>    nonisolated func urlSession(<br>        _ session: URLSession,<br>        downloadTask: URLSessionDownloadTask,<br>        didWriteData bytesWritten: Int64,<br>        totalBytesWritten: Int64,<br>        totalBytesExpectedToWrite: Int64<br>    ) {<br>        let progress = totalBytesExpectedToWrite &gt; 0<br>            ? Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)<br>            : -1   // unknown content length<br>        Task {<br>            await updateProgress(<br>                sessionTaskId: downloadTask.taskIdentifier,<br>                progress: progress<br>            )<br>        }<br>    }</pre><pre>    // ② Download finished — file written to a TEMP location by the OS<br>    nonisolated func urlSession(<br>        _ session: URLSession,<br>        downloadTask: URLSessionDownloadTask,<br>        didFinishDownloadingTo location: URL<br>    ) {<br>        Task {<br>            await handleCompletion(<br>                sessionTaskId: downloadTask.taskIdentifier,<br>                tempURL: location<br>            )<br>        }<br>    }</pre><pre>    // ③ Task ended — success or failure<br>    nonisolated func urlSession(<br>        _ session: URLSession,<br>        task: URLSessionTask,<br>        didCompleteWithError error: Error?<br>    ) {<br>        guard let error else { return }   // success handled in didFinishDownloadingTo<br>        Task { await handleError(sessionTaskId: task.taskIdentifier, error: error) }<br>    }</pre><pre>    // ④ App relaunch after background download completes<br>    nonisolated func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {<br>        Task { @MainActor in<br>            guard let handler = AppDelegate.shared.backgroundCompletionHandler else { return }<br>            AppDelegate.shared.backgroundCompletionHandler = nil<br>            handler()   // MUST call on main thread to notify system<br>        }<br>    }<br>}</pre><h3>5.3 Handling Completion — File Move + Integrity Check</h3><pre>Swiftprivate func handleCompletion(sessionTaskId: Int, tempURL: URL) async {<br>    guard let taskId  = sessionTaskMap[sessionTaskId],<br>          let task   = taskRegistry[taskId]<br>    else { return }</pre><pre>    let dest = task.request.destination</pre><pre>    do {<br>        // 1. Move from OS-managed temp → destination (atomic on same volume)<br>        try FileManager.default.moveItem(at: tempURL, to: dest)</pre><pre>        // 2. Verify checksum (off the actor to keep it non-blocking)<br>        if let checksum = task.request.checksum {<br>            let ok = await Task.detached(priority: .utility) {<br>                ChecksumVerifier.verify(file: dest, against: checksum)<br>            }.value<br>            guard ok else { throw DownloadError.checksumMismatch }<br>        }</pre><pre>        // 3. Transition state and notify subscribers<br>        task.transition(to: .completed)</pre><pre>    } catch {<br>        handleError(sessionTaskId: sessionTaskId, error: error)<br>        return<br>    }</pre><pre>    store.save(task)<br>    sessionTaskMap.removeValue(forKey: sessionTaskId)<br>    downloadQueue.taskCompleted()<br>    drainQueue()              // immediately start next queued download<br>}</pre><h3>5.4 PersistenceStore</h3><p>The store serialises every task into SQLite. On every state change, the task is re-written. On app launch, all non-terminal tasks are restored and re-enqueued.</p><pre>Swiftfinal class PersistenceStore {<br>    private let db: DatabaseQueue   // GRDB wrapper (or raw SQLite3)</pre><pre>    struct TaskRecord: Codable, FetchableRecord, PersistableRecord {<br>        var id:          UUID<br>        var sourceURL:   String<br>        var destination: String<br>        var state:       String   // raw value of DownloadState<br>        var resumeData:  Data?<br>        var checksum:    String?<br>    }</pre><pre>    func save(_ task: FileDownloadTask) {<br>        try? db.write { db in<br>            var record = TaskRecord(from: task)<br>            try record.upsert(db)<br>        }<br>    }</pre><pre>    /// Called on launch — return all tasks not in terminal state<br>    func restorePendingTasks() -&gt; [FileDownloadTask] {<br>        (try? db.read { db in<br>            try TaskRecord.filter(Column(&quot;state&quot;) != &quot;completed&quot;<br>                                 &amp;&amp; Column(&quot;state&quot;) != &quot;cancelled&quot;)<br>                           .fetchAll(db)<br>        }) ?? []<br>    }<br>}</pre><h3>6. AppDelegate Integration</h3><p>When a background download completes while the app is <em>not running</em>, iOS relaunches the app in background mode and calls one specific AppDelegate method. Failing to call the system completion handler leaks resources and can affect future background launches.</p><pre>Swift@UIApplicationMain<br>class AppDelegate: UIResponder, UIApplicationDelegate {</pre><pre>    /// Store the system-provided handler — call it AFTER all events are processed<br>    var backgroundCompletionHandler: (() -&gt; Void)?</pre><pre>    func application(<br>        _ application: UIApplication,<br>        handleEventsForBackgroundURLSession identifier: String,<br>        completionHandler: @escaping () -&gt; Void<br>    ) {<br>        // 1. Store the handler<br>        backgroundCompletionHandler = completionHandler</pre><pre>        // 2. Reconnect URLSession with the SAME identifier<br>        //    This triggers replaying of all pending delegate events<br>        FileDownloader.shared.reconnectSession(identifier: identifier)</pre><pre>        // 3. The handler is called inside urlSessionDidFinishEvents(forBackgroundURLSession:)<br>        //    once ALL pending events have been delivered — do NOT call it here.<br>    }<br>}</pre><h3>7. End-to-End Download Lifecycle</h3><p>Fig 3 — Full Download Lifecycle (including background relaunch)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdJ7x951HNiESrCi2Sng4A.png" /></figure><h3>8. Choosing the Right URLSession Configuration</h3><p>ConfigurationBackground capableCompletion blocksUse case.default❌ Stops when app suspends✅ YesShort, foreground-only transfers.ephemeral❌ No disk cache, no background✅ YesPrivate/incognito transfers.background(id:)✅ Survives suspension &amp; kill❌ Delegate onlyFile downloads — this library ✓</p><p>⚠️ Critical: One session per identifierCreating a second URLSession with the same background identifier does not create a new session — it returns the original object with its <em>old</em> delegate attached. Creating the session in init and caching it as a singleton is mandatory.</p><h3>9. Concurrency — Thread Safety</h3><p>The entire internal state (task registry, session task map, queue) lives inside a Swift actor. This provides compile-time data-race safety via Swift 6 strict concurrency checking. The URLSession delegate methods are nonisolated (they run on URLSession&#39;s private serial queue) and hop back to the actor via Task { await ... }.</p><pre>Swift// DownloadQueue — manages active slot counting<br>final class DownloadQueue {<br>    private let maxConcurrent: Int<br>    private var pending: [FileDownloadTask] = []<br>    private var activeCount = 0</pre><pre>    var hasCapacity: Bool { activeCount &lt; maxConcurrent }</pre><pre>    func enqueue(_ task: FileDownloadTask) {<br>        pending.append(task)<br>    }</pre><pre>    func dequeueNext() -&gt; FileDownloadTask? {<br>        guard !pending.isEmpty else { return nil }<br>        activeCount += 1<br>        return pending.removeFirst()<br>    }</pre><pre>    func taskCompleted() {<br>        activeCount = max(0, activeCount - 1)<br>    }<br>}</pre><h3>10. Network Constraints &amp; Power Management</h3><pre>Swiftextension URLSessionConfiguration {<br>    func apply(_ constraints: NetworkConstraints) {<br>        switch constraints {<br>        case .wifiOnly:<br>            allowsCellularAccess = false<br>            allowsConstrainedNetworkAccess = false   // Low Data Mode<br>        case .wifiAndCellular:<br>            allowsCellularAccess = true<br>        }<br>    }<br>}</pre><pre>// Adaptive concurrency — reduce parallel downloads on cellular / low battery<br>func adaptiveMaxDownloads(config: FileDownloaderConfig) -&gt; Int {<br>    let isLowBattery  = ProcessInfo.processInfo.isLowPowerModeEnabled<br>    let isCellular    = NWPathMonitor().currentPath.isExpensive<br>    if isLowBattery || isCellular { return 1 }<br>    return config.maxParallelDownloads   // default: 4<br>}</pre><h3>11. iOS File System Sandbox</h3><p>Where you store the downloaded file matters for iCloud sync, backup, eviction, and user visibility.</p><p>DirectoryBacked upOS can purgeBest forDocuments/✅ Yes❌ NoUser-visible, permanent filesLibrary/Caches/❌ No✅ Yes (disk pressure)Re-downloadable assetsLibrary/Application Support/✅ Yes❌ NoApp data, not user-facingtmp/❌ No✅ Yes (on reboot)In-progress download temp files</p><p>Rule of thumbThe OS writes the in-progress download to tmp/ automatically. When didFinishDownloadingTo fires, move the file to Library/Caches/ (re-downloadable) or Documents/ (permanent). Do it synchronously inside the delegate — the temp file is deleted as soon as the method returns.</p><h3>12. Edge Cases &amp; Failure Handling</h3><ul><li>Force-quit by user — iOS cancels all background tasks. There is no recovery from this. Design your queue to be re-created on next launch from persisted state.</li><li>App suspension (not force-quit) — Downloads continue via nsurlsessiond. When the app returns to foreground, delegate events replay.</li><li>Lost Wi-Fi mid-download — URLSession retries automatically within the allowed period. After timeout, didCompleteWithError fires with NSURLErrorNetworkConnectionLost. Store resume data for manual restart.</li><li>Server doesn’t support range requests (HTTP 206) — Cannot resume; must restart from byte 0. Detect via Accept-Ranges response header upfront.</li><li>Duplicate download requests — Deduplicate by source URL in enqueue. Return the existing task handle.</li><li>Disk full — didCompleteWithError with NSURLErrorCannotWriteToFile. Surface a meaningful error to the caller, do not retry automatically.</li></ul><h3>13. What Interviewers Are Actually Looking For</h3><h4>🎯 Must-haves</h4><ul><li>Background session + daemon explained</li><li>Delegate vs completion handler distinction</li><li>State machine for task lifecycle</li><li>Concurrency cap reasoning</li><li>Persistence across crashes</li></ul><h4>🌟 Differentiators</h4><ul><li>Swift actor for thread safety</li><li>Combine publisher on task</li><li>Checksum integrity layer</li><li>Adaptive concurrency (cellular / low-power)</li><li>App Extension isolation via unique session IDs</li></ul><p>◆ ◆ ◆</p><h3>Putting It All Together</h3><p>A production-grade iOS file downloader isn’t just a wrapper around URLSessionDownloadTask. It&#39;s a system with at least five distinct responsibilities: public API design, concurrency management, state machine enforcement, crash-resilient persistence, and background execution via the OS daemon.</p><p>The hardest parts in a FAANG interview are usually the ones that look obvious until you dig in: Why can’t you use completion blocks in background sessions? What happens if two app processes share the same session identifier? Why does the system completion handler need to be called on the main thread?</p><p>If you can answer those fluently — backed by the architecture above — you’ve demonstrated the depth that separates a senior iOS engineer from a solid mid-level one.</p><p>Topics covered: URLSession · URLSessionDownloadDelegate · Swift Actors · State Machines · nsurlsessiond daemon · Background execution · Persistence · Checksum verification · iOS System Design</p><p>Serialises pending and in-progress tasks to disk on every state change. On app relaunch, reads persisted state and re-enqueues any non-terminal tasks. Uses SQLite (via GRDB or raw SQLite3) for robustness.</p><h3>4. Download State Machine</h3><p>Every FileDownloadTask is a finite state machine. Modelling this explicitly prevents impossible transitions and makes the code far easier to reason about.</p><p>idle queued active paused completed failed cancelled</p><p>Fig 2 — Download State Machine</p><p>queuedactivepausedcompletedfailedcancelledretryslot freedidFinishdidComplete(error)pause()resume()cancel()autore-enqueue</p><pre>Swift// Enforce valid transitions — crash fast on illegal ones in DEBUG<br>extension DownloadState {<br>    func canTransition(to next: DownloadState) -&gt; Bool {<br>        switch (self, next) {<br>        case (.queued,    .active):    return true<br>        case (.active,    .paused):    return true<br>        case (.active,    .completed): return true<br>        case (.active,    .failed):    return true<br>        case (.active,    .cancelled): return true<br>        case (.paused,    .queued):    return true   // resume()<br>        case (.paused,    .cancelled): return true<br>        case (.failed,    .queued):    return true   // retry<br>        default:                        return false<br>        }<br>    }<br>}</pre><h3>5. Core Implementation</h3><h3>5.1 DownloadManager — The Heart</h3><p>This is the actor-isolated internal engine. Using Swift’s actor model ensures all state mutations happen on a single serialised executor — no locks, no data races.</p><pre>Swiftactor DownloadManager: NSObject {<br>    private let config: FileDownloaderConfig<br>    private var urlSession: URLSession!<br>    private var taskRegistry: [UUID: FileDownloadTask] = [:]<br>    private var sessionTaskMap: [Int: UUID] = [:]  // taskIdentifier → UUID<br>    private var downloadQueue: DownloadQueue<br>    private let store: PersistenceStore</pre><pre>    init(config: FileDownloaderConfig, store: PersistenceStore) {<br>        self.config = config<br>        self.store  = store<br>        self.downloadQueue = DownloadQueue(maxConcurrent: config.maxParallelDownloads)<br>        super.init()</pre><pre>        let cfg = URLSessionConfiguration.background(<br>            withIdentifier: config.sessionIdentifier<br>        )<br>        cfg.isDiscretionary         = config.isDiscretionary<br>        cfg.sessionSendsLaunchEvents = true<br>        cfg.timeoutIntervalForRequest = config.timeoutInterval</pre><pre>        // IMPORTANT: URLSession must be created only ONCE per identifier.<br>        // Reconnecting returns the same session with the original delegate.<br>        self.urlSession = URLSession(<br>            configuration: cfg,<br>            delegate: self,<br>            delegateQueue: nil   // serial delegate queue managed internally<br>        )<br>    }</pre><pre>    func enqueue(_ request: FileDownloadRequest) -&gt; FileDownloadTask {<br>        let task = FileDownloadTask(request: request)<br>        taskRegistry[task.id] = task<br>        store.save(task)<br>        downloadQueue.enqueue(task)<br>        drainQueue()          // may start immediately if slot free<br>        return task<br>    }</pre><pre>    private func drainQueue() {<br>        while downloadQueue.hasCapacity, let next = downloadQueue.dequeueNext() {<br>            startURLSessionTask(for: next)<br>        }<br>    }</pre><pre>    private func startURLSessionTask(for task: FileDownloadTask) {<br>        let urlTask = urlSession.downloadTask(with: task.request.sourceURL)<br>        sessionTaskMap[urlTask.taskIdentifier] = task.id<br>        task.transition(to: .active)<br>        store.save(task)<br>        urlTask.resume()<br>    }</pre><pre>    func pause(_ id: UUID) {<br>        guard let task = taskRegistry[id], task.state == .active else { return }<br>        // cancelByProducingResumeData preserves partial download bytes<br>        urlSessionTask(for: id)?.cancel(byProducingResumeData: { [weak self] data in<br>            Task { await self?.handlePause(id: id, resumeData: data) }<br>        })<br>    }</pre><pre>    func resume(_ id: UUID) {<br>        guard let task = taskRegistry[id], task.state == .paused else { return }<br>        task.transition(to: .queued)<br>        downloadQueue.enqueue(task)<br>        drainQueue()<br>    }</pre><pre>    private func urlSessionTask(for id: UUID) -&gt; URLSessionTask? {<br>        guard let taskId = sessionTaskMap.first(where: { $0.value == id })?.key else { return nil }<br>        return urlSession.allTasks.first(where: { $0.taskIdentifier == taskId })   // sync access OK from actor<br>    }<br>}</pre><h3>5.2 URLSession Delegate Extension</h3><p>Because completion handler closures are not supported in background sessions, <em>all</em> notifications must flow through the delegate. Three delegate methods cover 95% of needs:</p><pre>Swiftextension DownloadManager: URLSessionDownloadDelegate {</pre><pre>    // ① Progress callback — fires continuously during download<br>    nonisolated func urlSession(<br>        _ session: URLSession,<br>        downloadTask: URLSessionDownloadTask,<br>        didWriteData bytesWritten: Int64,<br>        totalBytesWritten: Int64,<br>        totalBytesExpectedToWrite: Int64<br>    ) {<br>        let progress = totalBytesExpectedToWrite &gt; 0<br>            ? Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)<br>            : -1   // unknown content length<br>        Task {<br>            await updateProgress(<br>                sessionTaskId: downloadTask.taskIdentifier,<br>                progress: progress<br>            )<br>        }<br>    }</pre><pre>    // ② Download finished — file written to a TEMP location by the OS<br>    nonisolated func urlSession(<br>        _ session: URLSession,<br>        downloadTask: URLSessionDownloadTask,<br>        didFinishDownloadingTo location: URL<br>    ) {<br>        Task {<br>            await handleCompletion(<br>                sessionTaskId: downloadTask.taskIdentifier,<br>                tempURL: location<br>            )<br>        }<br>    }</pre><pre>    // ③ Task ended — success or failure<br>    nonisolated func urlSession(<br>        _ session: URLSession,<br>        task: URLSessionTask,<br>        didCompleteWithError error: Error?<br>    ) {<br>        guard let error else { return }   // success handled in didFinishDownloadingTo<br>        Task { await handleError(sessionTaskId: task.taskIdentifier, error: error) }<br>    }</pre><pre>    // ④ App relaunch after background download completes<br>    nonisolated func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {<br>        Task { @MainActor in<br>            guard let handler = AppDelegate.shared.backgroundCompletionHandler else { return }<br>            AppDelegate.shared.backgroundCompletionHandler = nil<br>            handler()   // MUST call on main thread to notify system<br>        }<br>    }<br>}</pre><h3>5.3 Handling Completion — File Move + Integrity Check</h3><pre>Swiftprivate func handleCompletion(sessionTaskId: Int, tempURL: URL) async {<br>    guard let taskId  = sessionTaskMap[sessionTaskId],<br>          let task   = taskRegistry[taskId]<br>    else { return }</pre><pre>    let dest = task.request.destination</pre><pre>    do {<br>        // 1. Move from OS-managed temp → destination (atomic on same volume)<br>        try FileManager.default.moveItem(at: tempURL, to: dest)</pre><pre>        // 2. Verify checksum (off the actor to keep it non-blocking)<br>        if let checksum = task.request.checksum {<br>            let ok = await Task.detached(priority: .utility) {<br>                ChecksumVerifier.verify(file: dest, against: checksum)<br>            }.value<br>            guard ok else { throw DownloadError.checksumMismatch }<br>        }</pre><pre>        // 3. Transition state and notify subscribers<br>        task.transition(to: .completed)</pre><pre>    } catch {<br>        handleError(sessionTaskId: sessionTaskId, error: error)<br>        return<br>    }</pre><pre>    store.save(task)<br>    sessionTaskMap.removeValue(forKey: sessionTaskId)<br>    downloadQueue.taskCompleted()<br>    drainQueue()              // immediately start next queued download<br>}</pre><h3>5.4 PersistenceStore</h3><p>The store serialises every task into SQLite. On every state change, the task is re-written. On app launch, all non-terminal tasks are restored and re-enqueued.</p><pre>Swiftfinal class PersistenceStore {<br>    private let db: DatabaseQueue   // GRDB wrapper (or raw SQLite3)</pre><pre>    struct TaskRecord: Codable, FetchableRecord, PersistableRecord {<br>        var id:          UUID<br>        var sourceURL:   String<br>        var destination: String<br>        var state:       String   // raw value of DownloadState<br>        var resumeData:  Data?<br>        var checksum:    String?<br>    }</pre><pre>    func save(_ task: FileDownloadTask) {<br>        try? db.write { db in<br>            var record = TaskRecord(from: task)<br>            try record.upsert(db)<br>        }<br>    }</pre><pre>    /// Called on launch — return all tasks not in terminal state<br>    func restorePendingTasks() -&gt; [FileDownloadTask] {<br>        (try? db.read { db in<br>            try TaskRecord.filter(Column(&quot;state&quot;) != &quot;completed&quot;<br>                                 &amp;&amp; Column(&quot;state&quot;) != &quot;cancelled&quot;)<br>                           .fetchAll(db)<br>        }) ?? []<br>    }<br>}</pre><h3>6. AppDelegate Integration</h3><p>When a background download completes while the app is <em>not running</em>, iOS relaunches the app in background mode and calls one specific AppDelegate method. Failing to call the system completion handler leaks resources and can affect future background launches.</p><pre>Swift@UIApplicationMain<br>class AppDelegate: UIResponder, UIApplicationDelegate {</pre><pre>    /// Store the system-provided handler — call it AFTER all events are processed<br>    var backgroundCompletionHandler: (() -&gt; Void)?</pre><pre>    func application(<br>        _ application: UIApplication,<br>        handleEventsForBackgroundURLSession identifier: String,<br>        completionHandler: @escaping () -&gt; Void<br>    ) {<br>        // 1. Store the handler<br>        backgroundCompletionHandler = completionHandler</pre><pre>        // 2. Reconnect URLSession with the SAME identifier<br>        //    This triggers replaying of all pending delegate events<br>        FileDownloader.shared.reconnectSession(identifier: identifier)</pre><pre>        // 3. The handler is called inside urlSessionDidFinishEvents(forBackgroundURLSession:)<br>        //    once ALL pending events have been delivered — do NOT call it here.<br>    }<br>}</pre><h3>7. End-to-End Download Lifecycle</h3><p>Fig 3 — Full Download Lifecycle (including background relaunch)</p><p>App calls download(request:)Task added to DownloadQueueActive slotavailable?YesNoWait inqueueCreate URLSessionDownloadTasknsurlsessiond daemon downloads(even if app is suspended or killed)didWriteData → progress eventDownloaddone?YesNoMove temp → destinationVerify checksum (if configured)ChecksumOK?YesNoState →failedState → completed ✓drainQueue() → start next task</p><h3>8. Choosing the Right URLSession Configuration</h3><p>ConfigurationBackground capableCompletion blocksUse case.default❌ Stops when app suspends✅ YesShort, foreground-only transfers.ephemeral❌ No disk cache, no background✅ YesPrivate/incognito transfers.background(id:)✅ Survives suspension &amp; kill❌ Delegate onlyFile downloads — this library ✓</p><p>⚠️ Critical: One session per identifierCreating a second URLSession with the same background identifier does not create a new session — it returns the original object with its <em>old</em> delegate attached. Creating the session in init and caching it as a singleton is mandatory.</p><h3>9. Concurrency — Thread Safety</h3><p>The entire internal state (task registry, session task map, queue) lives inside a Swift actor. This provides compile-time data-race safety via Swift 6 strict concurrency checking. The URLSession delegate methods are nonisolated (they run on URLSession&#39;s private serial queue) and hop back to the actor via Task { await ... }.</p><pre>Swift// DownloadQueue — manages active slot counting<br>final class DownloadQueue {<br>    private let maxConcurrent: Int<br>    private var pending: [FileDownloadTask] = []<br>    private var activeCount = 0</pre><pre>    var hasCapacity: Bool { activeCount &lt; maxConcurrent }</pre><pre>    func enqueue(_ task: FileDownloadTask) {<br>        pending.append(task)<br>    }</pre><pre>    func dequeueNext() -&gt; FileDownloadTask? {<br>        guard !pending.isEmpty else { return nil }<br>        activeCount += 1<br>        return pending.removeFirst()<br>    }</pre><pre>    func taskCompleted() {<br>        activeCount = max(0, activeCount - 1)<br>    }<br>}</pre><h3>10. Network Constraints &amp; Power Management</h3><pre>Swiftextension URLSessionConfiguration {<br>    func apply(_ constraints: NetworkConstraints) {<br>        switch constraints {<br>        case .wifiOnly:<br>            allowsCellularAccess = false<br>            allowsConstrainedNetworkAccess = false   // Low Data Mode<br>        case .wifiAndCellular:<br>            allowsCellularAccess = true<br>        }<br>    }<br>}</pre><pre>// Adaptive concurrency — reduce parallel downloads on cellular / low battery<br>func adaptiveMaxDownloads(config: FileDownloaderConfig) -&gt; Int {<br>    let isLowBattery  = ProcessInfo.processInfo.isLowPowerModeEnabled<br>    let isCellular    = NWPathMonitor().currentPath.isExpensive<br>    if isLowBattery || isCellular { return 1 }<br>    return config.maxParallelDownloads   // default: 4<br>}</pre><h3>11. iOS File System Sandbox</h3><p>Where you store the downloaded file matters for iCloud sync, backup, eviction, and user visibility.</p><p>DirectoryBacked upOS can purgeBest forDocuments/✅ Yes❌ NoUser-visible, permanent filesLibrary/Caches/❌ No✅ Yes (disk pressure)Re-downloadable assetsLibrary/Application Support/✅ Yes❌ NoApp data, not user-facingtmp/❌ No✅ Yes (on reboot)In-progress download temp files</p><p>Rule of thumbThe OS writes the in-progress download to tmp/ automatically. When didFinishDownloadingTo fires, move the file to Library/Caches/ (re-downloadable) or Documents/ (permanent). Do it synchronously inside the delegate — the temp file is deleted as soon as the method returns.</p><h3>12. Edge Cases &amp; Failure Handling</h3><ul><li>Force-quit by user — iOS cancels all background tasks. There is no recovery from this. Design your queue to be re-created on next launch from persisted state.</li><li>App suspension (not force-quit) — Downloads continue via nsurlsessiond. When the app returns to foreground, delegate events replay.</li><li>Lost Wi-Fi mid-download — URLSession retries automatically within the allowed period. After timeout, didCompleteWithError fires with NSURLErrorNetworkConnectionLost. Store resume data for manual restart.</li><li>Server doesn’t support range requests (HTTP 206) — Cannot resume; must restart from byte 0. Detect via Accept-Ranges response header upfront.</li><li>Duplicate download requests — Deduplicate by source URL in enqueue. Return the existing task handle.</li><li>Disk full — didCompleteWithError with NSURLErrorCannotWriteToFile. Surface a meaningful error to the caller, do not retry automatically.</li></ul><h3>13. What Interviewers Are Actually Looking For</h3><h4>🎯 Must-haves</h4><ul><li>Background session + daemon explained</li><li>Delegate vs completion handler distinction</li><li>State machine for task lifecycle</li><li>Concurrency cap reasoning</li><li>Persistence across crashes</li></ul><h4>🌟 Differentiators</h4><ul><li>Swift actor for thread safety</li><li>Combine publisher on task</li><li>Checksum integrity layer</li><li>Adaptive concurrency (cellular / low-power)</li><li>App Extension isolation via unique session IDs</li></ul><p>◆ ◆ ◆</p><h3>Putting It All Together</h3><p>A production-grade iOS file downloader isn’t just a wrapper around URLSessionDownloadTask. It&#39;s a system with at least five distinct responsibilities: public API design, concurrency management, state machine enforcement, crash-resilient persistence, and background execution via the OS daemon.</p><p>The hardest parts in a FAANG interview are usually the ones that look obvious until you dig in: Why can’t you use completion blocks in background sessions? What happens if two app processes share the same session identifier? Why does the system completion handler need to be called on the main thread?</p><p>If you can answer those fluently — backed by the architecture above — you’ve demonstrated the depth that separates a senior iOS engineer from a solid mid-level one.</p><p>Topics covered: URLSession · URLSessionDownloadDelegate · Swift Actors · State Machines · nsurlsessiond daemon · Background execution · Persistence · Checksum verification · iOS System Design</p><p>Resources :</p><p>1- <a href="https://github.com/weeeBox/mobile-system-design/tree/master">https://github.com/weeeBox/mobile-system-design/tree/master</a></p><p>2- <a href="https://youtu.be/t1ulqa7oAKg?list=PLTEPl9qIyDfmBzIL375dS8Tjb_KfiroaF">https://youtu.be/t1ulqa7oAKg?list=PLTEPl9qIyDfmBzIL375dS8Tjb_KfiroaF</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f55aac7ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>