Port Authority

Port patterns / Across windows, tabs and reloads

Multi-tab OPFS database leader with automatic failover

Fast local SQLite engines in the browser — wa-sqlite, PGlite, PowerSync, ElectricSQL, Evolu, LiveStore and Rocicorp Zero — rely on OPFS FileSystemSyncAccessHandle, which only works inside a Dedicated Worker and allows just one exclusive writer per file. Every tab here connects to a small SharedWorker coordinator and queues for a Web Lock. Whoever wins spawns the Dedicated DB Worker, opens OPFS, and mints a direct MessagePort for each follower tab so writes never bounce through the SharedWorker. Close Tab 1 and the browser drops its lock straight away: Tab 2 wins election, reopens the same OPFS file with every row intact, and hands Tab 3 a fresh direct port.

When you'd use this

A local-first web app backed by SQLite in OPFS — like a mail client, issue tracker or notes tool — is open in three tabs at once. Because FileSystemSyncAccessHandle only works in a Dedicated Worker and permits a single writer, only one tab can own the database file. Every tab queues for a Web Lock and connects to a tiny SharedWorker. The winning tab opens OPFS in its Dedicated Worker and hands every other tab a direct MessagePort straight to that worker. When the user closes the leader tab, the browser drops its Web Lock immediately, the next tab takes over the same OPFS file with zero lost writes, and the coordinator hands surviving tabs fresh direct ports.

Code

// Every tab queues for the exclusive leader lock (FIFO order)
navigator.locks.request("db-leader", async () => {
  const db = new Worker("/opfs-db-worker.js");
  const ctrl = new MessageChannel();
  db.postMessage({ type: "attach-coord" }, [ctrl.port1]);
  coord.port.postMessage({ type: "announce-leader" }, [ctrl.port2]);
  return new Promise(() => {});                // held until this tab closes
});

// Inside the leader's Dedicated DB Worker (OPFS SyncAccessHandle)
const handle = await fileHandle.createSyncAccessHandle();
coordPort.onmessage = ({ data: { forTab } }) => {
  const { port1, port2 } = new MessageChannel();
  attachClient(port1);                         // follower writes hit this worker directly
  coordPort.postMessage({ minted: forTab }, [port2]);
};

In practice

// In every tab of a local-first notes or email app
const coord = new SharedWorker("/opfs-coord.js");
let dbPort = null;

coord.port.onmessage = ({ data, ports }) => {
  if (data.type === "db-port") {
    dbPort?.close();
    dbPort = ports[0];                          // straight to the leader's OPFS worker
    dbPort.onmessage = ({ data: msg }) => renderRows(msg.rows);
  }
};

// Every tab queues for leadership; only one holds the OPFS SyncAccessHandle
navigator.locks.request("app-sqlite-leader", async () => {
  const worker = new Worker("/sqlite-opfs-worker.js");
  const ctrl = new MessageChannel();
  worker.postMessage({ type: "attach-coord" }, [ctrl.port1]);
  coord.port.postMessage({ type: "announce-leader" }, [ctrl.port2]);
  return new Promise(() => {});                // released automatically when the tab closes
});

How it works

The Origin Private File System gives browsers fast synchronous file I/O through FileSystemSyncAccessHandle, which is what lets WASM SQLite builds like wa-sqlite and PGlite approach native disk speed. The catch is a strict platform rule: createSyncAccessHandle() is only exposed inside a Dedicated Worker, never in a window or a SharedWorker, and only one worker can hold an exclusive sync handle on a given file at once.

Putting a SharedWorker in front as a tiny coordinator solves the multi-tab topology without proxying database traffic. Every open tab connects to the SharedWorker and immediately queues for the same exclusive Web Lock (navigator.locks.request("db-leader", ...)). Whichever tab gets the lock spawns the Dedicated DB Worker, opens OPFS, and hands the SharedWorker a control port to that DB Worker.

Whenever a follower tab joins, the SharedWorker asks the leader's DB Worker to create a fresh MessageChannel and transfers one end back to the follower. From that point on, every query and write travels straight from the follower tab to the leader's Dedicated Worker. Neither the SharedWorker nor the leader tab's main thread touches the SQL payload.

When the leader tab closes or crashes, the browser releases its Web Lock automatically. The next tab waiting in the lock queue wins election, boots a fresh Dedicated DB Worker against the exact same OPFS file, reads back every flushed record, announces itself to the SharedWorker, and mints fresh direct ports to every surviving follower.

