A listener starts a playlist on the walk to the station. The music begins. A second later the player shows an error banner with a Retry button.
The music is still playing.
The request that failed was the one reporting "playback started" to an analytics endpoint. Somewhere in the view model, one error property is shared by everything the Play action does, so a failed event upload was given authority over the player's interface. The listener now has to guess what Retry will do: restart the song, charge them twice for something, or fix a problem they cannot hear.
When I review a player, I start with that button. What operation does it repeat, and why is this person the one who has to recover it? If nobody can answer, the failure has been routed to the wrong owner.
How a telemetry call gets authority over playback
Nobody decides that analytics should be able to stop the music. It happens through the shape of the code. The most common version looks reasonable in a diff:
import Foundation
struct LegacyServices {
var checkEntitlement: @Sendable (String) async throws -> Void
var prepareMedia: @Sendable (String) async throws -> Void
var reportStarted: @Sendable (String) async throws -> Void
}
func legacyPlay(trackID: String, services: LegacyServices) async throws {
async let entitlement: Void = services.checkEntitlement(trackID)
async let media: Void = services.prepareMedia(trackID)
async let report: Void = services.reportStarted(trackID)
_ = try await (entitlement, media, report)
}Three async let bindings look like three independent pieces of work. In structured concurrency they are siblings under one parent that share one result: if the report throws, legacyPlay throws, and the caller treats the whole Play action as failed even though entitlement and media both succeeded. Written as a withThrowingTaskGroup, it gets worse, because the first child to fail actively cancels its siblings, so a 503 from the analytics endpoint can cancel media preparation that was still in flight. The sequential version has the same outcome with less ceremony: try await report() one line above player.play() means the player never starts.
Structured concurrency is doing its job here. It assumes that work started together shares one fate unless you say otherwise. The mistake is upstream: the code never stated which of these operations the product depends on.
Write the dependency table first
Before adding types, I write down what each piece of work is allowed to do to playback:
| Work | May block playback? | Who recovers a failure |
|---|---|---|
| Entitlement check | Yes, under the access policy | Playback coordinator, with a message the listener can act on |
| Media preparation | Yes | Playback coordinator |
| Product telemetry | No | Delivery worker, silently |
| Contractual play accounting | Decided by the contract | A domain service with an explicit policy for local failure |
The last row is there to stop the discussion from collapsing into "analytics is optional". A royalty report or an ad-impression record may be called analytics in the codebase while being a contractual obligation. If the business says every play must be counted, that is a different design (covered below), and calling the request "tracking" does not change it.
The table also replaces a rule I see teams adopt after being burned once: "wrap everything non-critical in a detached task". That hides the failure without giving it an owner.
Give each process its own state and identity
Playback, event creation, and event delivery are three processes with three lifetimes. A view model may present all of them; a single Boolean or error field must not merge them.
struct PlaybackSessionID: Hashable, Codable, Sendable {
let rawValue: UUID
}
struct PlaybackEvent: Codable, Equatable, Sendable {
enum Kind: String, Codable, Sendable {
case requested, started, completed
}
let id: UUID
let accountID: UUID
let sessionID: PlaybackSessionID
let trackID: String
let kind: Kind
let observedAt: Date
}
enum PlaybackState: Equatable, Sendable {
case idle
case preparing(PlaybackSessionID)
case playing(PlaybackSessionID)
case interrupted(PlaybackSessionID)
case failed(PlaybackSessionID, message: String)
var sessionID: PlaybackSessionID? {
switch self {
case .idle: nil
case .preparing(let id), .playing(let id),
.interrupted(let id), .failed(let id, _): id
}
}
}Two identities matter. The session ID is new every time the listener presses Play, even for the same track on repeat, so "played twice" and "reported twice" stay distinguishable. The event ID is created once, when the event is observed, and survives every retry. Neither should be derived from the track ID alone.
A coordinator where the types carry the policy
Now the Play action can state its dependencies in its signatures:
import Observation
protocol EntitlementChecking: Sendable {
func canPlay(trackID: String, accountID: UUID) async throws -> Bool
}
protocol MediaPreparing: Sendable {
func prepare(trackID: String) async throws
}
protocol EventRecording: Sendable {
func record(_ event: PlaybackEvent) async
}
@MainActor
@Observable
final class PlaybackCoordinator {
private(set) var state: PlaybackState = .idle
private let accountID: UUID
private let entitlements: any EntitlementChecking
private let media: any MediaPreparing
private let events: any EventRecording
init(
accountID: UUID,
entitlements: any EntitlementChecking,
media: any MediaPreparing,
events: any EventRecording
) {
self.accountID = accountID
self.entitlements = entitlements
self.media = media
self.events = events
}
func play(trackID: String) async {
let session = PlaybackSessionID(rawValue: UUID())
state = .preparing(session)
await emit(.requested, session: session, trackID: trackID)
do {
guard try await entitlements.canPlay(
trackID: trackID, accountID: accountID
) else {
finish(session, with: .failed(
session, message: "This track isn't included in your plan."
))
return
}
try await media.prepare(trackID: trackID)
} catch {
finish(session, with: .failed(
session, message: "We couldn't load this track."
))
return
}
guard state.sessionID == session else { return }
state = .playing(session)
await emit(.started, session: session, trackID: trackID)
}
private func finish(_ session: PlaybackSessionID, with newState: PlaybackState) {
guard state.sessionID == session else { return }
state = newState
}
private func emit(
_ kind: PlaybackEvent.Kind,
session: PlaybackSessionID,
trackID: String
) async {
await events.record(PlaybackEvent(
id: UUID(), accountID: accountID, sessionID: session,
trackID: trackID, kind: kind, observedAt: Date()
))
}
}EventRecording.record is async and does not throw. That one missing keyword is the dependency table expressed in the type system: there is no catch through which an event failure could reach the player's state, and a future contributor cannot add one by accident. Recording is a local hand-off to an outbox, not a network call, so awaiting it costs an actor hop.
The other thing to notice is state.sessionID == session after every suspension. If the listener skips to another track while the first is preparing, the first call's continuation must not flip the state to .playing for a session that is no longer current. I cancel superseded work where I can, and I still check, because cancellation is cooperative and may arrive after the result.
Translating AVPlayer honestly
These states are domain values. An adapter has to translate what AVPlayer reports into transitions for the current session, and two details routinely go wrong.
timeControlStatus has three values: .paused, .waitingToPlayAtSpecifiedRate, and .playing. A stall on a weak connection moves .playing → .waiting → .playing. If "started" is emitted on every transition into .playing, one listen on a train produces a dozen start events. Decide what the event means (play requested, first audio rendered, thirty seconds elapsed, completed) and emit a start once per session, however many times the player rebuffers. .playing also means the player is advancing its timeline; it does not prove a person heard anything with the volume at zero.
Item notifications need an identity check as well. AVPlayerItem.didPlayToEndTimeNotification for the previous item can be delivered after you replaced it. Observe with the specific item as the notification's object and compare it with the session's item before ending anything. Removing the observer is cleanup. Validating which item the callback belongs to is what keeps the old track's ending from stopping the new one.
The outbox: bounded and account-scoped
A Task {} moves work off the current path, but it dies with the process. Events that deserve retry need to be written somewhere first. The kernel of an outbox is small:
enum DeliveryOutcome: Sendable {
case acknowledged
case retryLater
case rejected
}
actor EventOutbox: EventRecording {
private var pending: [PlaybackEvent] = []
private var attempts: [UUID: Int] = [:]
private(set) var droppedCount = 0
private let capacity: Int
private let maximumAttempts: Int
init(capacity: Int, maximumAttempts: Int) {
self.capacity = capacity
self.maximumAttempts = maximumAttempts
}
func record(_ event: PlaybackEvent) {
guard !pending.contains(where: { $0.id == event.id }) else { return }
if pending.count >= capacity {
let evicted = pending.removeFirst()
attempts[evicted.id] = nil
droppedCount += 1
}
pending.append(event)
}
func batch(for accountID: UUID, limit: Int) -> [PlaybackEvent] {
Array(pending.lazy.filter { $0.accountID == accountID }.prefix(limit))
}
func resolve(_ eventID: UUID, as outcome: DeliveryOutcome) {
switch outcome {
case .acknowledged:
remove(eventID)
case .rejected:
remove(eventID)
droppedCount += 1
case .retryLater:
let count = attempts[eventID, default: 0] + 1
if count >= maximumAttempts {
remove(eventID)
droppedCount += 1
} else {
attempts[eventID] = count
}
}
}
func purge(accountID: UUID) {
let removed = pending.filter { $0.accountID == accountID }
pending.removeAll { $0.accountID == accountID }
for event in removed { attempts[event.id] = nil }
}
var oldestPendingDate: Date? { pending.first?.observedAt }
private func remove(_ eventID: UUID) {
pending.removeAll { $0.id == eventID }
attempts[eventID] = nil
}
}This version is in memory so the rules are readable. A production outbox stores the same rows in SQLite or a file and keeps the same four properties:
- Bounded. A phone that is offline for a week must not accumulate events without limit. When the cap is reached something is evicted, and the eviction is counted so the loss can be reported.
- Resolved per event. A worker sends a batch and resolves each event separately. One malformed record that the server rejects with a 400 must not sit at the head of the queue forever, blocking everything behind it while the HTTP dashboard shows "requests succeeding".
- Retry is different from rejection. A timeout or a 503 is
retryLater. A 400 or a 410 isrejectedand will never succeed; retrying it burns battery. - Scoped to an account. Every record carries the account it was observed under. Sign-out purges or parks that account's records according to the documented consent policy. The next person to sign in must never have the previous user's plays delivered under their token.
The worker removes an event only after the receiver accepts responsibility for it. If the acknowledgement is lost, the same ID and the same payload go out again, which means the server has to make that harmless. An Idempotency-Key header does nothing by itself: the server must record the ID in the same transaction as the effect, keep it for a defined window, and reject a known ID that arrives with different content.
Background execution helps drain the queue, but BGTaskScheduler gives you an opportunity whose timing you do not control. Drain on foreground as well, and design the receiver to tolerate gaps and late arrivals.
When every play must be counted
If the contract says every play is reported, an outbox alone will not deliver that. A player transition and a disk write cannot be made one atomic transaction; the process can die between them. The usual answer is to invert the order for that class of event: acquire a server-issued play token before starting (which makes it a blocking dependency, on purpose, with its own row in the table), or write the intent durably before calling play() and reconcile on the next launch. Both have a cost the product has to accept in writing. What I push back on is the middle position, where the code treats the event as optional and the business believes it is guaranteed.
Keep the failure visible to the team
Isolating a failure from the listener is half of the work. The other half is that someone still finds out.
Monitor the age of the oldest pending event and the dropped and rejected counts. HTTP success rate is a poor signal here: a worker can report healthy requests for hours while one poisoned record or an expired token prevents anything from leaving the device. Tie session and event identifiers together in diagnostics so an investigator can tell "event never created" from "local write failed", "waiting to retry", and "receiver accepted it", using identifiers that are not personal data and logs with bounded retention.
That is the difference between isolating a failure and swallowing it. The product stays usable, and the failure still has an owner who is told about it.
Tests that assert both sides
The first test is the one from the opening: entitlement passes, media prepares, the recorder fails every time. Assert that the state is .playing and that the event is still pending for retry.
Then the cases that find real bugs:
- acknowledgement lost after the server accepted: the retry carries the same event ID;
- outbox at capacity: oldest evicted,
droppedCountincremented, playback unaffected; - sign-out with pending events, then sign-in as another account: nothing from the first account is in the next batch;
- skip to track B while A is preparing: A's completion does not change the state;
- five rebuffer cycles from a fake player: exactly one
startedevent.
Unit tests of an enum will not tell you how the audio session behaves. The device pass needs a phone call during playback, a Bluetooth route change, a locked screen, and an hour of continuous play.
What to ask of your own player
- For each request the Play action makes, is there a written answer to "may this block playback"?
- Does any optional work share a throwing scope (
async let, task group, sequentialtry) with required work? - Can a late completion for a previous session change the current state?
- Is the outbox bounded, per-event, and scoped to an account?
- Which metric would tell you that events stopped leaving devices three hours ago?
The next analytics request will fail; that is certain on a mobile network. The song continues, delivery follows its own recovery policy, and the listener never sees a Retry button for something they did not ask for.
References
- AVPlayer.timeControlStatus
- AVPlayer.reasonForWaitingToPlay
- Handling audio interruptions
- SE-0317: async let bindings
- BGTaskScheduler
Related editions
- Edition 23 · Your App Has More States Than Your Model Admits
- Edition 27 · A Fold Shouldn’t Restart Playback
- Edition 20 · The Work Is Cancelled. The Cleanup Isn’t.
If this edition sharpened your next review, you can buy me a coffee.