Skip to main content

Cross-Tab Sync via SharedWorker Architecture

How a single SharedWorker broker handles WebSocket multiplexing, IndexedDB locking, and leader election to stop cross-tab state divergence.

KBY Technologies11 min read
Cross-Tab Sync via SharedWorker Architecture

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

Open six tabs of a trading dashboard micro-frontend and you get six independent WebSocket connections, six IndexedDB writers racing on the same object store, and six divergent copies of client-side state the instant one tab misses a push update. Multiply that by a corporate proxy throttling concurrent connections per origin and you have a production incident.

The fix is not “just use localStorage events” — that approach cannot arbitrate write conflicts or multiplex a single upstream socket. What you need is a proper SharedWorker architecture that centralises network I/O and state ownership behind a single execution context, regardless of how many tabs the user has open.

Design, implementation and failure semantics all matter when you use a SharedWorker as the single source of truth for cross-tab state in a micro-frontend estate, including the leader-election fallback required for browsers and WebViews that do not implement it.

#The Problem: N Tabs, N Sockets, Zero Consistency

Most micro-frontend shells are composed independently per browser tab — each shell instance boots its own Redux/Zustand store, opens its own WebSocket to the pricing gateway, and independently hydrates from IndexedDB on load. This produces three concrete failure classes:

  • Connection fan-out: N tabs open N WebSocket connections to the same backend, multiplying gateway load and burning through per-origin or per-host connection limits (browser limits vary and are different for WebSockets than for , and corporate proxies are often far stricter).
  • Write races: Two tabs writing to the same IndexedDB record concurrently produces last-write-wins corruption with no application-level arbitration.
  • State drift: A tab backgrounded by the browser’s tab-throttling scheduler stops receiving timely updates, then wakes up and overwrites fresher state held in a foreground tab.

A SharedWorker solves all three because it is a single JavaScript execution context shared across every same-origin browsing context — tabs, iframes, even other workers — connected via MessagePort. One socket, one IndexedDB writer, one authoritative state tree, N read-only subscribers.

#Architectural Breakdown: Why a SharedWorker Architecture Wins Over BroadcastChannel Alone

BroadcastChannel is frequently proposed as a lighter alternative, but it only solves the fan-out problem for messages already produced — it cannot own the network connection or arbitrate writes, because every tab still runs its own JavaScript instance. A SharedWorker architecture differs structurally: the worker itself becomes the network client and the database owner, and tabs become dumb rendering surfaces that subscribe to a port.

SharedWorker architecture

#
Leader Election Inside the SharedWorker Architecture

The SharedWorker lives for as long as any owning document is alive, and it starts on the first connect event. There is no observable disconnect event for ports, so you cannot rely on the worker seeing when a tab goes away.

Within that limit, the worker itself acts as the leader, and there is no need for a distributed lock manager across tabs. Election only becomes necessary as a fallback where SharedWorker is unavailable.

Support varies by browser and version (including Safari, iOS Safari, Chrome for Android and embedded WebViews), so check current MDN or caniuse compatibility data for your target matrix and detect the feature at runtime rather than by user agent.

In the fallback, elect a leader tab using the Web Locks API and have that tab behave as the broker via BroadcastChannel.

#Implementation Logic

Implementing this SharedWorker architecture in production involves four discrete stages: worker registration, port handshake, message protocol design, and graceful teardown.

#
1. Registering the Worker from Each Micro-Frontend Shell

1// client.js — loaded by every micro-frontend shell instance
2if (typeof SharedWorker === 'undefined') {
3  // use the leader-election fallback instead
4} else {
5  const worker = new SharedWorker('/workers/state-broker-v13.js', { name: 'state-broker-v13' });
6
7  worker.onerror = (e) => reportWorkerFailure(e);
8
9  worker.port.start();
10  worker.port.postMessage({ type: 'REGISTER', tabId: window.__TAB_ID__ });
11
12  // a tab woken from background re-registers in case the worker dropped its port
13  document.addEventListener('visibilitychange', () => {
14    if (document.visibilityState === 'visible') {
15      worker.port.postMessage({ type: 'REGISTER', tabId: window.__TAB_ID__ });
16    }
17  });
18
19  worker.port.onmessage = (event) => {
20    const { type, payload } = event.data;
21    switch (type) {
22      case 'PING':
23        worker.port.postMessage({ type: 'PONG', tabId: window.__TAB_ID__ });
24        break;
25      case 'STATE_PATCH':
26        applyPatch(payload); // JSON-patch applied to local read-only store
27        break;
28      case 'CONN_STATUS':
29        updateConnectionBadge(payload.status);
30        break;
31    }
32  };
33
34  function dispatchAction(action) {
35    worker.port.postMessage({ type: 'ACTION', payload: action, tabId: window.__TAB_ID__ });
36  }
37}

