Actor reentrancy bugs in real apps: 5 patterns and how to fix them

A quick follow-up to Swift 6 actors and concurrency: how they work, reentrancy pitfalls, and what's new in 6.2. That post covered the mechanics; this one is the field guide. One-line recap: Swift actors are reentrant — whenever an actor method hits an await, the actor is free to run other queued calls before that method resumes, so an actor method is not atomic across its suspension points.

That single fact is behind a whole class of bugs that sail through code review and unit tests and then surface in production. They pass review because the method reads correctly top to bottom when you trace one call. They pass tests because most tests fire one call at a time, and the bug needs two callers racing at the exact same await. Under real load — a user double-tapping, two screens observing the same model, a retry colliding with the original — that race stops being rare.

Below are five patterns I keep seeing in iOS codebases, with Swift 6.2 fixes. The snippets are written against Swift 6.2 strict concurrency to illustrate the shape of each fix; I haven't run them in this post, and I've flagged the couple of 6.2-specific attributes that need an upcoming-feature flag.

1. Stale state read after an await

Scenario: a Wallet actor checks the balance, charges a payment gateway, then deducts the amount.

actor Wallet {
    private var balance: Int

    init(balance: Int) { self.balance = balance }

    func withdraw(_ amount: Int, using gateway: PaymentGateway) async throws {
        guard balance >= amount else { throw WalletError.insufficientFunds }
        try await gateway.charge(amount)   // suspension point
        balance -= amount
    }
}

What goes wrong, step by step: Call A enters with balance == 100 and amount == 100. The guard passes. At try await gateway.charge, A suspends and the actor picks up Call B, also for 100. B's guard reads the still-unchanged balance == 100 and passes too. Both charge the gateway, both resume, both run balance -= 100, and you end at -100. The value you validated before the await was stale by the time you acted on it.

Fix: reserve the funds before you suspend, and roll back on failure. Re-reading the balance after the await is not enough — two callers can both pass a post-await re-check just as easily.

func withdraw(_ amount: Int, using gateway: PaymentGateway) async throws {
    guard balance >= amount else { throw WalletError.insufficientFunds }
    balance -= amount                      // commit before suspending
    do {
        try await gateway.charge(amount)
    } catch {
        balance += amount                  // roll back if the charge fails
        throw error
    }
}

Rule of thumb: state you read before an await is a snapshot, not a guarantee — mutate or reserve before you suspend.

2. Duplicate concurrent work

Scenario: two views appear at once and both ask an ImageLoader for the same URL; two identical downloads go out.

actor ImageLoader {
    private var cache: [URL: Data] = [:]

    func data(for url: URL) async throws -> Data {
        if let cached = cache[url] { return cached }
        let data = try await download(url)   // both callers reach here
        cache[url] = data
        return data
    }
}

What goes wrong: Caller A misses the cache and suspends in download. Before A writes the cache, Caller B runs, also misses, and starts a second download. You pay for two requests, and whichever finishes last wins the cache write.

Fix: cache the in-flight Task, not just the finished result, and insert it before the first await so concurrent callers find it and await the same work.

actor ImageLoader {
    private enum Entry {
        case ready(Data)
        case inProgress(Task<Data, Error>)
    }
    private var cache: [URL: Entry] = [:]

    func data(for url: URL) async throws -> Data {
        switch cache[url] {
        case .ready(let data):
            return data
        case .inProgress(let task):
            return try await task.value
        case nil:
            let task = Task { try await download(url) }
            cache[url] = .inProgress(task)
            do {
                let data = try await task.value
                cache[url] = .ready(data)
                return data
            } catch {
                cache[url] = nil             // let a later call retry
                throw error
            }
        }
    }
}

Rule of thumb: deduplicate concurrent identical work by caching the in-flight Task, not only the result.

3. Check-then-act across a suspension point

Scenario: a SessionManager that should perform a handshake exactly once.

actor SessionManager {
    private var isStarted = false

    func startIfNeeded() async {
        guard !isStarted else { return }
        await performHandshake()    // suspension point
        isStarted = true
    }
}

What goes wrong: this is pattern 1 in disguise, and it's the most common form I see. Two callers both read isStarted == false, both pass the guard, both run the handshake. The flag is only set after the await, so it can't protect the window that matters.

Fix: if callers don't need to wait for completion, commit the decision before suspending:

func startIfNeeded() async {
    guard !isStarted else { return }
    isStarted = true                // commit the decision first
    await performHandshake()
}

If callers do need the handshake to be finished when startIfNeeded() returns, store the work as a Task and await it (the same shape as pattern 2):

actor SessionManager {
    private var startTask: Task<Void, Never>?

    func startIfNeeded() async {
        if let startTask {
            return await startTask.value
        }
        let task = Task { await performHandshake() }
        startTask = task
        await task.value
    }
}

