skip to content

A Swift actor thumbnail cache checks its dictionary, awaits a download, then stores the image; why can two screens trigger the same download, and how do you fix it?

level: seniorimportance: must knowfreq 62%

answer

  1. actors interleave at suspension points
  2. the check runs before the await
  3. state read before await may be stale
  4. record in-flight work before suspending

basics

~20 s

Swift actors are reentrant: while one call waits at an await, other calls run on the actor, so both callers miss the cache before either download finishes. Store an in-flight Task before suspending and let later callers await it.

solid answer

~40 s

An actor guarantees that only one piece of its code runs at a time, not that a method runs start to finish uninterrupted. At every `await` inside an actor method the call can suspend, and Swift actors are **reentrant**: the actor runs other waiting calls meanwhile. Caller A checks `thumbnails[name]`, misses, and suspends on the download; caller B enters, misses too, and starts a second download; both later store the same key. There is no data race, since the dictionary is never touched concurrently, but the invariant "one download per image" breaks. The fix is to change state synchronously before suspending: put a `Task` for the in-flight download in the dictionary, so a later caller finds it and awaits `task.value`. More generally, re-check after an `await` anything you read before it.

code

swift · 27 lines
swift
actor ThumbnailCache {
    private var thumbnails: [String: String] = [:]
    private(set) var downloads = 0

    func thumbnail(for name: String) async -> String {
        if let cached = thumbnails[name] { return cached }
        let image = await download(name)     // suspension: other calls run here
        thumbnails[name] = image
        return image
    }

    private func download(_ name: String) async -> String {
        downloads += 1
        try? await Task.sleep(for: .milliseconds(50))
        return "thumb-\(name)"
    }
}

@main struct Demo {
    static func main() async {
        let cache = ThumbnailCache()
        async let a = cache.thumbnail(for: "cat")
        async let b = cache.thumbnail(for: "cat")
        _ = await (a, b)
        print("downloads:", await cache.downloads)
    }
}

go deeper

for a junior

Recall that an actor can run other calls while one of its methods is suspended at an await.

for a middle

Explain why reentrancy keeps the actor free of data races yet still lets state read before an await go stale.

for a senior

Diagnose the duplicate-download trace and fix it by storing an in-flight Task synchronously, handling failure and stale entries.

for a principal

Set a review rule for actor code: invariants change synchronously, and every await is treated as a point where actor state may change.

## What an actor promises, and what it does not A Swift actor runs **one piece of its code at a time**, so its stored properties are never read and written concurrently: there are no data races on actor state. The unit that runs without interruption, though, is not a whole method. It is the stretch of code **between suspension points**. When an actor-isolated method reaches `await` and actually suspends, the actor is free to run other work that is waiting for it. SE-0306, the proposal that introduced actors, calls this **interleaving** and chose it on purpose: actor-isolated functions are **reentrant**. The proposal's reasons are that non-reentrant actors can deadlock when two actors call each other, and they block every other caller, cache hits included, for as long as one call is suspended. The cost it names is that actor-isolated state can change across an `await`, so code must not rely on an invariant holding across one. ## Tracing the duplicate download Take a cache whose `thumbnail(for:)` checks a dictionary, awaits `download(_:)`, and stores the result. Two screens ask for `"cat"` at almost the same time: 1. Call A runs on the actor, finds no entry for `"cat"`, and calls `download`, which suspends at its `await` on the network. 2. The actor is now free. Call B runs, finds no entry either, because A has not stored anything yet, and starts a second download. 3. Both downloads finish; A and B each write `thumbnails["cat"]`. The second write replaces the first. Nothing crashed and the dictionary is consistent, yet the app paid for two downloads, and with side effects such as counting, billing or writing to disk the duplicate is a real bug. The demo in the first code example prints `downloads: 2`. ## Fixes | Fix | How it works | What to watch | |---|---|---| | Store in-flight work | put a `Task` in the dictionary **before** the first `await`; later callers await `task.value` | remove or replace the entry if the download fails | | Re-check after `await` | after resuming, look at the state again before acting on what you read earlier | turns a duplicate into a wasted but harmless call | | Keep invariant changes synchronous | move multi-step updates into a synchronous method, which cannot contain a suspension point | does not help when the work itself must await | The in-flight pattern works because the check and the insert happen in one synchronous stretch: between `entries[name] == nil` and `entries[name] = .inFlight(task)` there is no `await`, so no other call can interleave. Call B then finds `.inFlight` and awaits the same task. The second code example prints `downloads: 1`. ## Edges of the in-flight pattern - **Failure.** If the download can throw, a failed task left in the dictionary hands the same error to every later caller. On failure, remove the entry, after checking it still holds that task, since another call may have replaced it while you were suspended. - **Isolation of the task.** A `Task { }` created inside an actor method inherits the actor's isolation, so its closure may call actor-isolated helpers; what else a task inherits is covered with tasks and cancellation. - **Cancellation.** Cancelling one waiting caller does not cancel the shared unstructured task; that is usually what you want for a cache, but decide it deliberately. - **Memory.** Finished entries should move from `.inFlight` to `.ready`, or into an eviction policy, so tasks do not pile up. ## The same bug on the main actor The main actor is an actor too, and just as reentrant. A `@MainActor` view model whose `reload()` sets `isLoading`, awaits a fetch, and assigns the results can run twice if the user refreshes twice: both calls suspend on the fetch, and the slower, older response may arrive last and overwrite the newer one. The fixes are the same in spirit: cancel the previous task when starting a new one, or record a request token before the `await` and drop a result whose token is no longer current. ## What a candidate should say - Reentrancy is not a data race; Swift's isolation still holds. - Every `await` inside an actor is a point where other calls may change the actor's state. - Fix it by making the decision and the bookkeeping synchronous, then awaiting shared work.

  • What goes wrong if the download throws and its in-flight entry stays in the dictionary?
    Every later caller finds the same finished task and awaits the same error, so the image never loads until the entry is evicted. On failure, remove the entry so the next request retries; because the removal happens after an `await`, first check that the dictionary still holds that same task, since another call may have replaced it while you were suspended.
  • Would making `download` a synchronous call inside the actor avoid the problem?
    It would remove the suspension point, so no call could interleave, but the actor would be held for the whole download: every other caller, including cache hits, would wait behind it. SE-0306 rejected non-reentrant actors for exactly this unnecessary blocking and for the deadlocks it invites. Keep the work asynchronous and make the bookkeeping synchronous instead.
  • Can the same interleaving happen on a `@MainActor` view model?
    Yes. The main actor is reentrant like any actor: two overlapping `reload()` calls can both suspend on the fetch, and the older response may finish last and overwrite the newer one. Cancel the previous task when a new reload starts, or record a request token before the `await` and ignore a result whose token is stale.

A pharmacist serves one customer at a time, but while your order is fetched from the back room they serve the next person. If you both asked for the last box, the shelf you checked before stepping aside may be empty when you return, unless the pharmacist put your name on the box first.

  • An actor runs each method to completion before it starts another call.
  • Reentrancy means two threads write the actor's dictionary at the same time.
  • Values read before an await inside an actor are still current after it.
  • Wrapping the dictionary in a lock inside the actor stops the duplicate download.
  • Swift 6 language mode reports this interleaving as a compile-time data-race error.