Coalesce Network Requests Without Reviving An Invalid Cache

An actor is a great place to put a small network cache. It protects the dictionary, gives callers one async entry point, and keeps the synchronization out of our views.

It can also confidently return yesterday’s data after we explicitly asked it to forget that data. 😅

The problem appears when invalidation happens while a request is suspended. Sharing in-flight tasks solves duplicate requests, but we need one more rule: only the current generation may update the cache.

Donny Wals’s explanation of actor reentrancy is a useful starting point for the shared-task pattern. Let’s extend that idea with a refresh scenario that is easy to miss in a small demo.

September 2026 review: the complete cache and controlled-response checks compile and run in Swift 6 mode with Xcode 27. The example uses established concurrency APIs rather than a Swift 6.4-only feature.

Reproduce the stale write

Imagine a book-details screen and its toolbar both need the same summary. We store a loading task so they can await the same request.

Then the user edits the book:

  1. Request A starts loading the old summary.
  2. The edit succeeds. We invalidate the summary.
  3. Request B starts loading the new summary.
  4. Request A finishes late.

If A blindly writes its result, invalidation has effectively been reversed. If A’s error handler blindly removes the loading entry, it can remove B instead.

Neither operation violates actor isolation. They happen one at a time. They simply happen in an order our logic did not anticipate. Swift’s actor proposal describes this distinction: a suspension permits other actor work to interleave, so assumptions made before an await may need checking afterward.

Give each flight its own identity

Here is a small cache intended to live with one bounded feature or session. Key identifies the representation being loaded; Value is an immutable, sendable snapshot.

import Foundation

struct SupersededRequest: Error {}

actor RequestCache<Key: Hashable & Sendable, Value: Sendable> {
    private struct Flight {
        let id: UUID
        let task: Task<Value, Error>
    }

    private var values: [Key: Value] = [:]
    private var flights: [Key: Flight] = [:]
    private var generations: [Key: UUID] = [:]

    func value(
        for key: Key,
        load: @escaping @Sendable (Key) async throws -> Value
    ) async throws -> Value {
        try Task.checkCancellation()
        if let value = values[key] { return value }

        let flight: Flight
        if let existing = flights[key] {
            flight = existing
        } else {
            let id = UUID()
            let task = Task { try await load(key) }
            flight = Flight(id: id, task: task)
            generations[key] = id
            flights[key] = flight
        }

        do {
            let value = try await flight.task.value
            guard generations[key] == flight.id else {
                throw SupersededRequest()
            }

            values[key] = value
            if flights[key]?.id == flight.id {
                flights[key] = nil
            }

            try Task.checkCancellation()
            return value
        } catch {
            if flights[key]?.id == flight.id {
                flights[key] = nil
            }
            throw error
        }
    }

    func invalidate(_ key: Key) {
        values[key] = nil
        generations[key] = nil
        flights.removeValue(forKey: key)?.task.cancel()
    }
}

We store a new task before reaching the first suspension. Another caller arriving at that point finds the task and joins it.

After the suspension, the generation check decides whether the result still belongs to this cache. Invalidating the key removes its generation. Starting a replacement assigns a different one. Either action prevents an older success from being installed.

The conditional cleanup matters just as much. A failed or superseded request only removes its own flight. It cannot erase a newer task that happens to use the same key.

Why keep the generation separately from flights? Several callers can await one task. The first caller to resume may store the value and remove the flight before the second resumes. The generation remains available so that second caller can still recognize a valid result.

Decide who owns cancellation

In this design, the cache owns the shared task. Canceling one waiting screen does not cancel work another screen still needs. We check the caller’s cancellation before starting and again before returning a successful value.

That has a deliberate limitation: a canceled waiter can remain suspended until the shared task finishes. If immediate waiter cancellation matters, use a design that tracks individual waiters and resumes each cancellation independently. Add that complexity because the feature needs it, not because every cache must become a scheduler.

Invalidation does cancel the shared task, because its result is no longer useful to this cache. But task cancellation is cooperative. A loader can ignore cancellation, or finish too close to the cancellation request to stop. The generation check is what enforces correctness even in that case.

Notice that a current result may still populate the cache even if one caller was canceled. That is consistent with shared ownership. The canceled caller then throws instead of consuming the result.

Include the whole representation in the key

The cache does not know what makes two requests equivalent. We have to decide that:

struct SummaryKey: Hashable, Sendable {
    let accountID: UUID
    let bookID: UUID
    let languageCode: String
}

If account, language, or a relevant filter changes the response, it belongs in the identity. Calling the same key with two different loaders does not create two flights; the first loader wins. In a real feature, I would usually inject one loader when constructing a specialized cache so callers cannot disagree about that contract.

This example also has no expiration or size policy. Use it for a bounded working set, add explicit eviction for a growing set, and clear session-owned data on logout. An in-memory generation check does not replace server authorization or HTTP cache rules.

Test the order, not the delay

To check the bug, the test loader holds each response behind a continuation. The test can wait until request A has actually started, invalidate, wait until B starts, and then release A. No arbitrary sleep is needed.

The important assertions are:

  • A’s late success throws SupersededRequest.
  • B still completes and becomes the cached value.
  • A late failure cannot clear B’s loading entry.
  • A failed current flight is removed, so the next read can retry.
  • Concurrent reads of a completed entry do not call the loader again.

I ran the stale-success/replacement, failure/retry, and concurrent-cache-hit cases against the implementation above. The fixture deliberately ignores cancellation, which makes the stale-result check meaningful instead of accidentally relying on a well-behaved URLSession request.

For your integration test, add concurrent misses against the actual loader and count underlying requests. Also test account switching if this cache can outlive a login session.

The next time you review an await inside a cache actor, look at the code immediately after it. Before that code writes or clears anything, it should be able to answer one question: does this result still own the entry it is about to change?