Rule of thumb: a check-then-act must not straddle an await — commit the decision (set the flag, store the Task) before you suspend.

4. Missing cancellation handling

Scenario: search-as-you-type. Each keystroke starts a new search Task; the old one should stop.

func search(_ query: String) async throws -> [Result] {
    let ids = try await api.search(query)
    var results: [Result] = []
    for id in ids {
        results.append(try await api.details(id))   // keeps going after cancel
    }
    return results
}

What goes wrong: cancellation in Swift is cooperative. Cancelling the Task only sets a flag; this loop never looks at it, so a superseded search keeps fetching details for every id and may deliver stale results over the fresh ones.

Fix: check cancellation in the loop, and use withTaskCancellationHandler when you need to tear down callback-based work (for example to resume a continuation or cancel an in-flight URLSessionTask).

func search(_ query: String) async throws -> [Result] {
    let ids = try await api.search(query)
    var results: [Result] = []
    for id in ids {
        try Task.checkCancellation()                 // throws CancellationError
        results.append(try await api.details(id))
    }
    return results
}

Two things worth flagging: structured concurrency (async let, task groups) propagates cancellation to children automatically, but the leaf work still has to check and throw. And whether a given async call aborts on cancellation depends on the API — URLSession's async methods do throw on cancellation; a CPU loop or a third-party callback bridged with a plain continuation will not unless you wire it up.

Rule of thumb: cancellation is cooperative — add try Task.checkCancellation() to loops and withTaskCancellationHandler to callback-bridged work, and confirm your async APIs actually honor it.

5. Unnecessary @MainActor hops (and what 6.2 changes)

This one is about performance, not correctness, and Swift 6.2 shifts the defaults.

Scenario: a @MainActor view model fetches a feed and decodes it — on the main actor.

@MainActor
final class FeedViewModel {
    private(set) var items: [Item] = []

    func reload() async throws {
        let data = try await api.fetchFeed()
        let items = try JSONDecoder().decode([Item].self, from: data)  // on main
        self.items = items
    }
}

What goes wrong: because the type is @MainActor, the decode runs on the main actor. A large payload blocks the main thread and janks scrolling. The inverse mistake also exists: sprinkling nonisolated async helpers that hop off the main actor and back for trivial work, paying for context switches you didn't need.

Fix: push the heavy, self-contained work off the main actor explicitly. In Swift 6.2 the tool for this is @concurrent, which opts an async function out of running on the caller and onto the concurrent executor.

@MainActor
final class FeedViewModel {
    private(set) var items: [Item] = []

    func reload() async throws {
        let data = try await api.fetchFeed()
        let items = try await Self.decode(data)   // runs off the main actor
        self.items = items                         // back on main to publish
    }

    @concurrent
    private static func decode(_ data: Data) async throws -> [Item] {
        try JSONDecoder().decode([Item].self, from: data)
    }
}

What's new in 6.2 and why it matters here: with the NonisolatedNonsendingByDefault upcoming feature (SE-0461), a plain nonisolated async function now runs on the caller's executor by default instead of always hopping to the generic executor — so you stop paying for accidental hops on light async work, and you offload deliberately with @concurrent. Combined with default actor isolation (.defaultIsolation(MainActor.self), SE-0466), the mental model flips: code is on the main actor unless you say otherwise, and leaving it is an explicit choice.

A couple of flags on the 6.2 specifics: @concurrent and nonisolated(nonsending) come from SE-0461 and require the NonisolatedNonsendingByDefault upcoming feature to be enabled; I've seen the attribute need to precede the access modifier (@concurrent private static func, not the other way around), so if the compiler complains, check ordering. If anyone has the exact current spelling/behavior in a released 6.2 toolchain, please correct me.

Rule of thumb: keep CPU-heavy work off @MainActor with @concurrent, and let light async stay on the caller rather than hopping needlessly.

Checklist before you ship

  • For every await in actor-isolated code, ask: can this state change while I'm suspended? Re-read, reserve, or commit before the suspension.
  • Deduplicate concurrent identical work by caching the in-flight Task, not just the result.
  • Don't let check-then-act straddle a suspension point; set the flag or store the Task before you await.
  • Add try Task.checkCancellation() to loops, use withTaskCancellationHandler for callback-bridged work, and verify your async APIs honor cancellation.
  • Keep heavy CPU work off the main actor with @concurrent; don't add needless actor hops for trivial async.
  • Add a test that fires two concurrent calls at the same actor method and asserts the invariant (balance never negative, exactly one network call, handshake runs once). That's the test that actually catches these.

Over to you

What reentrancy bug has bitten you in production — and did you catch it in review, in a crash log, or in a user report? I'm especially interested in cases where the "obvious" fix (a lock, or re-reading state after the await) quietly didn't hold under real concurrency.