Engineering

Bluetooth LE is underrated

Most developers think of Bluetooth LE as the flaky radio behind headphones and fitness bands. Used as a small, serverless local network between phones, tablets and laptops, it is quietly remarkable: no router, no accounts, no internet, and every phone already has it. When we built local band sync for ChordCast, a 500-byte state record over GATT turned out to be plenty.

Updated

Why a band on stage fits Bluetooth LE

A working band in a basement venue is a harsh test for networking. Cellars block mobile signal, venue Wi-Fi sits behind captive portals or disappears under a room full of phones, and nobody wants to configure a router or log into an account two minutes before downbeat. PDFs in a group chat and shared folders help before the gig, right up until someone calls a different key on stage or fixes a wrong bar in rehearsal.

Look at the actual state a band needs to share, and the problem shrinks fast. There are usually a handful of iPhones, iPads, Macs and Android devices standing a few metres apart. Between them, the shared session comes down to four newest-wins values:

  • who is leading the band
  • which exact chart version the band is on
  • the band's key for each song
  • the current band setlist

Everything else stays local. Say a saxophonist reads for a B♭ instrument: their +2 semitone offset and spelling preference live on their own device and never touch the radio. That kind of small, room-scoped state is what makes setlists without internet viable over a low-bandwidth link. When you only need to keep a few screens in step, usually within a second, Bluetooth LE already sits in every pocket.

Peripheral and central over one GATT service

Most mobile developers meet Bluetooth LE as a one-way pipe to a heart-rate strap or a pair of earbuds. Peer-to-peer work flips that assumption: every device acts as both a peripheral (advertising a GATT service) and a central (scanning for peers and opening links).

Our transport exposes one GATT service with four characteristic roles:

CharacteristicDirectionPurpose
stateread + notifyPeripheral's state record; notifies with a 5-byte change marker, then the central reads
peerInboxwriteCentral writes its own state record so the peripheral hears it without a reverse link
chartRequest / chartDatawrite / readCentral pulls a chart or setlist page by page (≤ 512 bytes per ATT value, zlib-compressed)
chartInboxwriteCentral pushes a chart the peripheral requested in want

Separating notifications from reads keeps traffic light: a 5-byte marker tells centrals that state changed, and each central pulls the fresh record when ready. Putting peerInbox and chartInbox on the same service means a single LE connection carries traffic in both directions. No system pairing dialogue appears, no access point sits in the middle, and nothing leaves the room.

Fitting room state into 500 bytes

Bluetooth LE imposes a 512-byte ATT ceiling on a single characteristic value. Go past 512 bytes and the remote side fails to read the record at all, so the device effectively drops out of the band. We cap every encoded record at MAX_ENCODED_BYTES (500 bytes) and treat the budget as a hard invariant.

Five hundred bytes sounds cramped until you stop sending streams and send current state instead. One compact record holds the entire snapshot of a device's view of the room:

  • Identity and compatibility: protocol version v, oldest compatible version vc, session, visibility vis, stable 8-character hex tag and display name.
  • Current song and leader: chart fingerprint fp, hybrid-logical-clock revision rev, origin, leader claim lead, lrev, recent leader history lhist and direct-link flag lh.
  • Song key and setlist: band key bk, flat or sharp spelling bks, key revision bkrev, song lineage bkl, and complete setlist reference sl with slrev.
  • Transfers and security: missing-item request want, invitee list inv (at most three tags, held for two minutes), X25519 public key pk (32 bytes, base64), opening revision vrev and truncated HMAC-SHA256 mac.

Even invite-only bands fit inside that envelope. Members share a random 16-byte session key and attach mac (HMAC-SHA256 over a canonical authString, truncated to 16 bytes and base64-encoded) to every record. Unverified records are stripped down to identity, versions, inv and pk before the session store ever sees them, so nobody outside the band can hijack the screen. Invitations seal the session key with X25519, HKDF-SHA256 (chordcast-invite-v1) and AES-GCM, then serve the sealed box as x-inv-<tag> over the same transfer channel.