#
2. The Worker Itself: Single Owner of Network and Storage

1// state-broker-v13.js — runs once, shared across all connected tabs
2const ports = new Map(); // port -> last-seen timestamp
3let socket;
4let shouldReconnect = false;
5let stateVersion = 0;
6let attempts = 0;
7
8// Placeholder: exponential backoff with a cap
9function backoff() {
10  attempts += 1;
11  return Math.min(30000, 500 * 2 ** attempts);
12}
13
14// Placeholder: validate the message shape, then perform the IndexedDB write
15// (the worker is the only writer) inside try/catch
16async function handleAction(port, action) {
17  try {
18    if (!action || typeof action.kind !== 'string') throw new Error('invalid action');
19    // await writeToIndexedDB(action);  // implement with short transactions
20  } catch (err) {
21    port.postMessage({ type: 'ACTION_ERROR', error: String(err) });
22  }
23}
24
25function connectUpstream() {
26  if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) return;
27  shouldReconnect = true;
28  socket = new WebSocket('wss://gateway.internal/prices');
29  socket.onopen = () => { attempts = 0; };
30  socket.onmessage = (msg) => {
31    stateVersion += 1;
32    broadcast({ type: 'STATE_PATCH', payload: JSON.parse(msg.data), v: stateVersion });
33  };
34  socket.onclose = () => {
35    socket = undefined;
36    if (shouldReconnect) setTimeout(connectUpstream, backoff());
37  };
38}
39
40function broadcast(message) {
41  for (const port of ports.keys()) port.postMessage(message);
42}
43
44self.onconnect = (event) => {
45  const port = event.ports[0];
46  ports.set(port, Date.now());
47  port.start();
48
49  port.onmessage = (e) => {
50    // any message, including REGISTER, re-adds a port that was dropped
51    ports.set(port, Date.now());
52    if (e.data.type === 'ACTION') handleAction(port, e.data.payload);
53  };
54
55  port.onmessageerror = (e) => console.error('message deserialisation failed', e);
56  connectUpstream(); // no-op if a socket already exists
57};

#
3. Cross-Origin Isolation for Advanced Cases

If your SharedWorker architecture needs SharedArrayBuffer for zero-copy state hand-off (common when the worker is also decoding a binary market-data feed), you must serve the shell under cross-origin isolation headers, or the browser silently disables the buffer. Only COOP same-origin and COEP require-corp are required. Record your current header configuration and test on a pilot environment first, because these headers can break embedded content; to undo, remove the headers:

1location / {
2    add_header Cross-Origin-Opener-Policy "same-origin" always;
3    add_header Cross-Origin-Embedder-Policy "require-corp" always;
4}

Set Cross-Origin-Resource-Policy only on the specific resources that other origins need to embed, with a value suited to each (same-site or cross-origin). Full behaviour of these headers is documented in the MDN SharedArrayBuffer reference — treat this as mandatory reading before enabling COEP on a shell that embeds third-party iframes, since it will break any cross-origin resource lacking a matching CORP header.

#
4. Graceful Port Teardown

Tabs close without warning, and postMessage on a port does not throw when the peer has gone, so the worker must detect dead ports with a reply-based heartbeat rather than trust an explicit disconnect message or onmessageerror. Each tab answers a PING with a PONG, and the worker drops ports whose last reply is too old:

Cross-Tab Sync via SharedWorker Architecture architecture diagram 2
1const TIMEOUT_MS = 45000;
2
3setInterval(() => {
4  const now = Date.now();
5  for (const [port, lastSeen] of ports) {
6    if (now - lastSeen > TIMEOUT_MS) {
7      ports.delete(port);
8    } else {
9      port.postMessage({ type: 'PING' });
10    }
11  }
12  if (ports.size === 0 && socket) {
13    shouldReconnect = false;
14    socket.close();
15  }
16}, 15000);

