In high-concurrency mobile web applications streaming live sportsbook odds, match statistics, and balance updates, passing structured data to the UI thread via postMessage creates continuous cloning overhead. This continuous object copying consumes valuable CPU cycles and triggers frequent garbage collection pauses on budget handheld hardware.
To achieve zero-copy stream processing across browser threads, ingest raw binary WebTransport streams directly into a SharedArrayBuffer using Atomics for thread synchronization:
// telemetry/streamConsumer.worker.js
let sharedBuffer = null;
let int32View = null;
let float64View = null;
self.onmessage = async (event) => {
const { type, transportUrl, buffer } = event.data;
if (type === 'INIT_TRANSPORT') {
sharedBuffer = buffer;
// Shared Memory Layout:
// [0]: Lock/Sequence Counter (Int32)
// [1]: Event ID (Int32)
// [2..3]: Float64 Rate Metric
int32View = new Int32Array(sharedBuffer);
float64View = new Float64Array(sharedBuffer);
try {
const transport = new WebTransport(transportUrl);
await transport.ready;
const reader = transport.incomingUnidirectionalStreams.getReader();
while (true) {
const { value: stream, done } = await reader.read();
if (done) break;
handleIncomingStream(stream);
}
} catch (err) {
console.error('WebTransport session error:', err);
}
}
};
async function handleIncomingStream(stream) {
const streamReader = stream.getReader();
const chunkBuffer = new ArrayBuffer(16);
const chunkView = new DataView(chunkBuffer);
while (true) {
const { value, done } = await streamReader.read();
if (done) break;
// Fast copy to local DataView
new Uint8Array(chunkBuffer).set(value.subarray(0, 16));
const eventId = chunkView.getInt32(0, true);
const rateVal = chunkView.getFloat64(4, true);
// Acquire write lock via Atomics
Atomics.add(int32View, 0, 1);
int32View[1] = eventId;
float64View[1] = rateVal; // Float64 offset index 1 maps to bytes 8-15
Atomics.notify(int32View, 0, 1);
}
}
// client/telemetryClient.js
export class ZeroCopyTelemetrySubscriber {
constructor(workerScriptUrl, serverUrl) {
this.worker = new Worker(workerScriptUrl, { type: 'module' });
this.sharedMemory = new SharedArrayBuffer(16);
this.int32View = new Int32Array(this.sharedMemory);
this.float64View = new Float64Array(this.sharedMemory);
this.worker.postMessage({
type: 'INIT_TRANSPORT',
transportUrl: serverUrl,
buffer: this.sharedMemory
});
}
pollLatestMetric(targetNode) {
// Read atomic state non-blockingly
const currentSeq = Atomics.load(this.int32View, 0);
const eventId = this.int32View[1];
const metric = this.float64View[1];
if (currentSeq > 0 && targetNode) {
targetNode.textContent = `${metric.toFixed(2)}`;
targetNode.dataset.event = eventId;
}
}
}
// Example usage: Bind telemetry updates to UI render loop
const oddsDisplay = document.querySelector('#liveOddsLadder');
const subscriber = new ZeroCopyTelemetrySubscriber(
'./telemetry/streamConsumer.worker.js',
'[https://stream.bl777.com.co/events](https://stream.bl777.com.co/events)'
);
function renderLoop() {
subscriber.pollLatestMetric(oddsDisplay);
requestAnimationFrame(renderLoop);
}
requestAnimationFrame(renderLoop);
Key Engineering Advantages:
- Bypasses Structured Cloning: Workers process raw network chunks and write directly to physical memory locations read by the UI thread, eliminating object allocations.
- Zero Main-Thread Freezes: Network stream reading and packet transformation occur strictly inside worker threads, preventing event-loop delays during intensive animations.
For an operational reference of decoupled, low-footprint web viewports running in production, inspect this reference node.
Comments
Join the discussionNo comments yet. Be the first to comment.