Every byte still hurts at gig scale. origin is omitted whenever it matches the HLC node of the jump, which is the common case. Song key revisions use the 8-character device tag as the HLC node rather than a longer ID. Two fields taught us just how tight 500 bytes really is:

  1. Optional metadata gets squeezed out first. We used to carry hr (the chart's head revision) in the record, only to find full gig records shedding it so peers waited instead of comparing versions. It was removed completely. Likewise, vrev (used to order locking and opening a band) adds 33 bytes; keeping it on every record pushed the setlist reference out of a full signed record on real hardware, so it is now sent only in an open band while a bandmate is still locked.
  2. Shedding must be deterministic. Before crossing 500 bytes, the encoder drops optional fields in order: a trail request, leader history, most of the display name, wants, then sl. As a last resort it trims the rest of the name, invitations, want, vrev and the song key, while pk is never shed. Even with those cuts, a full gig record has almost no spare headroom: roughly one in eight records carrying a setlist reference sheds it.

Gossip and hybrid logical clocks instead of handshakes

Protocols built on handshakes and session setup tend to wedge the moment someone walks behind a stack of speakers. Gossip avoids that trap altogether. Every device publishes its state record, adopts whatever is newest among the records it hears, and re-publishes what it adopted. Values hop across the room even to devices out of direct range of the originator. Nothing waits on an acknowledgement, and a device that drops out simply stops being heard.

Ordering comes from a hybrid logical clock (NearbyHLC, formatted as physical-counter-node) backed by one causal rule across local edits, Bluetooth and cloud sync:

  • Only a person's edit mints a new revision via ReplicaClock.
  • Transports relay values together with their original revision, never re-stamping them.
  • Every write passes through ReplicaRule.accepts(incoming, over: current), keeping a value only if its revision is newer.

That single rule kills a whole class of bugs where a stale copy heard over Bluetooth gets re-stamped and overwrites a newer edit elsewhere. When two edits are concurrent (detected by checking whether the incoming edit was built on a device's own base chart or from setlist), the device whose edit lost merges the two (bar by bar for charts via ChartMerge, item by item for setlists via SetlistMerge) and saves a fresh winning revision.

Leadership runs on the same handshake-free footing. Tapping Take Lead publishes a newer claim. In a brand-new room with no claim, devices wait a 3-second grace period before the lowest device tag claims the lead. A device rejoining a remembered band waits the full 8-second leader timeout instead; turning the radio back on can take several seconds before bandmates are heard, and a 3-second grace let returning devices grab the lead and jump the room to an old offline edit.

If the current leader goes unheard for 8 seconds, every peer computes the exact same successor (the most recent previous leader still present, or else the lowest present tag), and only that device publishes a claim. No election round-trip is needed. If a room splits in two, each half elects its own leader and the newer claim wins when they reconnect.

Real rooms still expose subtle edge cases. Bands are not always fully connected: a Pixelbook and a Mac that could not link directly, yet shared a mutual bandmate, kept deciding the other had vanished and trading the lead every 8 seconds. Adding lh, set to true only when a sender has a direct link to the leader, never forwarded second-hand, stopped the flapping while still letting failover trigger once direct links actually drop.

Mixed app versions meet in the same room too. Decoders ignore unknown keys so additive fields need no bump, while behavioural changes raise v alongside a degradation rule, and vc rises only when older builds cannot sync at all. Incompatible peers stay visible under a "Needs an Update" list (clearing after 45 seconds of silence or once updated) rather than silently failing to appear.

Content-addressed charts over a narrow pipe

State records carry pointers, not songs. Every chart is content-addressed by a fingerprint (a hash of title, content and format). A separate lineage ID stays constant across saves so band song keys follow the song rather than a single revision, while duplicating a chart creates a new lineage that the band never touches.

If a follower already holds the announced fingerprint, zero bytes cross the radio. Otherwise NearbyBandChartSync pulls it page by page (at most 512 bytes per ATT read, zlib-compressed) from peers advertising the move. To avoid piling onto the leader, each follower picks the peer with the nearest lower tag, runs one fetch at a time, and backs off at 1, 2, 4 and 8 seconds on failure, giving every peer another turn after three misses. If the follower is on a one-way link and cannot initiate reads, it advertises the missing fingerprint in want and the linked central pushes it through chartInbox.

Setlists (NearbySetlistShare) travel the same way. Because a full setlist will not fit in 500 bytes, the state record carries only sl and slrev. Followers fetch the setlist document and then each missing chart one by one, always putting the band's current song first. Only once a device holds the entire set does it save the setlist locally and start advertising sl, turning itself into another relay for the rest of the room.

Edits and undos follow one version per song. Early on, guessing that a chart fingerprint already in local history must be older created an infinite loop after an undo, because undoing a fix names a fingerprint everyone has already seen. Now, when a band announces a version held in local history, the device fetches the band's copy to compare headRev, trusting the announcer's own copy before moving the band forward (or giving up on an unresponsive announcer after 20 seconds). ChordCast's web app skips Bluetooth and syncs through cloud links instead; you can see how the native radio layer behaves from a player's point of view in band sync in the user guide.

The rough edges you meet on real hardware

Bluetooth LE is underrated, not magical. The parts that take real engineering are platform quirks you only uncover once you put three or four different devices on a table.

One link per pair. An iPhone 14 Pro and a Mac could not reliably hold two opposite-direction LE connections at the same time. The transport therefore assumes a single link per pair. Each device advertises its 8-character tag so both sides know who should connect: Apple devices put CC<tag> in the local name, while Android, which cannot set an arbitrary local name, packs [1][tag as 4 bytes] into advertised service data. The lower tag initiates; the higher tag waits 5 seconds before connecting as a fallback. If both links still form anyway, the higher tag closes its outbound link (duplicate_link) once the inbound link is confirmed working.

Android on ChromeOS. ChromeOS's Android container broke two assumptions at once: its GATT server never delivers incoming requests, and it neither sends nor receives scan responses, so its advertised tag never reaches Apple devices. The workaround is a central-only mode: the device stops advertising and serving and connects out to every peer instead. On the Apple side, once a peripheral's inbox write arrives, the transport maps that tag to the peer's CoreBluetooth UUID so the Mac stops opening a doomed reverse link to a Pixelbook that is already connected.

iOS background limits and naming. On iPhone and iPad, entering background suspends the BLE transport (and iOS drops the local name from background advertisements anyway). Keeping the transport alive during inactive (notification banners and quick system overlays) prevents players from dropping out of the band mid-song. Macs and Android devices keep syncing in the background (Android holds a notification while sync is active), and if nobody with sync on is nearby for 15 minutes, sync turns itself off to save battery. iOS also hides the user's device name from apps, so display names fall back to model plus ID until a player sets a name.

The full-mesh ceiling. A full mesh requires N − 1 connections per device. Because iOS allows roughly 8 to 10 BLE links, full-mesh presence tops out at around 8 devices. Beyond that you would need partial-mesh presence, even though charts already relay across multiple hops.

Deadlines everywhere. Every GATT read, write and subscription runs on a single serial CoreBluetooth queue with a hard deadline. Failed steps back off from 1 second to 15 seconds and retry only while the peer is still advertising. Inbox heartbeats fire every 8 seconds, and silent inbound peers expire after 25 seconds.

One shared core, fuzzing and simulated bands

Implementing a radio state machine once in Swift and again in Kotlin is a reliable way to create bugs that only reproduce on stage. Every protocol decision here lives in one Kotlin Multiplatform module (kmp/offline-core):

  • NearbyPeerStateMessage and NearbySessionLock handle record encoding, shedding, admission and HMAC signing.
  • NearbyLinkEngine and NearbyGattServerModel run the connection state machine and GATT server replies.
  • NearbyBandLeadership, NearbyBandChartSync, NearbyBandSongKeys, NearbyBandSetlistSync and NearbyBandInvitations hold the pure state machines for band behaviour.

Native transports (NearbyCollabService on Apple, AndroidNearbyTransport on Android) stay thin: feed radio callbacks in, carry out the returned effects. Shared wire fixtures verify both platforms agree byte for byte, including Apple CryptoKit against Android's NearbyInvitation sealing and the protocol version constants.

Testing happens in layers so bugs die long before a rehearsal:

  • Byte-budget property tests: NearbyRecordBudgetTest checks realistic and worst-case payloads, while NearbyRecordPropertyTest generates 3,000 random real-shaped records to prove the 500-byte limit never breaks and shedding rates do not regress.
  • Link fuzzers: NearbyLinkFuzzTests (Swift) and NearbyLinkFuzzTest (Kotlin) hammer the engine with simulated peers connecting, duplicating links and dropping out.
  • Simulated bands and hardware runs: full scripted band scenarios (jams, gigs, invite-only rooms and rough rooms) finish in a minute or two without any phones on the desk, complemented by real-device automation (nearby-sync-e2e.py and nearby-journeys.py).

Where else Bluetooth LE belongs

Stages are an unusual setting, yet the shape of the problem shows up everywhere. We think Bluetooth LE is a natural fit for any room of people holding phones who need small, shared state without trusting the building's network.

Think of a classroom where a teacher advances everyone's worksheet or slide deck despite locked-down school Wi-Fi. Think of theatre cues, choir rehearsals, tabletop gaming groups or a small meeting in a basement room with no guest network where five people want a live agenda and quick notes. Wherever groups are small, membership is temporary, payloads are kilobytes rather than streams and nobody wants to create an account just to sit in the same room, the radio already sitting in every phone does the job cleanly.

Questions

How many devices can sync over Bluetooth LE at once?

In a full mesh, every device holds N − 1 connections, and iOS allows roughly 8 to 10 simultaneous BLE links. That puts a practical ceiling of about 8 devices on full-mesh presence. Larger rooms need partial-mesh presence, though gossiped state and content-addressed files already relay across hops.

Does Bluetooth LE sync work across iPhone, Mac and Android without pairing?

Yes. Devices discover each other through GATT advertisements and exchange data over standard GATT reads, writes and notifications with no system pairing prompt. The main cross-platform detail is advertising format: Apple devices can advertise a local name (CC<tag>), whereas Android packs its device tag into advertised service data ([1][tag as 4 bytes]), so readers need to accept both.

How do you transfer larger documents over a 512-byte GATT limit?

Keep the live state record under 500 bytes and store only content hashes there. Larger payloads, like charts or setlists, are zlib-compressed and paged over dedicated request/data characteristics at up to 512 bytes per ATT value, or pushed over an inbox characteristic when the link is one-way. Any peer that finishes fetching a document can immediately relay it to others.

What happens when an iOS app using Bluetooth LE moves to the background?

On iPhone and iPad, entering background suspends the BLE transport, and iOS stops advertising the local name while backgrounded. Keeping the transport active during inactive states avoids dropping connections for brief notification banners, and persisting sync state lets the device rejoin its band automatically on return. macOS and Android can keep running in the background, with Android displaying an active sync notification.