Adopt Remote Configuration Without Changing Work In Flight

An export starts with a batch size of 50. While its first request is running, remote configuration changes the batch size to 200 and disables exports.

Which rules should the remaining requests follow?

Reading a shared settings object before every request makes the answer depend on timing. Putting that object on an actor prevents simultaneous access, but another task can still change it while the export is suspended at an await.

We will give configuration three separate stages: received bytes, a validated pending policy, and the value captured by an operation. Each export keeps the policy it started with. The next export can adopt the replacement.

A configuration file is still input, even when it arrives wearing our company logo.

Fetching is not adopting

The Stack Overflow question about values remaining at their defaults already has an accepted answer about activation after fetching. Firebase’s current loading guidance also separates fetching values from choosing when to activate them.

Our question starts one layer later: when several values jointly control a running operation, how do we keep them consistent?

Joe Heck’s article about dynamic configuration in Swift services uses immutable provider snapshots to make related reads consistent. We will apply that principle to a small iOS export, without adding a configuration framework.

This is timely after the Firebase Analytics configuration incident, discussed in iOS Dev Weekly 770. The code below validates JSON our app owns. It cannot prevent a crash inside a third-party SDK before that SDK returns control to us.

The four Swift blocks belong in one file. The complete test package uses Xcode 27 / Swift 6.4 and targets iOS 17 and macOS 14 or later. The app code needs only Foundation; Hummingbird is a dependency of the HTTP tests. This is an established concurrency technique, not a new OS 27 API.

Make invalid policies impossible to adopt

Suppose the server returns this document:

{
  "schemaVersion": 1,
  "revision": "autumn-42",
  "exportEnabled": true,
  "batchSize": 50,
  "maxItemsPerExport": 5000
}

Decoding establishes that the fields have the expected types. It does not establish that a batch size of zero is useful, or that a batch can fit inside the export’s item limit. Keep the wire model separate from the validated value:

import Foundation

private nonisolated struct PolicyPayload: Decodable {
    let schemaVersion: Int
    let revision: String
    let exportEnabled: Bool
    let batchSize: Int
    let maxItemsPerExport: Int
}

nonisolated enum PolicyError: Error {
    case tooLarge, unsupportedSchema, invalidValues
}

nonisolated struct ExportPolicy: Equatable, Sendable {
    let revision: String
    let exportEnabled: Bool
    let batchSize: Int
    let maxItemsPerExport: Int

    static let bundled = ExportPolicy(
        revision: "bundled-1", exportEnabled: true,
        batchSize: 50, maxItemsPerExport: 5000
    )

    private init(
        revision: String, exportEnabled: Bool,
        batchSize: Int, maxItemsPerExport: Int
    ) {
        self.revision = revision
        self.exportEnabled = exportEnabled
        self.batchSize = batchSize
        self.maxItemsPerExport = maxItemsPerExport
    }

    init(data: Data) throws {
        guard data.count <= 64 * 1024 else {
            throw PolicyError.tooLarge
        }
        let value = try JSONDecoder().decode(PolicyPayload.self, from: data)
        guard value.schemaVersion == 1 else {
            throw PolicyError.unsupportedSchema
        }
        guard (1...80).contains(value.revision.utf8.count),
              value.revision.utf8.allSatisfy({
                  (48...57).contains($0) || (65...90).contains($0) ||
                  (97...122).contains($0) || $0 == 45
              }),
              (1...200).contains(value.batchSize),
              (value.batchSize...10_000).contains(value.maxItemsPerExport)
        else {
            throw PolicyError.invalidValues
        }
        self.init(
            revision: value.revision,
            exportEnabled: value.exportEnabled,
            batchSize: value.batchSize,
            maxItemsPerExport: value.maxItemsPerExport
        )
    }
}

The value and transport types are explicitly nonisolated so the same code works when a project uses MainActor default isolation; validation and adoption still run synchronously inside the store’s main-actor methods.

The limits are application policy, not Foundation requirements. Pick bounds your backend actually supports. The revision is a short diagnostic identifier, not a number to sort: deliberately rolling back to autumn-41 must remain possible.

Missing fields, wrong types, and malformed JSON throw through JSONDecoder. Unknown keys are ignored; an unknown schema version rejects the whole document. This allows harmless added fields without accidentally interpreting a new protocol as the old one.

ExportPolicy does not conform to Decodable. That prevents a synthesized decoder from creating a value that skips our validation. The bundled policy is the one deliberate, version-controlled default.

Check the response before decoding

This adapter accepts one JSON document from an app-owned endpoint:

nonisolated enum PolicyResponseError: Error {
    case unexpectedResponse
}

nonisolated struct HTTPPolicyLoader: Sendable {
    let url: URL
    let session: URLSession

    func load() async throws -> Data {
        var request = URLRequest(url: url)
        request.timeoutInterval = 15
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        let (data, response) = try await session.data(for: request)
        guard let http = response as? HTTPURLResponse,
              http.statusCode == 200,
              http.mimeType?.lowercased() == "application/json" else {
            throw PolicyResponseError.unexpectedResponse
        }
        return data
    }
}

Use your normal HTTPS endpoint and an appropriately configured session. The caller owns the session’s lifetime, cache and authentication policy. No credentials belong in the configuration document.

data(for:) buffers the response. Our 64 KiB check rejects oversized documents after download; it is not a network memory limit. If the endpoint needs a streaming byte budget, enforce that while receiving the body, as in the bounded streaming example.

Stage a complete value, and reject stale refreshes

The store keeps the currently adopted policy and, optionally, its validated replacement:

