Design a Serialized BLE Command Queue and Transport Handler
System DesignModel answerLast updated
Architect a reliable, serialized command dispatch system for Bluetooth Low Energy peripherals with response matching, timeout management, and fault tolerance.
Architect an event-driven BLE (Bluetooth Low Energy) Command Handler for a mobile application communicating with an external peripheral device.
System Requirements
- Strict Serialization: Commands must be processed sequentially—no command can be issued until the preceding command completes (either via success, failure, or timeout).
- Response & Timeout Guarantee: Once a command is transmitted, the system must wait for a matching incoming response frame or an explicit execution timeout.
- Queue Unblocking & Failure Policy: A timed-out or failed command must unblock the dispatch queue according to a deterministic policy (e.g., configurable retries, drop, or queue invalidation).
- Thread-Safe Concurrent Submission: Multiple features within the app must be able to enqueue commands concurrently from any thread without race conditions.
- Robust Operations: Address transport fragmenting (MTU limits), asynchronous disconnects, Task cancellation, and unit testability.
Design the architecture, data models, state machine, concurrency/cancellation semantics, and edge-case failure strategies.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Architecture Overview
A robust BLE command processing system requires strict decoupling between raw transport operations, request queuing/timeout logic, and application-level business logic.
┌─────────────────────────────────────────┐
│ Application Clients │
│ (e.g., SyncEngine, BatteryChecker) │
└────────────────────┬────────────────────┘
│ enqueue(command)
▼
┌─────────────────────────────────────────┐
│ BLE Command Orchestrator │
│ (Actor / Serial Queue Engine) │
│ ┌──────────────┐ ┌─────────────┐ │
│ │ Pending Queue│ │ State Logic │ │
│ └──────────────┘ └─────────────┘ │
└────────────────────┬────────────────────┘
│ write(payload)
▼
┌─────────────────────────────────────────┐
│ BLE Transport │
│ (Wraps CBCentralManager / CBPeripheral)│
└────────────────────┬────────────────────┘
│ BLE Packets
▼
Hardware Device
Component Layering
-
Transport Layer (
BLETransport):- Manages raw connection states, characteristic writes, notification subscriptions, and MTU chunking/fragmentation.
- Emits an asynchronous stream of incoming raw response frames and link lifecycle events (
connected,disconnected). - Does not maintain command queue state or manage timeouts.
-
Orchestrator Layer (
BLECommandEngine):- Manages an internal FIFO execution queue.
- Maintains the state of the single active in-flight request.
- Controls response frame matching, timeout timers, retry strategies, and queue recovery.
-
Client API Layer:
- Exposes strongly typed async functions (e.g.,
fetchDeviceStatus() -> DeviceStatus). - Encapsulates payload serialization and response decoding logic into discrete
Commandtypes.
- Exposes strongly typed async functions (e.g.,
Data Models & Core Protocol Contracts
/// Defines the structure of a command sent over BLE.
protocol BLECommand {
associatedtype Response
var opcode: UInt8 { get }
var payload: Data { get }
var timeoutDuration: TimeInterval { get }
var maxRetries: Int { get }
var isIdempotent: Bool { get }
/// Validates if an incoming frame belongs to this command.
func matches(frame: BLEFrame) -> Bool
/// Parses a raw payload into the concrete Response type.
func decode(payload: Data) throws -> Response
}
/// Raw protocol packet received from the peripheral.
struct BLEFrame {
let sequenceID: UInt8? // Optional sequence number echoed by firmware
let opcode: UInt8
let payload: Data
}
/// Internal wrapper for queued items tracking execution metadata.
private struct EnqueuedCommand {
let id: UUID // Monotonic unique identifier for stale-event filtering
let sendAction: () async throws -> Data
let responseHandler: (Result<Data, Error>) -> Void
let timeoutDuration: TimeInterval
let maxRetries: Int
let isIdempotent: Bool
var attemptCount: Int = 0
}
State Machine & Concurrency Model
To eliminate state corruption and data races from multi-threaded enqueuing, state mutations are isolated within a Swift actor (or pre-Swift 5.5: a serial DispatchQueue).
Execution States
┌──────┐ enqueue() ┌─────────┐
│ Idle ├────────────────────►│ Pending │
└▲─────┘ └────┬────┘
│ │ pumpQueue()
│ finish(id, result) ▼
└───────────────────────── Write to Link
│
▼
┌────────────────┐
│ In-Flight │
│ (Timer Active) │
└────────────────┘
The system transitions between three core states:
- Idle: No command is currently executing.
- Transmitting: Writing raw bytes across the physical BLE link.
- AwaitingResponse: Payload is written; a timer task is actively listening for the matching response.
State Representation
actor BLECommandEngine {
private enum State {
case idle
case executing(inFlight: InFlightContext)
}
private struct InFlightContext {
let command: EnqueuedCommand
let timerTask: Task<Void, Never>
}
private var queue = [EnqueuedCommand]()
private var state: State = .idle
private var sequenceCounter: UInt8 = 0
private var isConnected: Bool = false
// Injected clock interface for unit testing
private let clock: ContinuousClock
private let transport: BLETransportProtocol
init(transport: BLETransportProtocol, clock: ContinuousClock = ContinuousClock()) {
self.transport = transport
self.clock = clock
}
}
Serialization & Execution Flow
extension BLECommandEngine {
/// Public entry point: Enqueues a command and suspends until execution completes.
func execute<C: BLECommand>(_ command: C) async throws -> C.Response {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation { continuation in
let item = EnqueuedCommand(
id: UUID(),
sendAction: { [weak self] in
guard let self = self else { throw BLEError.deallocated }
return try await self.transport.write(
opcode: command.opcode,
payload: command.payload
)
},
responseHandler: { result in
switch result {
case .success(let data):
do {
let decoded = try command.decode(payload: data)
continuation.resume(returning: decoded)
} catch {
continuation.resume(throwing: BLEError.decodingFailed(error))
}
case .failure(let error):
continuation.resume(throwing: error)
}
},
timeoutDuration: command.timeoutDuration,
maxRetries: command.maxRetries,
isIdempotent: command.isIdempotent
)
self.enqueue(item)
}
}
private func enqueue(_ item: EnqueuedCommand) {
queue.append(item)
pump()
}
private func pump() {
guard case .idle = state, isConnected, !queue.isEmpty else { return }
var current = queue.removeFirst()
current.attemptCount += 1
let currentID = current.id
// Start non-blocking timeout task tied to current execution generation
let timerTask = Task { [weak self] in
try? await self?.clock.sleep(for: .seconds(current.timeoutDuration))
await self?.handleTimeout(for: currentID)
}
state = .executing(inFlight: InFlightContext(command: current, timerTask: timerTask))
Task {
do {
_ = try await current.sendAction()
// Physical write succeeded; remaining suspended until incoming response or timeout
} catch {
await self.finish(id: currentID, result: .failure(BLEError.writeFailed(error)))
}
}
}
}
Matching Responses & Timeout Prevention
1. Frame Matching Strategy
- Sequence Identifiers (Preferred): If firmware supports header sequence IDs (e.g.,
0x00–0xFF), matching is unambiguous (incoming.seq == inFlight.seq). - Opcode Fallback: If sequence numbers are absent, match based on expected opcode (
incoming.opcode == inFlight.opcode).- Risk: A late-arriving frame for a timed-out command can match a newly scheduled command with the same opcode.
2. Disambiguating Late Arrivals via Generation Tokens
Every queued item receives a monotonic UUID (id). When processing responses or timeouts, events are verified against inFlight.command.id. If they differ, the event is dropped as stale.
extension BLECommandEngine {
/// Invoked by transport layer when a complete BLE frame arrives.
func receive(frame: BLEFrame) {
guard case .executing(let inFlight) = state else {
// Unsolicited notification or late frame: forward to stream handler
handleUnsolicitedFrame(frame)
return
}
// Verify sequence number or opcode matching
if frame.opcode == inFlight.command.opcode {
finish(id: inFlight.command.id, result: .success(frame.payload))
} else {
// Frame is intended for unsolicited notifications stream
handleUnsolicitedFrame(frame)
}
}
private func handleTimeout(for id: UUID) {
guard case .executing(let inFlight) = state, inFlight.command.id == id else {
return // Ignore stale timeout task
}
let cmd = inFlight.command
if cmd.isIdempotent && cmd.attemptCount <= cmd.maxRetries {
// Re-queue at the front for immediate retry
state = .idle
inFlight.timerTask.cancel()
queue.insert(cmd, at: 0)
pump()
} else {
finish(id: id, result: .failure(BLEError.timeout))
}
}
private func finish(id: UUID, result: Result<Data, Error>) {
guard case .executing(let inFlight) = state, inFlight.command.id == id else {
return
}
inFlight.timerTask.cancel()
state = .idle
// Fulfill external caller completion
inFlight.command.responseHandler(result)
// Process next queued command
pump()
}
}
Edge Cases & Fault Tolerance
Disconnections During In-Flight Execution
When a peripheral disconnects mid-command:
- Immediately cancel any active
timerTask. - Fail the currently in-flight command with
.disconnected. - Flush all remaining items in
queuewith.disconnectederrors. - Set state to
.idleuntil link status becomes.connected.
func handleDisconnect() {
isConnected = false
if case .executing(let inFlight) = state {
inFlight.timerTask.cancel()
inFlight.command.responseHandler(.failure(BLEError.disconnected))
}
while !queue.isEmpty {
let item = queue.removeFirst()
item.responseHandler(.failure(BLEError.disconnected))
}
state = .idle
}
Swift Task Cancellation Support
If a caller cancels their enclosing Swift Task:
- If still in
queue, the item is removed. - If currently
inFlight, the operation can either be abandoned or allowed to finish while returningCancellationErrorto the caller.
Circuit Breaker for Repeated Failures
If $N$ consecutive commands time out (e.g., $N=3$), the transport link is likely dead locked. Trigger a transport reset (CBPeripheralManager.cancelPeripheralConnection()) and flush the queue to avoid waiting for every queued command to time out sequentially.
Strategy Comparison: Concurrency Models
| Metric | Swift Actor | Serial DispatchQueue | Mutex / Lock |
|---|---|---|---|
| Data Race Safety | Compile-time guaranteed | Runtime enforced | Manual / Error-prone |
| Cancellation Flow | Native Task cancellation integration | Requires custom handling | Requires custom handling |
| Reentrancy Risk | Must ensure invariant checks across await | Avoided if non-blocking | N/A (Blocking) |
| Testability | High (using ContinuousClock) | Medium (using custom queues) | Low |
Testing & Validation Strategy
-
Mock Transport Injections:
- Create a
MockBLETransportconforming toBLETransportProtocol. Simulate normal frame responses, out-of-order notifications, delayed frame arrivals, and unexpected disconnections.
- Create a
-
Deterministic Time Testing:
- Use Swift's
TestClock(or custom clock abstraction). Advance virtual time manually to test timeout paths instantaneously without usingTask.sleepdelays in unit test suites.
- Use Swift's
-
Concurrency Stress Tests:
- Spawn 100 parallel
Taskinstances callingexecute(cmd)simultaneously. Assert that the commands execute in sequential order and that all continuations complete without deadlocks or memory leaks.
- Spawn 100 parallel