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

  1. 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 = 20 payload 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 await its decoded result.
    • Strict one-at-a-time execution: At most one command is in flight on the wearable at any moment. Command N + 1 is never written until command N has 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 async call 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 without seq.
    • Target platform: iOS 16+ with Swift structured concurrency (async/await, Duration, ContinuousClock) and the bluetooth-central background mode enabled so a screenless wearable can sync in the user's pocket.
    • Per-device isolation: One BLECommandHandler instance manages one connected wearable peripheral; supporting multiple paired accessories simply instantiates one handler per peripheral.
  2. 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:

    1. 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,000 commands (~500 seconds = 8+ minutes). Bulk sync must therefore be one command ("start stream from offset X") followed by windowed notification streaming.
    2. 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 at t = 2 s, whereas iOS may not report didDisconnectPeripheral until t = 4 s. Timeout handling is our primary fault detector.
    3. 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.
  3. 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 one async throws method plus an AsyncStream (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, GetBatteryLevel or SetLedBrightness(50) is idempotent, whereas StartWorkout or EraseFlashSector is 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. Surfacing outcomeUnknown: Bool tells 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 async function, two sequential try 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).

  4. 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 after 65,536 commands (~1.8 hours). An 8-bit counter (256 values) 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 len payload bytes have arrived (discarding any partial buffer that stalls for more than 500 ms). Thus CommandEngine always works on complete frames.

    Internal records and engine state

    A continuation (CheckedContinuation in Swift) is a single-use callback handle that suspends an async caller 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 (inFlightTimer on 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 == .ready means four things have all finished: radio connected, GATT services discovered, characteristics discovered, setNotifyValue(true, for: responseCharacteristic) confirmed by didUpdateNotificationStateFor, and any protocol handshake completed. Writing a command right when didConnect fires—before notifications are enabled—would cause the wearable's fast reply to vanish silently.

  5. 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:

    1. UI calls try await handler.send(GetBatteryLevel()). BLECommandHandler wraps the request in a PendingCommand, captures a CheckedContinuation, and hops onto bleQueue.
    2. CommandEngine.enqueue checks Bluetooth availability and the 64-item cap, appends the command to pending, and calls pump().
    3. pump() sees link == .ready and inFlight == nil, pops the head command, assigns seq = 42, sets inFlight, starts inFlightTimer for 2 seconds, and asks BLETransport to write the frame.
    4. CoreBluetoothTransport writes the bytes and reassembles the notification reply into a Frame(opcode: 0x10, seq: 42, status: 0, payload: [87]).
    5. CommandEngine.didReceive matches (0x10, 42), cancels inFlightTimer, clears inFlight, resumes the caller with [87], and immediately calls pump() to send item #43 if one is waiting.
  6. Deep dive 1: Concurrency model and strict serialization

    Why share one serial DispatchQueue (bleQueue) with CoreBluetooth? When you initialize CBCentralManager(delegate: self, queue: bleQueue), iOS guarantees that every Bluetooth event—characteristic notification, write error, disconnect, radio power change—is delivered sequentially on bleQueue. By running CommandEngine on that exact same bleQueue, writes, responses, timers, cancellations, and disconnects execute strictly one after another with zero locks and zero event reordering.

    Why not use a plain Swift actor called from CoreBluetooth delegate methods via Task { await engineActor... }? Because unstructured Task blocks 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 single AsyncStream read by one loop, or on iOS 17+ bind the actor's custom executor directly to bleQueue.)

    Bridging async callers safely (send, enqueue, and pump)

    Notice a subtle Swift detail in withTaskCancellationHandler: if the calling task was already cancelled before send starts, Swift invokes onCancel before the operation block dispatches onto bleQueue. Because both blocks dispatch to the serial bleQueue and share cmd.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 drain pending. To avoid leaving callers suspended for hours, a 1-second repeating timer on bleQueue sweeps pending whenever link != .ready and fails any command whose scheduler.now >= cmd.queueDeadline with .queueDeadlineExceeded.

  7. Deep dive 2: Response matching, timeouts, and failure policy

    Why opcode-only matching corrupts future responses Suppose screen A sends GetSettings, it times out at 2.0 s, we unblock the queue and screen B sends GetSettings at 2.01 s, and then the wearable's slow reply to screen A arrives at 2.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 inFlightTimer captures activeSeq: even if a timeout callback was already queued on bleQueue a microsecond after the valid response cleared inFlight and started seq + 1, cmd.seq == seq rejects 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 inFlight Effect on remaining pending queue
    1st timeout on idempotent command Re-inserted at index 0, retried once with new seq Waits 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-handshakes
    Firmware status != 0 Fails 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 queueDeadline timer)
    Bluetooth powered off / unauthorized Fails with .bluetoothUnavailable Entire queue drained with .bluetoothUnavailable

    What if legacy firmware has no seq field? Matching falls back to frame.opcode == cmd.opcode, and after any timeout the engine injects an internal EchoPing(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.

  8. 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 pending is easy: remove it from the array so it never touches the radio. Cancelling inFlight is trickier: the bytes are already on the wearable!

    If we cleared inFlight = nil immediately 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 cancelled inFlightTimer, and the wearable never replied, inFlight would stay occupied forever, deadlocking the entire queue! That is why resumeCaller only wakes the caller while inFlight and inFlightTimer stay 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: Clear inFlight + inFlightTimer, resume that caller with .disconnected(outcomeUnknown: true), set link = .disconnected, keep pending (guarded by the 1-second queueDeadline sweep), and immediately call centralManager.connect(peripheral)—on iOS, connect never 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 when didFailToConnect or 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.now has still advanced monotonically during sleep. Therefore, at the top of every bleQueue callback, the engine first checks whether inFlight's deadline or pending queue deadlines have already elapsed before processing new work. Multi-command background sync jobs also acquire a UIApplication.beginBackgroundTask assertion 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, BLECommandHandler remains 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.
  9. 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 sends AckWindow(offset) commands so urgent UI commands can interleave cleanly between windows without breaking FIFO order.
    • Multi-command transactions: Operations like BeginConfig -> SetAlarm -> CommitConfig must not interleave with background battery checks. handler.transaction { tx in ... } places a single slot in pending; once at the head, only tx.send(...) commands bypass the outer queue until the closure returns or a 10-second transaction guard expires.
    • Read coalescing: Five UI widgets requesting GetBatteryLevel simultaneously while one GetBatteryLevel is still sitting in pending can attach their continuations to that single queued PendingCommand instead 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, outcomeUnknown rate, 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

    1. Deterministic unit tests (FakeTransport + ManualScheduler): Because both CoreBluetooth and time are behind tiny protocols, unit tests advance a virtual clock by 2.0 seconds in microseconds and script exact byte deliveries:
      • Strict serialization: Enqueue A and B concurrently; assert FakeTransport.writes.count == 1 until A's response frame is injected, after which B is written immediately.
      • Stale reply immunity: Enqueue A (seq = 1), advance virtual clock +2s to trigger timeout (non-idempotent), observe B (seq = 2) written, inject late reply for seq = 1, assert B stays suspended until reply seq = 2 arrives.
      • Cancel while in flight: Cancel A while in flight; assert A throws .cancelled immediately, 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.
    2. Randomized concurrency fuzzing: Spawn 1,000 concurrent tasks in a TaskGroup with random cancellations, random virtual delays, and 10% simulated packet drops. Assert three hard invariants: maxConcurrentOnDevice <= 1, every send returned or threw once (0 leaks, 0 double resumes), and single-task sequential calls arrived on the fake wire in order.
    3. Thread Sanitizer (TSan) + hardware-in-the-loop: Run CI tests with TSan enabled and dispatchPrecondition(condition: .onQueue(bleQueue)) assertions inside CommandEngine, followed by soak tests against debug firmware configured to inject delayed, dropped, and duplicate BLE notifications.

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 DispatchQueue vs. Swift actor vs. locks: Passing the same serial DispatchQueue (bleQueue) to CBCentralManager and running all CommandEngine state transitions on it keeps radio callbacks, timers, and writes in exact arrival order with zero locks. A Swift actor provides compiler-enforced actor isolation (a guarantee that only one task mutates the actor's properties at a time), but wrapping each delegate callback in Task { await actor.handle(...) } can reorder a response and a disconnect unless routed through a single ordered AsyncStream or a custom executor on iOS 17+. Manual NSLock synchronization scatters concurrency invariants across threads and risks deadlocks when resuming continuations.
  • 16-bit sequence numbers (seq) vs. opcode-only matching: Adding a 2-byte seq echoed 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. Without seq on 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 inspect outcomeUnknown: true to 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 transaction wrapper 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 inFlight set to protect the device from overlapping commands, a dropped firmware reply leaves inFlight stuck 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 == expectedSeq on bleQueue, a timer that fires right after command 1 finished will mistakenly fail command 2.
  • Sending commands inside didConnect before enabling notifications: Writing to the command characteristic before GATT service discovery, setNotifyValue(true, ...), and didUpdateNotificationStateFor complete causes the wearable's reply to be dropped before iOS is subscribed.
  • Relying on dispatch timers while suspended in the background: Even with bluetooth-central background mode, iOS suspends the process between BLE events and pauses timers, so every wake-up callback must compare deadlines against ContinuousClock.now (a monotonic clock that keeps counting while the phone sleeps).
  • Checking queue deadlines only inside pump(): Because centralManager.connect on iOS waits indefinitely when a wearable is out of range, pump() never runs while disconnected; without a periodic sweep while link != .ready, callers wait far past their 10-second queueDeadline.

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 short AckWindow(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 storing nextOffset makes 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? and inFlightTimer: Cancellable? with a dictionary inFlightBySeq: [UInt16: InFlightSlot] capped at maxWindow = 4, where each slot owns its own PendingCommand and timeout timer, and change pump()'s condition from inFlight == nil to inFlightBySeq.count < maxWindow. Because our wire frame already echoes seq, 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 explicitly await A before calling B or use handler.transaction to 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 p99 round-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

Similar questions

More Whoop interview questions

All 1 Whoop questions →