Step by step

What each press of Next does in the demo above.

  1. Tab 1 elects itself leader. Tab 1 connects to the SharedWorker, wins the Web Lock, boots a Dedicated Worker holding OPFS SyncAccessHandle, and writes row #1.
  2. Tab 2 & Tab 3 join. Tab 2 and Tab 3 open, queue behind Tab 1 on the Web Lock, and receive direct db ports straight to Tab 1's Dedicated DB Worker.
  3. Tab 2 & Tab 3 write rows. Both followers write straight over their yellow direct ports. The SharedWorker carries zero database writes, and all tabs sync to 3 rows.
  4. Close Tab 1. Tab 1 is destroyed. The browser releases its Web Lock immediately, Tab 2 wins failover, reopens the same OPFS file with all 3 rows, and hands Tab 3 a fresh db port.
  5. Tab 3 writes after failover. Tab 3 writes row #4 down its new port to Tab 2's DB Worker. All 4 rows are committed with zero lost.

What you can build with it

Other ideas

  • Local-first SQLite or Postgres in multi-tab web apps (the exact architecture used by wa-sqlite, PGlite, PowerSync, ElectricSQL, Evolu, LiveStore and Rocicorp Zero).
  • A single write-ahead log or local search index (such as Tantivy or DuckDB-WASM) shared across every open tab without corrupting OPFS handles.
  • Leader-elected background sync engines where one tab owns the sync socket and local DB while every other tab reads and writes over direct ports.

Things to try

  • Step through all five buttons and watch the SharedWorker's meta line stay at DB writes relayed: 0 while Tab 2 and Tab 3 write rows #2 and #3.
  • Check the backend label in Tab 1 and Tab 2 after failover: in desktop Chromium both report OPFS SyncAccessHandle, proving Tab 2 reopened the real file after Tab 1 died.
  • Press Back after failover or Start again to verify that each run uses a fresh lock and OPFS file with no leftover state.

Gotchas

  • When a leader tab closes, the browser releases its Web Lock almost instantly, but the OS file lock on the terminating worker's FileSystemSyncAccessHandle can lag by a few tens of milliseconds. Always retry createSyncAccessHandle() with a short backoff on NoModificationAllowedError before giving up or falling back.
  • Holding a Web Lock for a tab's lifetime can prevent the back/forward cache (bfcache) from freezing that tab in some browsers. If bfcache matters, release the lock on pagehide and re-acquire it on pageshow.
  • SharedWorker isn't available everywhere — Safari on iOS added it in 16 and Chrome on Android only shipped it in 148. Production libraries often fall back to a BroadcastChannel plus Web Locks relay when SharedWorker is missing, even though BroadcastChannel can't transfer ports or buffers.
  • Never store transient state only in the leader's memory if you expect clean failover: flush writes to OPFS (or IndexedDB) before acknowledging commits to follower tabs, and make follower clients retry in-flight queries when a new db port arrives.

References

The web platform features this page mentions, with what each one is, its documentation on MDN and the specification that defines it.

Origin private file system
Origin-scoped file storage hidden from the user's normal filesystem. A worker can open a file in it for fast, exclusive synchronous access. MDNFile System Standard
Web Workers
Scripts that run on their own thread, away from the page. MDNHTML Standard
SharedWorker
A worker that every page on the same origin can connect to. Each page that connects gets a port to it. MDNHTML Standard
Web Locks
Lets pages and workers on one origin take a named lock, so that only one of them does a piece of work at a time. MDNWeb Locks
MessagePort
One end of a message channel. Whatever is posted into it comes out of the other end, and it can be sent to another page, frame or worker. MDNHTML Standard
MessageChannel
Makes a new pair of joined ports, port1 and port2. MDNHTML Standard
Back/forward cache
The browser keeps a page it has left, whole and paused, so that Back shows it at once. A page in the cache receives no messages. MDNHTML Standard
pagehide event
An event fired when a page is being left: closed, navigated away from, or put in the back/forward cache. MDNHTML Standard
BroadcastChannel
A named channel that every page and worker on the same origin can join. A message goes to all of them. It cannot carry ports or other transferable objects. MDNHTML Standard
IndexedDB
A database in the browser that belongs to one origin. It can store most things that can be posted, including a CryptoKey. MDNIndexed Database API

For more, see Further reading: articles, talks, papers, libraries and the specifications, collected in one place.