On Monday morning a scheduling app opened shifts, messages, and requests at once. Each screen asked for a valid token. The token had expired. Three refresh calls reached the server, and a server that rotates refresh tokens treated the second and third as replays. It revoked the session. The user was signed out while opening the app.
The token store was already an actor. The compiler was satisfied, and it was right to be: no two callers ever touched the store’s state at the same time. They simply took turns making the same decision.
Actor isolation answers who may touch the state now. It does not answer whether a decision made before a suspension is still true after it. That question belongs to whoever owns the work, and here nobody did.
The store that looks safe
import Foundation
struct AuthToken: Sendable {
let refreshToken: String
let expiresAt: Date
}
protocol AuthAPI: Sendable {
func refresh(_ token: String) async throws -> AuthToken
}
actor NaiveTokenStore {
private let api: any AuthAPI
private var token: AuthToken
init(api: any AuthAPI, token: AuthToken) {
self.api = api
self.token = token
}
func validToken(at now: Date) async throws -> AuthToken {
if token.expiresAt <= now {
token = try await api.refresh(token.refreshToken)
}
return token
}
}Read it the way the runtime runs it. The first caller sees an expired token and suspends at await api.refresh. Actors are reentrant, so while it is suspended the second caller enters, sees the same expired token, and suspends at the same line. So does the third. Each one acted on a check that was true when it was made and stale by the time it mattered.
The repair is not a lock around the network call. It is to make the refresh a piece of shared work with one owner, published before anyone suspends.
Publish shared work before suspending
The check and the publication of the refresh task belong in one actor turn. Joiners await the same task. The session is captured too, because sign-out or an account switch can happen while the network is still working.
enum SessionError: Error {
case signedOut
case sessionChanged
}
actor TokenStore {
private struct Flight {
let id: UUID
let task: Task<AuthToken, any Error>
}
private let api: any AuthAPI
private var token: AuthToken?
private var session = UUID()
private var flight: Flight?
init(api: any AuthAPI, token: AuthToken?) {
self.api = api
self.token = token
}
func validToken(at now: Date) async throws -> AuthToken {
try Task.checkCancellation()
guard let token else { throw SessionError.signedOut }
let expectedSession = session
let current: Flight
if let flight {
current = flight
} else {
guard token.expiresAt <= now else { return token }
let task = Task { [api, refreshToken = token.refreshToken] in
try await api.refresh(refreshToken)
}
current = Flight(id: UUID(), task: task)
flight = current
}
let result = await current.task.result
guard session == expectedSession else {
throw SessionError.sessionChanged
}
if flight?.id == current.id {
flight = nil
if case .success(let refreshed) = result {
self.token = refreshed
}
}
try Task.checkCancellation()
_ = try result.get()
guard let committed = self.token else {
throw SessionError.signedOut
}
return committed
}
func replaceSession(with replacement: AuthToken?) {
session = UUID()
token = replacement
flight?.task.cancel()
flight = nil
}
}Every line after the await exists because the world may have changed during it.
The flight is published before the suspension. Between flight = current and await current.task.result there is no await, so no other caller can observe an expired token without also observing the flight.
The session is re-checked after the suspension. A response that belongs to a replaced session is refused before it can touch the new one. Clearing a published token on sign-out is not enough if a late refresh can write it back.
The flight ID guards the commit. The first waiter to resume commits and clears its own slot. Later waiters find the slot empty, or occupied by a newer flight, and leave it alone.
A caller’s cancellation is its own. One screen disappearing must not cancel a refresh the other two still need, so the shared task is cancelled only by replaceSession. A cancelled caller still waits for the shared result here; if individual waits must be abandoned promptly, that is a separate waiter policy, not a reason to cancel the work.
The store is in memory. The transport and the secure persistence of the token belong at the app’s integration boundary, and persistence needs the same session check: a write to the keychain from a replaced session is the same bug in a more durable place.
Put remote decisions at their authority
The same shape appears when someone claims the last open shift. A local count can say whether a request is worth sending. It cannot say who gets the slot, because another device is outside the actor. Holding a local mutex around the network call would serialize this phone and leave every other phone outside the decision. The server decides atomically and returns the confirmed result. The client renders that answer.
Session ownership also lives above the window hierarchy. On iPad and Mac, three windows can read one account state derived from a single owner. Three windows each creating their own TokenStore would rebuild the original bug across scenes.
Reproduce the interleaving
Ordering bugs need ordering under test control. A fake whose refresh the test releases explicitly:
import Testing
actor GatedAuthAPI: AuthAPI {
private(set) var calls = 0
private var gates: [CheckedContinuation<Void, Never>] = []
private var callWaiters: [CheckedContinuation<Void, Never>] = []
func refresh(_ token: String) async throws -> AuthToken {
calls += 1
callWaiters.forEach { $0.resume() }
callWaiters = []
await withCheckedContinuation { gates.append($0) }
return AuthToken(refreshToken: "rotated", expiresAt: .distantFuture)
}
func waitForFirstCall() async {
if calls > 0 { return }
await withCheckedContinuation { callWaiters.append($0) }
}
func release() {
gates.forEach { $0.resume() }
gates = []
}
}
@Test func concurrentCallersShareOneRefresh() async throws {
let api = GatedAuthAPI()
let expired = AuthToken(refreshToken: "old", expiresAt: .distantPast)
let store = TokenStore(api: api, token: expired)
async let a = store.validToken(at: .now)
async let b = store.validToken(at: .now)
async let c = store.validToken(at: .now)
await api.waitForFirstCall()
await api.release()
let tokens = try await [a, b, c]
#expect(tokens.map(\.refreshToken) == ["rotated", "rotated", "rotated"])
#expect(await api.calls == 1)
}
@Test func aLateRefreshCannotRestoreASignedOutSession() async throws {
let api = GatedAuthAPI()
let expired = AuthToken(refreshToken: "old", expiresAt: .distantPast)
let store = TokenStore(api: api, token: expired)
let pending = Task { try await store.validToken(at: .now) }
await api.waitForFirstCall()
await store.replaceSession(with: nil)
await api.release()
await #expect(throws: SessionError.sessionChanged) { try await pending.value }
await #expect(throws: SessionError.signedOut) { try await store.validToken(at: .now) }
}The first test does not need to know when the second and third callers arrive, and that is the point. A caller that arrives during the flight joins it. A caller that arrives after the commit finds a valid token. Either way, the server sees one refresh. An invariant that holds under every arrival order is one you can test without guessing at the scheduler.
Point the same test at NaiveTokenStore and it does not pass. Every caller that arrives while the first refresh is suspended starts its own, and one that arrives after release() waits on a gate nobody opens, so give the suite a .timeLimit trait before you try it. Keep that failing version in mind as a reviewer: it is what most actor code looks like before someone asks what each await invalidates.
What to ask of your own code
- For each actor method, which decision was made before an
await, and what could invalidate it before the commit? - Is shared work published before the first suspension, so a second caller can join it?
- After every suspension, is the session, account, or selection checked again before writing?
- Does one caller’s cancellation cancel work that other callers still need?
- Which decisions belong to the server, however carefully the client serializes them?
An actor guarantees that only one caller is inside at a time. It never promised that the caller inside is acting on current facts. That promise has to be written by whoever owns the work.
References
- The Swift Programming Language: Concurrency
- SE-0306: Actors (see actor reentrancy)
- OAuth 2.0 Security Best Current Practice: refresh token rotation
Related editions
- Edition 15 · The Task Is Not the Unit of Work
- Edition 18 · Your App Is Showing the Truth. Just Not the Current One.
- Edition 20 · The Work Is Cancelled. The Cleanup Isn’t.
If this edition sharpened your next review, you can buy me a coffee.