Recover A Failed Background Task Without Repeating Its Side Effects

A background job writes its output and then the process ends before it records completion. On the next launch, the job still looks pending. Running it again is inevitable unless the work can recognize what already happened.

A completion flag alone cannot close every crash window. Design the output step so repeating it is safe, then advance a durable checkpoint after that output is accepted.

Identify the operation before running it

Give each persisted job a stable ID and immutable inputs. For a derived text file, the same job ID must describe the same output recipe and source revision on every attempt.

This small output step creates the file once, reuses identical existing bytes, and rejects conflicting bytes for the same identity:

import Foundation

enum OutputError: Error { case conflictingOutput }
func materialize(_ bytes: Data, jobID: UUID, directory: URL) throws -> Bool {
    let destination = directory.appendingPathComponent(jobID.uuidString).appendingPathExtension(
        "txt")
    if FileManager.default.fileExists(atPath: destination.path) {
        guard try Data(contentsOf: destination) == bytes else {
            throw OutputError.conflictingOutput
        }
        return false
    }
    try bytes.write(to: destination, options: .atomic)
    return true
}

The caller creates the directory and serializes execution. This is deliberately a single-worker example: fileExists followed by writing is not a lock between competing processes. Use an appropriate claim or database transaction if several workers can run the same job.

For large outputs, use content hashes and file-based verification rather than loading both complete files into memory. Include the transform version in the job contract so an updated algorithm does not silently reuse output from an older recipe.

Checkpoint after the output is durable enough for your contract

The intended sequence is: materialize output, record the job as completed, then tell the scheduler the execution attempt finished.

If execution stops before output publication, the next attempt produces it. If it stops after publication but before checkpointing, the next attempt recognizes the same output and continues. If the checkpoint exists, the dispatcher can skip the already-completed job.

Atomic file replacement helps avoid publishing a partial file, but it is not a complete power-loss durability guarantee. Choose the persistence mechanism and durability settings appropriate to the data rather than claiming an atomic write makes every hardware failure harmless.

Keep the job checkpoint in the same durable store that selects pending jobs. An in-memory Set of completed IDs disappears at exactly the moment this design is meant to handle.

Expiration is a request to stop useful work promptly

Apple’s BGTask expiration handler is where the app reacts when background execution time is ending. Connect it to the worker’s cancellation mechanism and stop admitting new units of work.

The worker must observe cancellation at safe boundaries. A cancellation request does not instantly interrupt arbitrary synchronous encoding or a file operation. Choose chunk sizes that permit timely response and avoid starting an enormous uninterruptible final step with little time remaining.

Have one owner call setTaskCompleted(success:) once for the scheduler attempt. That call is separate from the application’s durable per-job checkpoint. An unsuccessful attempt can still have useful committed progress to reuse later.

Separate replayable output from external side effects

Writing the same derived file is different from sending a message, charging a payment method, or incrementing a remote counter. Checking a local “done” flag cannot tell you whether a remote side effect happened just before a response was lost.

Those operations need a server-supported idempotency or reconciliation contract. The durable outbox example explains stable operation identities and exact acknowledgement; do not use this local-file helper as an exactly-once networking solution.

Likewise, retain account ownership and authorization checks when resuming a persisted job. A background retry must not apply one account’s output to another account that signed in later.

Test the gap, not just the finished job

The fixture writes output, deliberately leaves the checkpoint absent, and runs the materialization step again. The second run reuses the output. It then verifies that different bytes with the same job ID fail and that a saved checkpoint can be decoded on a later read.

This tests the recovery seam without waiting for the operating system to choose a background execution time. A device integration test should separately exercise expiration, cancellation, scheduling, and relaunch with the app’s actual task registration.

September 2026 review: replay, conflict rejection, and checkpoint reload checks passed; the helper type-checked for iOS 17. No real BGTask execution or abrupt device termination was triggered by the fixture.