Serial BLE Command Queue and Dispatcher for iOS
Hard · System Design · iOS Engineer · Technical Screen
Prompt
Architect a production Bluetooth Low Energy (BLE) command subsystem for an iOS companion app paired with a wearable peripheral. Multiple app features—such as interactive settings screens, workout controls, status widgets, and background sync jobs—submit commands concurrently, while the wearable protocol requires strict serial execution:
- Only one command may be active on the peripheral at any instant; a queued command must never be transmitted until every preceding command has finished.
- Once a command is written over BLE, the subsystem must suspend until either the matching reply arrives from the wearable or a per-command deadline elapses.
- Whenever a command expires without a reply, the queue must resolve that request, avoid wedging, and advance to subsequent queued commands under an explicit retry and recovery policy.
Detail a production-grade iOS design covering the public caller contract, wire framing, internal queue and state structures, concurrency synchronization, response correlation, timeout and disconnect policies, task cancellation, iOS background execution behavior, and deterministic hardware-free testing.
Scope & Expectations
- Define type-safe caller APIs, wire packet framing, and queue/in-flight state structures that cleanly separate unsolicited peripheral notifications from correlated command replies.
- Specify a lock-free or strictly serialized concurrency model that prevents overlapping writes, callback reordering, deadlocks, leaked callers, and double-resumed continuations.
- Detail timeout, idempotent retry, link-drop escalation, task cancellation, and iOS background-suspension semantics so stalled or cancelled work never corrupts subsequent responses.
- Show how abstracting BLE transport and clock scheduling enables fast, deterministic unit and fuzz tests alongside production latency and reliability telemetry.
Step-by-step walkthrough
Clarify requirements and BLE fundamentals
Before drawing boxes, let us define the Bluetooth Low Energy (BLE) terms that shape every design choice here:
- Central and peripheral: In BLE, the iPhone app is the central (the device that scans and initiates connections) and the wearable strap is the peripheral (the accessory that advertises and accepts connections).
- GATT service and characteristic: GATT (Generic Attribute Profile) organizes data on the wearable into characteristics—small typed data slots identified by UUIDs. Our app sends commands by writing bytes to a command characteristic and receives answers via notifications (asynchronous byte pushes from the wearable) on a response characteristic.
- ATT MTU: MTU (Maximum Transmission Unit) is the maximum packet size at the Attribute Protocol (ATT) layer. Each notification or write uses a 3-byte ATT header, so the default 23-byte MTU leaves
23 - 3 = 20payload bytes per packet unless iOS and the wearable negotiate a larger MTU (commonly 185–247 bytes on modern iPhones). - Supervision timeout: If the user walks away from the phone, the radio link does not report a disconnect instantaneously; iOS waits for the supervision timeout (typically 2–6 seconds per Apple's accessory guidelines) before firing a disconnect callback.
Functional requirements
- Any feature module in the app (dashboard sync, alarm settings UI, workout controls, firmware updater, background sync) can concurrently submit a typed command and
awaitits decoded result. - Strict one-at-a-time execution: At most one command is in flight on the wearable at any moment. Command
N + 1is never written until commandNhas received its matching response, failed to write, or timed out. - Once bytes go over the air, the engine suspends on that active slot until a correlated device reply arrives or its per-opcode timer expires, then advances to queued work using an explicit retry-and-escalation policy.
- Unsolicited device events (battery updates, live heart-rate notifications, button presses) flow to event subscribers and are never mistaken for command responses.
- Callers can cancel waiting or in-flight tasks; disconnects, Bluetooth power-off, and iOS background suspension all terminate or pause commands cleanly.
Non-functional requirements
- Zero deadlocks, zero leaked callers (every
asynccall resumes once), and zero double-resumed continuations (which crash iOS apps immediately). - Fully deterministic unit testing in milliseconds without physical hardware, Bluetooth permissions, or real wall-clock sleeps.
- Minimal CPU and memory overhead so the BLE radio, not app concurrency bookkeeping, is the only bottleneck.
Assumptions stated up front
- Protocol ownership: Because the same company builds both the iOS app and the wearable firmware, each request carries a sequence number (
seq) that the firmware echoes in its response. We also cover a fallback for legacy firmware withoutseq. - Target platform: iOS 16+ with Swift structured concurrency (
async/await,Duration,ContinuousClock) and thebluetooth-centralbackground mode enabled so a screenless wearable can sync in the user's pocket. - Per-device isolation: One
BLECommandHandlerinstance manages one connected wearable peripheral; supporting multiple paired accessories simply instantiates one handler per peripheral.
Back-of-the-envelope numbers
Planning numbers turn vague instincts about timeouts, queue bounds, and data sync into concrete arithmetic (to be validated with telemetry on real phones and firmware):
BLE radio link connection interval 30 ms typical (Apple guidelines require >= 15 ms) 1 command round trip write (1 interval) + firmware work + notify (1-2 intervals) -> ~50-150 ms per simple control command (~100 ms median) serial command ceiling 1 / 0.10 s = ~10 commands/s maximum payload bytes per packet 23 B default MTU - 3 B ATT header = 20 B minimum; 182-244 B after MTU negotiation (query at runtime via peripheral.maximumWriteValueLength(for:)) disconnect detection lag 2-6 s supervision timeout (4 s typical) App workload screen-open burst 5-10 control commands (battery, firmware version, alarm status, user settings) -> 0.5-1.5 s to drain serially periodic background sync ~10 control commands every 15 min; megabytes of sensor history MUST stream via notifications, NOT 1 command/chunk Timeouts and bounds default response timeout 2 s (~6x an assumed 300 ms p99 round trip) slow hardware commands 30-60 s (for example flash erase), set per command type default queue wait deadline 10 s before a command even gets onto the wire max queued commands 64 -> 64 x 150 ms = ~9.6 s worst-case wait (~10 s deadline) memory footprint 64 records x ~256 B = ~16 KB (negligible)Three design lessons fall directly out of these numbers:
- 10 commands/s is fine for settings, fatal for bulk sensor sync. Downloading 1 MB of overnight physiological data at 200 bytes per request/response would take
5,000commands (~500 seconds= 8+ minutes). Bulk sync must therefore be one command ("start stream from offset X") followed by windowed notification streaming. - Response timeouts fire before iOS knows the link dropped. If the wearable goes out of range at
t = 0, a 2-second command timeout fires att = 2 s, whereas iOS may not reportdidDisconnectPeripheraluntilt = 4 s. Timeout handling is our primary fault detector. - A bounded queue (64) matches our 10-second freshness window. Queueing 1,000 commands would only force users to wait minutes for stale UI actions.
- 10 commands/s is fine for settings, fatal for bulk sensor sync. Downloading 1 MB of overnight physiological data at 200 bytes per request/response would take
Public API and error contract
Feature code should never touch raw bytes, opcodes, or CoreBluetooth delegates. Instead, each command is a small value type conforming to
BLECommand, and callers use oneasync throwsmethod plus anAsyncStream(Swift's async sequence for push events) for unsolicited device notifications.Two terms in this API are crucial for correctness:
- Idempotent command: A command is idempotent if executing it twice on the wearable has the exact same effect as executing it once (for example,
GetBatteryLevelorSetLedBrightness(50)is idempotent, whereasStartWorkoutorEraseFlashSectoris not). - Unknown outcome (
outcomeUnknown): When a write times out or the radio disconnects mid-command, the phone genuinely cannot know whether the wearable received and ran the command right before the reply was lost. SurfacingoutcomeUnknown: Booltells callers of non-idempotent commands to query device state before deciding whether to retry.
public protocol BLECommand: Sendable { associatedtype Response: Sendable var opcode: UInt8 { get } var timeout: Duration { get } // max wait AFTER the command is written to BLE var isIdempotent: Bool { get } // true if safe to auto-retry once on timeout func encodePayload() -> Data func decode(_ payload: Data) throws -> Response } public enum BLECommandError: Error, Equatable { case queueFull // backpressure: 64 commands already waiting case queueDeadlineExceeded // expired in queue before ever reaching the radio case bluetoothUnavailable // Bluetooth off, unauthorized, or unsupported case timedOut(outcomeUnknown: Bool) // wearable did not answer before command.timeout case disconnected(outcomeUnknown: Bool) case deviceRejected(status: UInt8) // wearable answered, but with a firmware error code case writeFailed(description: String)// CoreBluetooth rejected the write (not delivered) case malformedResponse // payload failed validation in decode(_:) case cancelled // Swift Task was cancelled by caller } public final class BLECommandHandler: Sendable { public func send<C: BLECommand>( _ command: C, queueDeadline: Duration = .seconds(10) ) async throws -> C.Response public var events: AsyncStream<DeviceEvent> { get } } // Concrete command example: struct GetBatteryLevel: BLECommand { let opcode: UInt8 = 0x10 let timeout: Duration = .seconds(2) let isIdempotent = true func encodePayload() -> Data { Data() } func decode(_ payload: Data) throws -> UInt8 { guard payload.count == 1 else { throw BLECommandError.malformedResponse } return payload[0] } }Commands enter the FIFO (first-in, first-out) queue in the order they reach the handler. Within a single
asyncfunction, two sequentialtry await handler.send(...)calls are strictly ordered; across two independent concurrent tasks, whichever reaches the queue first runs first. Multi-step sequences that must not let another feature slip in between use a transaction API (covered in the scaling step).- Idempotent command: A command is idempotent if executing it twice on the wearable has the exact same effect as executing it once (for example,
Wire frame format and handler state
To match responses unambiguously and handle payloads larger than 20 bytes, we separate frame framing (in the transport layer) from command sequencing (in the engine).
Wire frame layout (little-endian integers)
Request frame (app -> wearable): +-----------+---------------+---------------+------------------------+ | opcode u8 | seq u16 LE | len u16 LE | payload (len bytes) | +-----------+---------------+---------------+------------------------+ Response frame (wearable -> app, opcode in 0x00..0xDF): +-----------+---------------+-----------+---------------+------------+ | opcode u8 | seq u16 LE | status u8 | len u16 LE | payload | +-----------+---------------+-----------+---------------+------------+ Unsolicited event frame (wearable -> app, opcode in 0xE0..0xFF): +-----------+---------------+------------------------+ | opcode u8 | len u16 LE | payload (len bytes) | +-----------+---------------+------------------------+- Why no extra checksum inside every packet? BLE's link layer already guards every radio packet with a 24-bit CRC (Cyclic Redundancy Check) and retransmits corrupted packets automatically while connected.
- Why 16 bits for
seq? At 10 commands/second, a 16-bit counter wraps around after65,536commands (~1.8 hours). An 8-bit counter (256values) would wrap in~25 seconds—shorter than a 30-second flash-erase timeout, risking a wrap-around collision! - Chunking and reassembly: If a 120-byte frame is sent over a 20-byte MTU link, the transport splits outgoing writes into 20-byte slices and buffers incoming notifications until
lenpayload bytes have arrived (discarding any partial buffer that stalls for more than 500 ms). ThusCommandEnginealways works on complete frames.
Internal records and engine state
A continuation (
CheckedContinuationin Swift) is a single-use callback handle that suspends anasynccaller and wakes it up when resumed. Resuming a continuation twice crashes the process; never resuming it leaks the task forever. Notice how we separate waking the caller (resumeCaller) from timing the wire slot (inFlightTimeron the engine)—that separation avoids a subtle bug when an in-flight command is cancelled!// Mutable fields are accessed ONLY on bleQueue. final class PendingCommand { let opcode: UInt8 let payload: Data let timeout: Duration let isIdempotent: Bool let queueDeadline: ContinuousClock.Instant var seq: UInt16 = 0 var attempts: Int = 0 var isCancelled: Bool = false var completion: ((Result<Data, BLECommandError>) -> Void)? // Guarantees the waiting Swift continuation is resumed at most once. func resumeCaller(_ result: Result<Data, BLECommandError>) { guard let completion else { return } self.completion = nil completion(result) } }CommandEngine state (100% confined to serial bleQueue): link disconnected | connecting | discovering | ready bluetoothAvailable Bool (false when Bluetooth is off, unauthorized, or unsupported) pending FIFO array of PendingCommand (bounded at <= 64) inFlight PendingCommand? (at most 1 command on the wire) inFlightTimer Cancellable? (response timeout timer for inFlight) nextSeq UInt16 (monotonic counter, wraps cleanly with &+=) consecutiveTimeouts Int (escalates to reconnect at 3 in a row)Crucially,
link == .readymeans four things have all finished: radio connected, GATT services discovered, characteristics discovered,setNotifyValue(true, for: responseCharacteristic)confirmed bydidUpdateNotificationStateFor, and any protocol handshake completed. Writing a command right whendidConnectfires—before notifications are enabled—would cause the wearable's fast reply to vanish silently.High-level architecture
Feature callers (Sync, Settings UI, Workout, Firmware Updater) | try await handler.send(cmd) ^ for await event in handler.events v | +------------------------------------------------------------------------+ | BLECommandHandler (Swift async/await facade) | | Creates PendingCommand, bridges CheckedContinuation + onCancel | +------------------------------------------------------------------------+ | bleQueue.async { ... } v +------------------------------------------------------------------------+ | CommandEngine (ALL state & methods run on serial DispatchQueue) | | pending FIFO (<= 64) ---> inFlight (<= 1) + inFlightTimer | | Matcher: (opcode, seq) -> clears inFlight, resumes caller, pumps | | Failure policy: single timeout -> retry/skip; 3x timeout -> recover | +------------------------------------------------------------------------+ | transport.write(frame) ^ didReceive(frame) ^ link state v | | +------------------------------------------------------------------------+ | BLETransport (protocol) | ConnectionManager | | Prod: CoreBluetoothTransport | Scan, connect, discover, | | (CBCentralManager initialized | enable notifications, | | with queue: bleQueue; MTU | handshake, backoff | | chunking + frame reassembly) | Scheduler (protocol) | | Test: FakeTransport (in-memory) | Prod: ContinuousClock + GCD | | | Test: ManualScheduler | +------------------------------------------------------------------------+ | writeValue / didUpdateValueFor v [ Wearable Firmware over BLE ]Walkthrough of one healthy command:
- UI calls
try await handler.send(GetBatteryLevel()).BLECommandHandlerwraps the request in aPendingCommand, captures aCheckedContinuation, and hops ontobleQueue. CommandEngine.enqueuechecks Bluetooth availability and the 64-item cap, appends the command topending, and callspump().pump()seeslink == .readyandinFlight == nil, pops the head command, assignsseq = 42, setsinFlight, startsinFlightTimerfor 2 seconds, and asksBLETransportto write the frame.CoreBluetoothTransportwrites the bytes and reassembles the notification reply into aFrame(opcode: 0x10, seq: 42, status: 0, payload: [87]).CommandEngine.didReceivematches(0x10, 42), cancelsinFlightTimer, clearsinFlight, resumes the caller with[87], and immediately callspump()to send item#43if one is waiting.
- UI calls
Deep dive 1: Concurrency model and strict serialization
Why share one serial
DispatchQueue(bleQueue) with CoreBluetooth? When you initializeCBCentralManager(delegate: self, queue: bleQueue), iOS guarantees that every Bluetooth event—characteristic notification, write error, disconnect, radio power change—is delivered sequentially onbleQueue. By runningCommandEngineon that exact samebleQueue, writes, responses, timers, cancellations, and disconnects execute strictly one after another with zero locks and zero event reordering.Why not use a plain Swift
actorcalled from CoreBluetooth delegate methods viaTask { await engineActor... }? Because unstructuredTaskblocks are scheduled independently and are not guaranteed to enter the actor in FIFO order:What actually happened on the radio: t = 100.0 ms didUpdateValueFor (response to seq 42 arrives!) t = 100.2 ms didDisconnectPeripheral (wearable goes out of range) Broken bridge using Task { await actor.handle(...) } per callback: Task 1 (response) created first, delayed slightly by scheduler Task 2 (disconnect) runs FIRST on actor -> fails seq 42 as disconnected! Task 1 (response) runs SECOND on actor -> dropped as unmatched! Shared serial bleQueue: Callback 1 runs to completion (completes seq 42 with valid data) Callback 2 runs next (cleanly marks link disconnected with nothing in flight)(If you prefer an
actor, you must either feed events into a singleAsyncStreamread by one loop, or on iOS 17+ bind the actor's custom executor directly tobleQueue.)Bridging
asynccallers safely (send,enqueue, andpump)Notice a subtle Swift detail in
withTaskCancellationHandler: if the calling task was already cancelled beforesendstarts, Swift invokesonCancelbefore theoperationblock dispatches ontobleQueue. Because both blocks dispatch to the serialbleQueueand sharecmd.isCancelled, whichever block runs first handles cancellation cleanly without losing the signal or double-resuming:public func send<C: BLECommand>( _ command: C, queueDeadline: Duration = .seconds(10) ) async throws -> C.Response { let cmd = PendingCommand( opcode: command.opcode, payload: command.encodePayload(), timeout: command.timeout, isIdempotent: command.isIdempotent, queueDeadline: scheduler.now.advanced(by: queueDeadline) ) let responseBytes = try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in bleQueue.async { cmd.completion = { result in continuation.resume(with: result) } self.engine.enqueue(cmd) } } } onCancel: { bleQueue.async { self.engine.cancel(cmd) } } // Decode on the caller's task so malformed payloads never stall bleQueue. return try command.decode(responseBytes) }// All methods below execute exclusively on bleQueue. func enqueue(_ cmd: PendingCommand) { if cmd.isCancelled { cmd.resumeCaller(.failure(.cancelled)) return } guard bluetoothAvailable else { cmd.resumeCaller(.failure(.bluetoothUnavailable)) return } guard pending.count < 64 else { cmd.resumeCaller(.failure(.queueFull)) return } pending.append(cmd) pump() } func pump() { while link == .ready, inFlight == nil, let cmd = pending.first { pending.removeFirst() // Drop commands that waited too long BEFORE their first send. if cmd.attempts == 0 && scheduler.now >= cmd.queueDeadline { cmd.resumeCaller(.failure(.queueDeadlineExceeded)) continue } nextSeq &+= 1 cmd.seq = nextSeq cmd.attempts += 1 inFlight = cmd let activeSeq = cmd.seq inFlightTimer = scheduler.after(cmd.timeout) { [weak self] in self?.responseTimedOut(seq: activeSeq) } transport.write(Frame.request(opcode: cmd.opcode, seq: activeSeq, payload: cmd.payload)) } }While
link != .ready(for instance, the user walked away from their phone and iOS is waiting to reconnect, which never times out on its own),pump()cannot drainpending. To avoid leaving callers suspended for hours, a 1-second repeating timer onbleQueuesweepspendingwheneverlink != .readyand fails any command whosescheduler.now >= cmd.queueDeadlinewith.queueDeadlineExceeded.Deep dive 2: Response matching, timeouts, and failure policy
Why opcode-only matching corrupts future responses Suppose screen A sends
GetSettings, it times out at2.0 s, we unblock the queue and screen B sendsGetSettingsat2.01 s, and then the wearable's slow reply to screen A arrives at2.10 s:Without seq (BUG - off-by-one corruption): t = 0.00 s Write GetSettings (for Caller A) t = 2.00 s Timeout! Fail Caller A, unblock queue t = 2.01 s Write GetSettings (for Caller B) t = 2.10 s Late reply from t=0 arrives -> matched to Caller B! (stale data!) t = 2.18 s Actual reply for Caller B arrives -> dropped or matched to Caller C! With 16-bit seq echoed by firmware (SAFE): t = 0.00 s Write GetSettings (seq = 41, Caller A) t = 2.00 s Timeout on seq = 41 -> fail Caller A, unblock queue t = 2.01 s Write GetSettings (seq = 42, Caller B) t = 2.10 s Reply (opcode = GetSettings, seq = 41) != 42 -> logged & ignored! t = 2.18 s Reply (opcode = GetSettings, seq = 42) == 42 -> completes Caller B!Matching and timeout handlers (
bleQueue)Notice how
inFlightTimercapturesactiveSeq: even if a timeout callback was already queued onbleQueuea microsecond after the valid response clearedinFlightand startedseq + 1,cmd.seq == seqrejects the stale timer safely.private func clearInFlight() -> PendingCommand? { let current = inFlight inFlight = nil inFlightTimer?.cancel() inFlightTimer = nil return current } func didReceive(_ frame: Frame) { if frame.isUnsolicitedEvent { eventContinuation.yield(DeviceEvent(frame)) return } guard let cmd = inFlight, frame.opcode == cmd.opcode, frame.seq == cmd.seq else { metrics.recordUnmatchedResponse(opcode: frame.opcode) return } _ = clearInFlight() consecutiveTimeouts = 0 if frame.status == 0 { cmd.resumeCaller(.success(frame.payload)) } else { cmd.resumeCaller(.failure(.deviceRejected(status: frame.status))) } pump() } func responseTimedOut(seq: UInt16) { guard let cmd = inFlight, cmd.seq == seq else { return } _ = clearInFlight() consecutiveTimeouts += 1 // 3 consecutive timeouts means the radio link or firmware state machine is wedged. if consecutiveTimeouts >= 3 { consecutiveTimeouts = 0 link = .connecting cmd.resumeCaller(.failure(.timedOut(outcomeUnknown: true))) connectionManager.forceReconnect() return } // Retry at most once, ONLY for idempotent, uncancelled commands with budget left. if cmd.isIdempotent && cmd.attempts < 2 && !cmd.isCancelled && scheduler.now < cmd.queueDeadline { pending.insert(cmd, at: 0) // keep head-of-line order, pump assigns a fresh seq } else { cmd.resumeCaller(.failure(.timedOut(outcomeUnknown: true))) } pump() }Explicit failure policy summary
Fault Effect on inFlightEffect on remaining pendingqueue1st timeout on idempotent command Re-inserted at index 0, retried once with new seqWaits one extra round trip Timeout on non-idempotent (or 2nd attempt) Fails with .timedOut(outcomeUnknown: true)Immediately unblocks and sends next command 3 consecutive timeouts Fails with .timedOut(outcomeUnknown: true)Queue pauses ( link = .connecting); reconnect tears down & re-handshakesFirmware status != 0Fails with .deviceRejected(status)Continues immediately CoreBluetooth write error Fails immediately with .writeFailed(known not run)Continues immediately Unexpected BLE disconnect Fails with .disconnected(outcomeUnknown: true)Waits for auto-reconnect (swept by queueDeadlinetimer)Bluetooth powered off / unauthorized Fails with .bluetoothUnavailableEntire queue drained with .bluetoothUnavailableWhat if legacy firmware has no
seqfield? Matching falls back toframe.opcode == cmd.opcode, and after any timeout the engine injects an internalEchoPing(random4ByteNonce)command at the head of the queue before allowing normal commands to proceed, discarding every incoming response until the exact 4-byte nonce comes back. That costs one extra round trip (~100 ms) per timeout to flush late replies safely.Deep dive 3: Cancellation, iOS background lifecycle, and disconnects
The two cases of task cancellation—and a classic deadlock trap Cancelling a command waiting in
pendingis easy: remove it from the array so it never touches the radio. CancellinginFlightis trickier: the bytes are already on the wearable!If we cleared
inFlight = nilimmediately on cancel and sent the next command, the wearable would receive a second command while still executing the first—violating our core protocol invariant. Equally important, if waking the caller accidentally cancelledinFlightTimer, and the wearable never replied,inFlightwould stay occupied forever, deadlocking the entire queue! That is whyresumeCalleronly wakes the caller whileinFlightandinFlightTimerstay alive until the wearable replies or times out:func cancel(_ cmd: PendingCommand) { cmd.isCancelled = true if let idx = pending.firstIndex(where: { $0 === cmd }) { pending.remove(at: idx) cmd.resumeCaller(.failure(.cancelled)) } else if inFlight === cmd { // Wake the caller right now so UI navigation feels instant, // while keeping inFlight AND inFlightTimer active until the device // replies (ignored by resumeCaller) or times out and calls pump(). cmd.resumeCaller(.failure(.cancelled)) } }Disconnects, Bluetooth state, and iOS background rules
didDisconnectPeripheral: ClearinFlight+inFlightTimer, resume that caller with.disconnected(outcomeUnknown: true), setlink = .disconnected, keeppending(guarded by the 1-secondqueueDeadlinesweep), and immediately callcentralManager.connect(peripheral)—on iOS,connectnever times out and automatically reconnects whenever the wearable comes back in range. Exponential backoff (1 s, 2 s, 4 s, ... max 30 s) is used only whendidFailToConnector post-connect GATT discovery/handshake fails.- iOS background execution (
bluetooth-central): Between BLE callbacks, iOS suspends the app process in the background, which freezes dispatch timers. When the next BLE notification or supervision-timeout disconnect wakes the app (~10 seconds of execution budget per wake),ContinuousClock.nowhas still advanced monotonically during sleep. Therefore, at the top of everybleQueuecallback, the engine first checks whetherinFlight's deadline orpendingqueue deadlines have already elapsed before processing new work. Multi-command background sync jobs also acquire aUIApplication.beginBackgroundTaskassertion so iOS keeps the process awake across consecutive round trips. - App termination and state restoration: With
CBCentralManagerOptionRestoreIdentifierKey, iOS relaunches a background-evicted app when the wearable sends an event. Because all Swift continuations died with the old process,BLECommandHandlerremains stateless across restarts; durable multi-step workflows (like "sync sleep log, then advance device pointer") live in a persistent job coordinator above the handler that re-submits commands on relaunch.
Scaling, observability, and deterministic validation
Scaling a 10-command/second radio pipe
- Windowed streaming for bulk data: Syncing sensor logs sends one
StartSync(fromOffset)command; the wearable streams numbered notification packets in 4 KB windows, and the app sendsAckWindow(offset)commands so urgent UI commands can interleave cleanly between windows without breaking FIFO order. - Multi-command transactions: Operations like
BeginConfig -> SetAlarm -> CommitConfigmust not interleave with background battery checks.handler.transaction { tx in ... }places a single slot inpending; once at the head, onlytx.send(...)commands bypass the outer queue until the closure returns or a 10-second transaction guard expires. - Read coalescing: Five UI widgets requesting
GetBatteryLevelsimultaneously while oneGetBatteryLevelis still sitting inpendingcan attach their continuations to that single queuedPendingCommandinstead of sending five identical radio reads.
Production observability
Log structured metrics per
(opcode, firmware_version): round-trip latency (p50,p95,p99), queue wait time, timeout rate, retry success rate,outcomeUnknownrate, and unmatched response count (a spike in unmatched responses arriving right after timeouts proves the per-opcode timeout is too tight).Layered validation without hardware
- Deterministic unit tests (
FakeTransport+ManualScheduler): Because both CoreBluetooth and time are behind tiny protocols, unit tests advance a virtual clock by2.0 secondsin microseconds and script exact byte deliveries:- Strict serialization: Enqueue A and B concurrently; assert
FakeTransport.writes.count == 1until A's response frame is injected, after which B is written immediately. - Stale reply immunity: Enqueue A (
seq = 1), advance virtual clock+2sto trigger timeout (non-idempotent), observe B (seq = 2) written, inject late reply forseq = 1, assert B stays suspended until replyseq = 2arrives. - Cancel while in flight: Cancel A while in flight; assert A throws
.cancelledimmediately, assert B is not written yet, advance virtual clock+2s, assert B is now written (catching the timer-cancellation deadlock!). - 3-timeout escalation, MTU multi-packet reassembly, and disconnected queue-deadline sweeps.
- Strict serialization: Enqueue A and B concurrently; assert
- Randomized concurrency fuzzing: Spawn 1,000 concurrent tasks in a
TaskGroupwith random cancellations, random virtual delays, and 10% simulated packet drops. Assert three hard invariants:maxConcurrentOnDevice <= 1, everysendreturned or threw once (0leaks,0double resumes), and single-task sequential calls arrived on the fake wire in order. - Thread Sanitizer (TSan) + hardware-in-the-loop: Run CI tests with TSan enabled and
dispatchPrecondition(condition: .onQueue(bleQueue))assertions insideCommandEngine, followed by soak tests against debug firmware configured to inject delayed, dropped, and duplicate BLE notifications.
- Windowed streaming for bulk data: Syncing sensor logs sends one
Intuition & how it works
Think of the BLE command handler as a single-lane drive-thru window with numbered order tickets. Inside the app, many passengers (the dashboard screen, alarm settings, workout controls, and a background sync task) shout orders at the same time. Instead of letting everyone yell into the speaker at once, a single clerk lines every order up in one queue, stamps ticket #42 on the front order, speaks only #42 into the radio, and starts a 2-second stopwatch. Order #43 waits behind the window until #42 either comes back with matching ticket #42 or the stopwatch rings—and if bag #42 comes out late after the clerk already moved on to #43, the ticket number immediately reveals it belongs to the expired order so #43 never receives the wrong data.
The naive approach—calling CoreBluetooth's peripheral.writeValue(...) directly from each screen and listening to didUpdateValueFor delegates—breaks immediately under concurrency and flaky radio links. CoreBluetooth only queues raw radio packet writes; it knows nothing about waiting for the wearable's application-level reply before sending the next command, so two screens overwrite each other on the firmware. Worse, matching replies by command type alone shifts every subsequent caller's response off by one after a single timeout, and spawning unstructured Task { ... } blocks inside Bluetooth callbacks can reorder a valid response behind a disconnect event.
Here is a tiny 3-command trace showing how the queue, sequence numbers, and response timer work together on a single serial queue (bleQueue):
1. UI enqueues GetBattery (idempotent) and StartWorkout (non-idempotent) at t = 0.0 s.
-> GetBattery pops immediately as inFlight (seq = 1, timer = 2.0 s); StartWorkout waits in pending.
2. Wearable replies (opcode = GetBattery, seq = 1) at t = 0.08 s.
-> Matches (GetBattery, 1)! Timer cancelled, UI gets 87%, StartWorkout pops as inFlight (seq = 2).
3. StartWorkout receives no reply by t = 2.08 s; UI then enqueues GetSettings at t = 2.09 s.
-> Timer for seq = 2 fires: StartWorkout is non-idempotent, so it fails with
timedOut(outcomeUnknown: true) without retrying; GetSettings pops as inFlight (seq = 3).
-> If a late reply for seq = 2 arrives at t = 2.20 s, seq 2 != 3, so it is safely ignored.
Key trade-offs
- Shared serial
DispatchQueuevs. Swiftactorvs. locks: Passing the same serialDispatchQueue(bleQueue) toCBCentralManagerand running allCommandEnginestate transitions on it keeps radio callbacks, timers, and writes in exact arrival order with zero locks. A Swiftactorprovides compiler-enforced actor isolation (a guarantee that only one task mutates the actor's properties at a time), but wrapping each delegate callback inTask { await actor.handle(...) }can reorder a response and a disconnect unless routed through a single orderedAsyncStreamor a custom executor on iOS 17+. ManualNSLocksynchronization scatters concurrency invariants across threads and risks deadlocks when resuming continuations. - 16-bit sequence numbers (
seq) vs. opcode-only matching: Adding a 2-byteseqechoed by the wearable requires firmware cooperation, and in return makes late or duplicate responses completely harmless so the queue can unblock immediately after a timeout. Withoutseqon legacy firmware, unblocking safely after a timeout requires injecting a nonce-echo ping command and discarding responses until the nonce returns, costing an extra ~100 ms round trip on every timeout. - Unblock after one timeout vs. reconnect after three: Failing a single timed-out command and moving on keeps the UI responsive when busy firmware drops one packet, whereas three consecutive timeouts (~6 seconds total) strongly indicate a wedged firmware parser or dead radio link where tearing down and reconnecting resets both ends cleanly.
- Auto-retry only idempotent commands once vs. retrying everything: Automatically re-sending an idempotent read (
GetBatteryLevel) once at the head of the queue hides transient BLE hiccups from users, while refusing to auto-retry non-idempotent commands (StartWorkout) prevents accidental double execution and lets callers inspectoutcomeUnknown: trueto check device state first. - Strict FIFO queue with transactions vs. priority queues: Priority queues let UI taps jump ahead of background sync commands, directly violating the requirement that no command is sent before earlier commands finish. Keeping individual background commands short (~100 ms) and providing an explicit
transactionwrapper for multi-step sequences bounds UI wait times without breaking ordering guarantees. - In-memory command queue vs. persistent disk queue: Persisting raw BLE commands to SQLite across app termination looks tempting, but every caller's suspended Swift continuation dies when iOS terminates the process, and blindly replaying stale hardware commands minutes later is unsafe. Keeping the handler's queue in memory while storing high-level idempotent sync jobs in a coordinator layer above it separates concerns cleanly.
Common mistakes
- Assuming CoreBluetooth serializes request/response pairs: CoreBluetooth's internal write queue only serializes outgoing ATT packet writes, so command 2 goes out over the air long before command 1's notification comes back unless your engine gates on
inFlight == nil. - Cancelling the response timer when cancelling an in-flight caller: If task cancellation wakes the caller and stops the response timer while keeping
inFlightset to protect the device from overlapping commands, a dropped firmware reply leavesinFlightstuck non-nil forever and deadlocks the entire queue. Always separate waking the caller (resumeCaller) from clearing the wire timer (inFlightTimer). - Untagged timeout timers: If a timer callback does not verify
inFlight?.seq == expectedSeqonbleQueue, a timer that fires right after command 1 finished will mistakenly fail command 2. - Sending commands inside
didConnectbefore enabling notifications: Writing to the command characteristic before GATT service discovery,setNotifyValue(true, ...), anddidUpdateNotificationStateForcomplete causes the wearable's reply to be dropped before iOS is subscribed. - Relying on dispatch timers while suspended in the background: Even with
bluetooth-centralbackground mode, iOS suspends the process between BLE events and pauses timers, so every wake-up callback must compare deadlines againstContinuousClock.now(a monotonic clock that keeps counting while the phone sleeps). - Checking queue deadlines only inside
pump(): BecausecentralManager.connecton iOS waits indefinitely when a wearable is out of range,pump()never runs while disconnected; without a periodic sweep whilelink != .ready, callers wait far past their 10-secondqueueDeadline.
Follow-up questions
- How would you upload megabytes of recorded physiological sensor logs from the wearable without starving interactive UI commands for minutes? Do not send thousands of tiny request/response commands at 10 commands/second. Instead, send one
StartSync(fromOffset)command and let the wearable stream data via back-to-back BLE notifications in small windows (such as 4 KB per window), with the app sending a shortAckWindow(nextOffset)command after each window. Making each window acknowledgement a normal command lets urgent UI commands (like silencing an alarm) slip naturally between 4 KB windows while preserving strict one-command-at-a-time execution on the wire, and storingnextOffsetmakes interrupted syncs resumable after a disconnect. - Suppose a next-generation wearable firmware upgrades its protocol to permit up to four simultaneous commands in flight. How would your engine evolve? Replace
inFlight: PendingCommand?andinFlightTimer: Cancellable?with a dictionaryinFlightBySeq: [UInt16: InFlightSlot]capped atmaxWindow = 4, where each slot owns its ownPendingCommandand timeout timer, and changepump()'s condition frominFlight == niltoinFlightBySeq.count < maxWindow. Because our wire frame already echoesseq, response matching (inFlightBySeq[frame.seq]) works out of the box even when the wearable finishes fast commands out of order. However, callers that rely on command A's side effect taking place before command B starts must now explicitlyawaitA before calling B or usehandler.transactionto temporarily set an exclusive barrier. - How would you calibrate per-opcode timeout thresholds in the field and tell apart a tight timeout setting from a firmware hang after an over-the-air update? Seed initial timeouts at roughly 4–6x the
p99round-trip latency measured on the oldest supported iPhone under weak RSSI (signal strength), such as 2 seconds for fast reads and 30–60 seconds for flash erases. In production, log round-trip histograms, timeout rates, and unmatched late responses sliced by(opcode, firmware_version). A spike in unmatched responses arriving 100–500 ms after timeouts tells you the timeout threshold is too tight for legitimate slow work, whereas rising 3-in-a-row reconnects with zero late responses points to a firmware hang or dropped notification bug in that release.
Follow-up questions
- How would you upload megabytes of recorded physiological sensor logs from the wearable without starving interactive UI commands for minutes?
- Suppose a next-generation wearable firmware upgrades its protocol to permit up to four simultaneous commands in flight. How would your engine evolve?
- How would you calibrate per-opcode timeout thresholds in the field and tell apart a tight timeout setting from a firmware hang after an over-the-air update?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System