Note that a heavily throttled background tab may miss the timeout and be dropped; the client sends a REGISTER message when it becomes visible again, and the worker re-adds the port to its map.

#Failure Modes & Edge Cases

The primary weakness of a SharedWorker architecture is that it introduces a single point of failure per browser process. If the worker throws an uncaught exception, every tab loses its data feed simultaneously rather than just one. Design considerations follow.

  • Worker crash without restart signal: an unhandled exception in the worker can terminate it silently, and error reporting for SharedWorkers is limited; attach worker.onerror on the SharedWorker object in each tab, but do not depend on it alone. Always wrap handleAction in try/catch and report failures back explicitly over the port rather than letting them propagate.
  • Version skew across shell deployments: if tab A loads shell v12 and tab B loads shell v13 after a deploy, both may connect to the same cached SharedWorker instance (keyed by URL + name). Version the worker script path (state-broker-v13.js) so a deploy forces a clean worker restart rather than mixing message schemas.
  • Browser and WebView support gaps: SharedWorker support differs across browsers, versions, iOS and embedded WebViews, and Chrome for Android support arrived late. Check current MDN or caniuse data for your target matrix, use feature detection, and make sure your fallback path fully replicates broker semantics using a leader-elected tab and BroadcastChannel, tested independently — don’t assume feature parity.
  • DevTools inspection gaps: SharedWorkers don’t appear in the standard tab console; debug via chrome://inspect/#workers or Firefox’s about:debugging, and budget extra triage time during incidents because stack traces are harder to correlate with a specific tab.
  • Storage quota contention: because the worker is now the sole IndexedDB writer, a slow transaction blocks state delivery to every tab, not just one. Batch writes and keep transactions short-lived to avoid head-of-line blocking across the whole browser process.

#Scaling & Security Trade-offs

A SharedWorker architecture trades per-tab isolation for resource efficiency, and that trade needs to be justified against your actual concurrency profile before adoption. Pilot it with a small group of users before a fleet-wide rollout, and keep the per-tab path switchable so you can roll back. Compare it against the alternatives your team is likely already running as part of broader architectural patterns for micro-frontend composition:

  • Connection cost: SharedWorker reduces N WebSocket connections to 1 per browser process; BroadcastChannel-only designs still open N connections, one per tab, so gateway load scales linearly with tabs opened rather than users.
  • Fault isolation: per-tab sockets fail independently (better isolation, worse efficiency); a shared broker fails for the whole process at once (worse isolation, better efficiency) — choose based on whether your product tolerates a full-process reconnect glitch.
  • Browser coverage: support for SharedWorker is not uniform across browsers, versions and WebViews, so verify it against current compatibility data; any client without it forces a dual-implementation maintenance burden.
  • Security surface: a compromised micro-frontend bundle running inside a tab can post arbitrary ACTION messages to the shared port. Validate and schema-check every inbound message inside the worker — never trust e.data shape, since it now represents a trust boundary between origins-in-practice even though technically same-origin.
  • Memory footprint: a single long-lived worker holding cached state for the session lifetime avoids the repeated rehydration cost paid by N independent tab stores, at the cost of one process holding a growing heap that needs explicit pruning logic.

For estates running more than a handful of concurrently open tabs per user — trading terminals, admin consoles, ops dashboards — the connection and consistency savings from a SharedWorker architecture comfortably outweigh the added debugging complexity, provided the fallback path is treated as a first-class implementation rather than an afterthought.

Evidence trail

Sources and verification

Primary documentation and external technical references used in this article.

  1. 01Web Locks APIdeveloper.mozilla.org
  2. 02MDN SharedArrayBuffer referencedeveloper.mozilla.org

About this page

Credited to

Dates

Published

Last updated

Corrections

  • : Corrected during a review of published articles. Details
Reader Interaction

Comments

Add a thoughtful note on Cross-Tab Sync via SharedWorker Architecture. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Engineering insights, direct to you.

Receive the latest Systems Engineering tutorials, production guides, Engineering Labs and operational best practices.