Navigation
  • Home
  • Work
  • About
  • Writing
  • Contact
Socials
LinkedInGitHubEmailResume
Writing
Code by AsjadAsjad Anwar
  • Work
  • About
  • Writing
  • Contact
28 October 2026 · 7 min read

Uploads that survive a crash

I built a clinical dictation app for iOS on my own. A clinician records a note, taps Stop, and puts the phone in a pocket. A 30-minute part is about 35 MB of FLAC. With the audio session ended, iOS suspends the app within seconds.

The first uploader I wrote was correct while the app was running, which is the case that almost never happens. It sent blocks four at a time and awaited each batch. Suspended, every batch needed the system to relaunch the app, and iOS rate-limits those relaunches. A 35 MB file at 4 MiB per block is 9 blocks, so at least three relaunches for one recording.

This is how the second version works. The storage target is Azure block blobs, written with three hand-rolled REST calls, but the design applies to any chunked upload.

The rules first

I wrote the invariants down first and reviewed every change against them:

  • Local audio is deleted only by the user's typed confirmation, or by purging a recording the server has confirmed. Never on an error, a 404, a sign-out or a different user signing in.
  • A recording is "confirmed" only on the server's word.
  • Nothing that could succeed later has a retry cap. A definitive refusal goes to a loud "needs attention" state the user can retry.
  • The file system is the only database. Every state change is an atomic file rewrite, and a relaunch recovers from the directory alone.
  • A recording is uploaded only with the token of the account that made it.

Hand the whole file to the background session

A background URLSession only uploads from files, so each block is sliced to its own small file and enqueued. The change that mattered was enqueuing every missing block at once, up to 48 per round, and letting the system run four at a time.

let config = URLSessionConfiguration.background(withIdentifier: sessionID)
config.isDiscretionary = false
config.sessionSendsLaunchEvents = true
config.httpMaximumConnectionsPerHost = 4
config.timeoutIntervalForResource = 15 * 60

Now the system drains the file while the app is suspended and wakes it once, at the end, to commit. The disk cost is at most one file's size again.

The resource timeout is deliberate. By default a background task can wait days for a usable network and hold the queue behind it. After 15 minutes mine fails, and my own backoff (5 s up to hourly, with no cap) and a network path monitor take over.

A ledger of blocks

The ledger is a JSON file keyed by block index. Each entry holds the MD5 and length of the bytes sent, and whether storage accepted them.

struct BlockLedger: Codable {
    struct Entry: Codable {
        var md5: String
        var length: Int64
        var sent: Bool
    }
    var blocks: [String: Entry] = [:]

    func isSent(_ index: Int, md5: String) -> Bool {
        guard let entry = blocks[String(index)] else { return false }
        return entry.sent && entry.md5 == md5
    }
}

An entry is written as pending before the upload starts and marked sent after a success. Ledger writes throw, and a round that makes no progress stops and backs off instead of re-sending forever.

Before committing, I hash the sealed file block by block. A block counts as uploaded only if the ledger says it was sent with that MD5 and the server's block list shows that id with the expected length. Anything else is re-sent.

The content check is what makes streaming possible. While recording, the app sends finished 1 MiB blocks (about 55 seconds of audio each) that end at least 64 KiB behind the current end of file. Block 0 is held back until the file is sealed, because the encoder rewrites the header on close. If any other bytes move, the post-seal hash catches it and that block goes again. A recording keeps one block size for life, because block id i must always cover the same byte range.

Adopting tasks from a previous launch

When the app is relaunched, the background session may still hold tasks created by a process that no longer exists. My first version cancelled them, which with whole-file handover throws away a nearly finished upload.

Now each task carries a description of the form <recording id>/<block index>/<md5>. That is enough for a fresh process, with nothing in memory, to update the right ledger entry.

func urlSession(_ session: URLSession, task: URLSessionTask,
                didCompleteWithError error: Error?) {
    if let waiter = takeWaiter(for: task) {      // created by this process
        waiter.resume(with: outcome(of: task, error))
    } else if error == nil, succeeded(task),
              let label = BlockLabel(task.taskDescription) {
        // started by an earlier process: record it, if the ledger still agrees
        try? store.markSent(label.recordingID, index: label.index, md5: label.md5)
    }
}

Two details came out of review. The ledger only marks a block sent if its entry still has the same MD5, so an old completion cannot vouch for bytes that were since replaced. And a task counts as "ours" only if both its identifier and its label match, because task identifiers can be reused across processes.

Before re-sending anything for a recording, the coordinator waits for adopted tasks to settle, up to 60 seconds, then cancels them. If any is still running after that, the file is skipped for now. A late, older copy of a block must not land after its replacement.

When the last block wakes the app, the app delegate receives the session's completion handler. I take a background-time assertion, give commit and the server's complete call up to 20 seconds, then call the handler. If time runs out after commit, the state file says committed, and the next run only calls complete.

Crash and force-quit

On launch, and on background wakes with no UI, any recording still marked as recording that is not the live one is sealed as-is, flagged as recovered, and queued. Nothing is deleted.

One bug here predated the upload work. Recovery discarded an empty later part based on duration, but an unfinalised FLAC can report a length of zero while holding minutes of audio. The check is now on bytes: 16 KiB or less and under a second.

A force-quit is different: background transfers stop until the user opens the app again. Two hours after a recording is sealed, a local notification says it has not been uploaded, and it is cancelled on confirmation. It carries the dictation number and no patient name, because it shows on the lock screen.

An outbox for events

The server keeps a trail per recording: sealed, uploading, upload failed, recovered from crash, needs attention, file missing. The first version sent these fire-and-forget, so events raised offline were lost.

Now each transition appends to an events file beside the state, capped at 50 with the oldest dropped. After a successful backend call the queue is flushed in a batch and only the sent events are removed, so anything appended in the meantime stays. Flushing runs one at a time; two concurrent flushes would send the same batch and then each drop one.

When the signed-in user changes

On a shared iPad, one clinician records and another signs in. Every manifest stores its owner, and the queue only ever lists the current account's recordings. The first clinician's files stay on disk and wait.

That was not enough. Sign-in stores the new session token before it stores the new account's identity, so for a moment the old owner check passes with the new token. The fix has three parts:

  • The uploader is suspended the moment a session ends and resumed only when the next session is fully entered.
  • Each pass captures the owner at the start and re-checks it before each file.
  • Ownership is checked again immediately before every request that carries the token.

What I'd do differently

  • Diff the client against the real server before trusting it. I wrote the uploader against the design document before the backend existed. The server nested a field one level deeper than the plan said, and no recording would ever have reached confirmed.
  • Classify errors in one table from day one. Before that, several answers that could never succeed, a validation error among them, were retried hourly, forever and silently.
  • Test on hardware earlier. All of this was verified by compiling and by an independent code review that found ten real issues. The 17-scenario device matrix (lock immediately, force-quit, reboot before unlock) is written but was still outstanding in my project notes. Until it passes, this design is unproven on hardware.
All writing

Let’s work
together

Get in touch
theasjadanwar@gmail.com+92 321 4010734Resume (PDF)LinkedInGitHub
Version2026 edition
Based inLahore, Pakistan (UTC+5)
SocialsLinkedInGitHub