The flight was cancelled at 14:02. The app said so. Thirty seconds later, it said the flight was confirmed again.
Nothing failed. Both requests returned 200. Both responses decoded. Every write went through an actor, the Thread Sanitizer was silent, and Swift 6 strict concurrency compiled without a warning. A request that had been stuck on a slow connection simply arrived last, carrying revision 41, and replaced revision 42.
This is the bug I look for first in a data layer that has just been migrated to Swift concurrency, because the migration makes it harder to see. The code looks safe, and in the sense that the compiler checks, it is. An actor answers one question: who may touch this state right now? It is silent on the question the passenger cares about: is this response still allowed to change what I see?
The second question has an owner, and it is not the network. It is the authority that committed the fact.
Three meanings of “latest”
When a team says “we always show the latest data,” it is usually saying one of three things without noticing which.
- The latest request started. This is user intent. A search field cares about it: only the results for the text on screen now are worth showing.
- The latest response received. This is arrival order, and it is an accident. Two requests sent 50 ms apart from a phone moving between Wi-Fi and cellular can arrive in either order.
- The latest revision committed by the authority. This is the server’s own ordering of the facts. A reservation, a balance, or a shared document needs this one.
Most stale-screen bugs come from implementing the second while believing you implemented the third. self.flight = try await api.flight(id) means “latest response received.” Nothing more.
Timestamps do not rescue it. Date() on the device records when the device noticed something, on a clock the user can change. A server updatedAt is better, but two writes in the same millisecond tie, and timestamps from different servers are only as ordered as their clocks.
So the rule is written before the mechanism:
Within one account, one entity, and one revision epoch, a lower authoritative revision must never replace a higher one.
The epoch is there because revision sequences restart in real systems. A reservation is deleted and re-created; a backend is migrated; a cache is rebuilt from an export. Revision 1 of the new reservation is newer than revision 900 of the old one, and the only way to know it is an identity that changes when the sequence restarts.
Make acceptance a single step
The smallest store that enforces the rule assumes the server sends a monotonically increasing revision per entity and never changes a payload without changing the revision.
import Foundation
struct FlightSnapshot: Equatable, Sendable {
let accountID: UUID
let flightID: UUID
let epoch: UUID
let revision: UInt64
let status: Status
enum Status: String, Sendable {
case confirmed, delayed, cancelled
}
}
enum Acceptance: Equatable, Sendable {
case applied, duplicate, stale, wrongScope, conflictingRevision
}
actor FlightStore {
private let accountID: UUID
private let flightID: UUID
private let epoch: UUID
private var current: FlightSnapshot?
init(accountID: UUID, flightID: UUID, epoch: UUID) {
self.accountID = accountID
self.flightID = flightID
self.epoch = epoch
}
func apply(_ incoming: FlightSnapshot) -> Acceptance {
guard incoming.accountID == accountID,
incoming.flightID == flightID,
incoming.epoch == epoch else { return .wrongScope }
if let current {
guard incoming.revision >= current.revision else {
return .stale
}
if incoming.revision == current.revision {
return incoming == current ? .duplicate : .conflictingRevision
}
}
current = incoming
return .applied
}
func snapshot() -> FlightSnapshot? { current }
}Three details carry the weight.
apply contains no await. Actors are reentrant: at every suspension point inside an actor method, other calls to the same actor may run. If apply read the current revision, awaited a disk write, and then assigned, a second apply could slip in between the comparison and the assignment, and you would be back to last-writer-wins. The check and the write it justifies must sit in one synchronous stretch. When I read actor code in review, this is what I read for: an await between a check and the write that depends on it.
The result is a value, not a Bool. .stale is normal on a mobile network. .wrongScope means a response for another account or entity reached this store, a routing bug you want to hear about. .conflictingRevision means two different payloads claimed the same revision: a broken server contract, a cache key that ignores a parameter, or two API versions encoding the same entity differently. Choosing whichever arrived last would bury that. Count it, log the identifiers without the payload, and refetch from the authority.
Scope is checked before order. A response for the previous account with a very high revision must not win because its number is larger.
The same rule where processes meet
The actor protects one process. If the snapshot is persisted and a widget, an app extension, or a background refresh writes to the same database, each of them has its own actor instance. The only thing they share is the database, so the database makes the decision. In SQL the rule becomes a conditional upsert, written the same way for SQLite and PostgreSQL:
INSERT INTO flight_snapshot (account_id, flight_id, epoch, revision, status)
VALUES (:account_id, :flight_id, :epoch, :revision, :status)
ON CONFLICT (account_id, flight_id) DO UPDATE
SET revision = excluded.revision,
status = excluded.status
WHERE flight_snapshot.epoch = excluded.epoch
AND flight_snapshot.revision < excluded.revision;Zero rows changed means the write was stale or belonged to another epoch. An epoch change is not something this statement should decide on its own; it is a re-creation, and the repository handles it explicitly by replacing the row inside the same transaction that learns of it.
Relevance is a different question
The user taps flight A, then flight B before A has loaded. A’s response arrives late. It is perfectly fresh for A, and it has no business on a screen showing B.
That is the first meaning of “latest,” user intent, and it needs its own token:
import Foundation
import Observation
protocol FlightLoading: Sendable {
func load(flightID: UUID) async throws -> FlightSnapshot
}
@MainActor
@Observable
final class FlightScreenModel {
private(set) var visible: FlightSnapshot?
private(set) var loadFailed = false
private let loader: any FlightLoading
private var selection: UInt64 = 0
private var loadTask: Task<Void, Never>?
init(loader: any FlightLoading) {
self.loader = loader
}
func select(flightID: UUID) {
selection += 1
let token = selection
loadTask?.cancel()
visible = nil
loadFailed = false
loadTask = Task {
do {
let snapshot = try await loader.load(flightID: flightID)
guard token == selection else { return }
visible = snapshot
} catch {
guard token == selection else { return }
loadFailed = !(error is CancellationError)
}
}
}
}The token is captured before the await and compared after it, on the main actor, in the same synchronous stretch as the assignment. It is the store’s shape, applied to another question.
The old task is cancelled and the token is still checked. Cancellation in Swift is cooperative: it sets a flag the callee may never read, and a response already decoded when the flag is set will still be delivered. Cancellation saves work. The token is what makes the screen correct.
Two things stay out of this class on purpose.
- The screen token does not gate the repository. The store is entitled to learn new facts about A after the user moved to B. If background updates are rejected because nobody is looking, the next visit to A shows old data. Relevance belongs to the presentation. Freshness belongs to the store.
- An account switch invalidates everything. Clearing a visible array on sign-out is not enough when an in-flight callback can refill it under the next account. Bump the selection, cancel the tasks, drop the subscriptions, and keep the account in the store’s scope so a late response fails
wrongScopeeven if everything else slips.
Keep a value without overstating it
A cached reservation is useful on a plane with no connectivity. It is harmful when it wears the same green “Confirmed” badge as a value fetched two seconds ago. Keep the accepted value with the moment this process accepted it, and derive what the interface may claim:
enum Freshness: Equatable, Sendable {
case current
case aging(since: Duration)
case expired
}
struct Observed<Value: Sendable>: Sendable {
let value: Value
let acceptedAt: ContinuousClock.Instant
func freshness(
now: ContinuousClock.Instant,
currentFor: Duration,
usableFor: Duration
) -> Freshness {
let age = acceptedAt.duration(to: now)
if age <= currentFor { return .current }
if age <= usableFor { return .aging(since: age) }
return .expired
}
}ContinuousClock keeps advancing while the device sleeps and ignores the user changing the date, which makes it the right measure of how long this process has held a value. It means nothing across launches, so a persisted snapshot also needs a wall-clock time, treated with suspicion after a restart: a stored date in the future means assume the worst and refresh.
The two durations are product decisions, and they differ by field. A gate assignment forty minutes before departure deserves seconds. A frequent-flyer tier can live for a day. A failed refresh should leave the last value in place and let it age, so the interface can say “last confirmed at 14:03” and stop short of “confirmed.”
Fresh is also not the same as permitted. If access to a booking was revoked, a snapshot cached one second ago is still something the user may no longer see. Authorization changes clear or re-scope the cache directly. They do not wait for an age threshold.
A local edit is an intention, not a revision
The passenger corrects the name on the booking while a refresh is in flight. The refresh returns revision 43 with the old name. Revision checks alone will overwrite the edit without hesitation.
Keep three things apart: the authoritative base (revision 43), the pending command (an ID, the new name, and the revision it was made against), and the overlay the interface renders from both. The mutation is conditional on the server: set the name if the revision is still 43. A conflict comes back as a conflict, and the app reconciles or asks. When the server accepts, its receipt carries the command ID, and only that receipt clears the pending state. A later refresh that happens to contain the same name is weaker evidence; someone else may have typed it.
An optimistic value is waiting for an answer. It should never be written into the store as if it were revision 44.
Tests that decide the order
Ordering bugs cannot be tested with Task.sleep. A sleep is slow on a fast machine, flaky on a slow one, and it encodes a guess about the scheduler. Use a loader whose responses the test releases explicitly, and drive the exact interleaving:
- revision 42 applied, then 41 offered:
.stale, stored revision still 42; - the same snapshot twice:
.duplicate; - revision 42 with a different payload:
.conflictingRevision, stored value unchanged; - a snapshot for another account with revision 999:
.wrongScope; - select A, select B, release B, release A: B stays visible;
- sign out while a request is pending, then release it: nothing becomes visible.
Assert the stored revision as well as the visible text. A test that only reads the label can pass while the ledger underneath is corrupted, and the next legitimate update is then rejected as stale.
Run the first four again against the real database with two connections. That is the test that finds a missing WHERE clause.
In production, count .stale and .conflictingRevision per endpoint. A steady trickle of stale rejections is the network being a network. A step change after a release means a new cache layer, a CDN rule, or a retry policy is replaying old responses, and it reaches a dashboard before it reaches a passenger at the gate.
What to ask of your own code
- For each piece of shared state, which of the three meanings of “latest” does the code implement, and is it the one the product needs?
- Is there an
awaitbetween any comparison and the assignment that depends on it? - Does every response carry enough identity (account, entity, epoch, revision) to be rejected safely?
- Does a second process write the same data, and if so, does the database enforce the rule?
- Can the interface tell “confirmed now” from “confirmed when we last heard”?
Thread safety decides who may write. The domain decides which facts deserve to be written. An app that gets only the first right will keep telling the truth at the wrong time.
References
- The Swift Programming Language: Concurrency
- SE-0306: Actors (see actor reentrancy)
- SQLite: UPSERT
- PostgreSQL: INSERT … ON CONFLICT
- ContinuousClock
Related editions
- Edition 16 · The Upload Finished. Did the Work?
- Edition 22 · When Actors Are Not Enough: Reentrancy and State Ownership
If this edition sharpened your next review, you can buy me a coffee.