nonisolated enum RefreshOutcome: Equatable, Sendable {
    case staged, superseded, cancelled, rejected
}

@MainActor
final class ConfigurationStore {
    private(set) var activePolicy = ExportPolicy.bundled
    private(set) var pendingPolicy: ExportPolicy?
    private var latestRefresh: UUID?

    func refresh(
        using load: @Sendable () async throws -> Data
    ) async -> RefreshOutcome {
        guard !Task.isCancelled else { return .cancelled }
        let ticket = UUID()
        latestRefresh = ticket

        do {
            let data = try await load()
            try Task.checkCancellation()
            guard latestRefresh == ticket else { return .superseded }
            let policy = try ExportPolicy(data: data)
            pendingPolicy = policy
            latestRefresh = nil
            return .staged
        } catch {
            guard latestRefresh == ticket else { return .superseded }
            latestRefresh = nil
            return Task.isCancelled ? .cancelled : .rejected
        }
    }

    func adoptPending() -> ExportPolicy {
        if let pendingPolicy {
            activePolicy = pendingPolicy
            self.pendingPolicy = nil
        }
        return activePolicy
    }
}

A successful refresh stages a whole value. It never edits individual fields of activePolicy. A failed refresh leaves both the active policy and any previously validated pending policy intact.

The ticket implements a specific rule: the most recently started refresh owns the right to stage its response. If refresh A starts, then B starts, A cannot replace B’s result—even if B fails. We keep our last validated value instead of guessing that A is still wanted. Tickets order requests, not server revisions; they cannot detect stale content returned by a cache or server.

Cancellation is checked again after the loader returns. That matters when a loader ignores cancellation and eventually returns successful data. Superseding a request does not cancel its network work; the task’s owner should cancel work it no longer needs. The ticket protects state even when cancellation arrives too late.

Start store.refresh(using: loader.load) from an owned refresh task and handle its outcome. Let export actions use the same store without waiting for a network refresh. On a fresh launch, the bundled policy is immediately available.

This sample keeps validated policies in memory. Persisting a last-known-good document across launches is a separate layer; the versioned Codable file example is a starting point. Revalidate restored bytes before staging them.

Capture once at the operation boundary

Here is an export whose input is an already available array of authorized item IDs. The injected send closure represents your existing upload operation:

nonisolated struct ExportBatch: Equatable, Sendable {
    let revision: String
    let itemIDs: [Int]
}

nonisolated enum ExportError: Error {
    case disabled, tooManyItems
}

@MainActor
func export(
    _ itemIDs: [Int],
    using store: ConfigurationStore,
    send: @Sendable (ExportBatch) async throws -> Void
) async throws {
    try Task.checkCancellation()
    let policy = store.adoptPending()
    guard policy.exportEnabled else { throw ExportError.disabled }
    guard itemIDs.count <= policy.maxItemsPerExport else {
        throw ExportError.tooManyItems
    }

    for start in stride(from: 0, to: itemIDs.count, by: policy.batchSize) {
        try Task.checkCancellation()
        let end = min(start + policy.batchSize, itemIDs.count)
        let batch = ExportBatch(
            revision: policy.revision,
            itemIDs: Array(itemIDs[start..<end])
        )
        try await send(batch)
        try Task.checkCancellation()
    }
}

The important line is let policy = store.adoptPending(). Adoption and capture happen synchronously on the main actor, before the first suspension. Everything after that reads this value, including the batch size and revision.

While send is suspended, another task can refresh the store. Another export can even adopt that replacement. Neither action changes the first export’s local policy.

An export with seven IDs and a batch size of two sends 2, 2, 2, 1. If a policy with a batch size of three arrives after its first send, it still sends 2, 2, 2, 1. The next export sends 3, 3, 1. No IDs disappear between batches because the rules changed.

Disabling exports blocks the next export that adopts that policy. It does not interrupt existing exports. If you need an emergency stop, model that as a separate cancellation signal and define how the server handles partially completed work. The low-power-mode article makes a similar distinction between deciding whether to begin work and interrupting work already underway.

The sender runs sequentially. A thrown error stops later batches; there is no automatic retry. Cancellation is cooperative and cannot undo a completed upload. A sender that ignores cancellation delays the export’s response until it returns. Server-side authorization, idempotency and transactional behavior remain the server’s responsibility. A client feature flag is not permission to access data.

Test the interleaving, not just the JSON

A decoder test cannot establish that an operation keeps its policy. Hold the first send open, refresh configuration, start a second export, and only then let the first continue.

The downloadable package uses controlled suspension points for that sequence and a real local HTTP fixture for response handling. Its checks cover:

  • Invalid types, missing fields, unsupported schemas, cross-field limits and oversized documents; added keys remain compatible.
  • A late refresh after a newer success or failure, and cancelled work that returns data anyway.
  • Failed refreshes retaining a valid pending policy, plus an intentional revision rollback.
  • Two overlapping exports retaining their own revision, batch boundaries and complete item order.
  • Disabled and oversized exports making no sends, partial final batches, sender errors and cancellation between sends.

Verification: the exact four Swift blocks were compiled and exercised with Xcode 27.0 / Swift 6.4 on macOS 27 and an iOS 27 Simulator, in both ordinary and MainActor default isolation. The sample targets iOS 17; older-OS runtime behavior, physical devices, Firebase SDK integration and disk restoration were not tested.

For a multistep operation, the useful configuration is the one it can finish with. Fetch a replacement whenever appropriate, validate it as a unit, and give the next operation a clean place to adopt it.