Skip to content

    Frontend System Design

    Cross-Tab Sync With BroadcastChannel

    Keep browser tabs in step with BroadcastChannel: design the message contract, avoid echo and stale data, elect one polling tab with Web Locks, help late tabs.

    By Published 13 min read

    • frontend-system-design
    • state-management
    • broadcastchannel
    • web-locks
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: State Persistence and Synchronization

    What you'll learn: By the end of this lesson you will be able to say what a BroadcastChannel delivers and to whom, design the small message contract that tabs need on top of it, stop a tab from echoing what it just received or accepting stale data, let a late tab catch up, use a Web Lock so that only one tab does shared work such as polling, and choose between a channel, the storage event and a shared worker.

    Think of an open-plan office with a shared intercom. Anyone can speak on a named line, and everyone listening on that line hears it, except the speaker. Nobody hears what was said before they sat down, and the intercom has no rule for what a sentence means or who should act on it. If three people each phone the supplier with the same question, someone has to be put in charge.

    Browser tabs of one site are that office. This lesson is about what to build on top of the channel: a message contract, rules against echo and stale data, a way to catch up late arrivals, and a way to choose one tab to do shared work.

    The running example is a shop header that shows a signed-in state and an unread-notifications badge, open in several tabs. The lab's server and numbers are made up for the lesson.

    The core idea

    1. A channel is a named line that tabs of one origin can join. Messages are copied, arrive later, and never go to the object that sent them. The API gives them no meaning, so you design the protocol.
    2. A message is an event, not state. A tab that joins late missed it. Anything a new tab must know needs a way to ask for it or a place to read it.
    3. Broadcasting tells; a lock decides. If three tabs poll the same endpoint, a message cannot make two of them stop. A lock gives one tab the job.

    Three illustrations run through the lesson: a minimal example (a sign-out that every tab follows), a realistic example (the header badge, with one tab polling for all) and a failure example (a new leader whose messages every tab ignores).

    What a channel gives you

    MDN describes the Broadcast Channel API as basic communication between browsing contexts (windows, tabs, frames, iframes) and workers on the same origin. A BroadcastChannel is created with one argument, the channel's name. Four rules matter.

    Rule What it means for your code
    Same origin and storage partition An iframe from another site embedded in your page may not reach your tab, even with the same origin.
    Not delivered to the sender's own object The tab that posts does not get the message back, so it must apply its own change locally.
    Copied with the structured clone algorithm You can send objects without serializing them yourself, but a function or DOM node cannot be sent.
    No semantics MDN says the API "doesn't associate any semantics to messages". Message types, versions and replies are yours to define.

    The HTML Standard adds how delivery works: for each destination it queues a task on the DOM manipulation task source, so a message arrives after the current code finishes, and a destination closed before its task runs does not get it. The standard sorts destinations that share an agent in creation order but says this "does not define a complete ordering", so do not build on the order in which several tabs receive a message.

    postMessage throws InvalidStateError on a closed channel and DataCloneError for data that cannot be cloned. A message that cannot be deserialized on arrival fires a messageerror event. Call close() to leave a channel, which allows the object to be garbage collected. MDN lists the API as available in Web Workers and widely available since March 2022, and names detecting a login or logout in another tab as a use case.

    Figure 1. Three tabs on one named channel

    Three tabs share a named channel; a message reaches every tab except the senderTab 1 to Channel (postMessage); Channel to Tab 2 (message event); Channel to Tab 3 (message event)Tab 1: postsTab 1postsChannel: shop-sessionChannelshop-sessionTab 2: listensTab 2listensTab 3: listensTab 3listenspostMessagemessage eventmessage event

    How to read this: the sender is on the left and gets no copy. Each listening tab gets its own copy later, as an event. Tabs that are not on this channel (another name, another origin) hear nothing.

    Minimal example: sign out everywhere

    When a user signs out in one tab, the others should not keep showing private data. That tab clears its own state, then posts { v: 1, type: "sign-out", from }. Each receiver sets its state to signed out and does not post again. Without that last rule, three tabs would answer each other forever. The lab's first scenario shows one message delivered to each of the two other tabs and none back to the sender. The cross-app communication lesson shows what happens to a store that rebroadcasts everything it adopts.

    Which tool for which job

    The storage event, covered in State Persistence and Synchronization, fires when another document updates a shared storage area, not on the window that made the change, and needs a value written to storage to carry the message. A shared worker is one script instance that several same-origin pages connect to through ports; MDN says it stays alive as long as any open page holds a reference to it, and marks it Baseline 2026, newly available. The Web Locks API lets scripts in different tabs coordinate: while one holds a lock, no other script in the origin can acquire it.

    These combine. A common design is a channel to announce, a lock to choose who works, and storage for what must survive a reload.

    Design the message contract

    Because the API has no semantics, every receiver faces untrusted input: an old build of your own site may be open in another tab. The lab's contract has a few fields and a parser that returns nothing for anything else.

    • v: a protocol version. A receiver ignores a version it does not know.
    • type: sign-out, unread or hello.
    • from: the sender's tab id, for logs and tie-breaking.
    • seq and count, on unread only: a sequence number and the value.

    A message of an unknown version, a plain string or a wrong field type is counted and dropped, and never throws. The lab's fifth scenario shows tabs ignoring three bad messages while staying signed in. Treat what arrives on a channel like data from the network.

    Ordering is yours to define

    A message arrives later, so a receiver needs a rule for what to adopt. The lab uses a sequence number: a tab adopts an unread message only if its seq is higher than its own, which rejects a stale or duplicate one. It is the revision idea from the persistence lesson with the same limit: it picks a winner and does not merge. It suits a value that only the leader writes. Two tabs that edit the same thing need the conflict handling and CRDT lessons planned in this course.

    One tab does the work: leader election

    Suppose the header polls /notifications every interval to update the badge. With three tabs open, the server gets three requests for one answer. A message cannot fix that, because every tab would announce at the same time that it is polling.

    The Web Locks API is built for it. MDN gives the use case: if a web app in multiple tabs wants only one tab syncing data, each tab tries to acquire the same named lock and only one succeeds. That is the leader election pattern. Details to rely on:

    • navigator.locks.request(name, callback) takes a lock name and a callback that runs when the lock is granted. The lock is released when the callback returns, or when the promise of an async callback settles. So a leader's callback is an async function that does not finish until the tab is done being leader.
    • While a lock is held, other requests for the same name are queued. The W3C draft says only the first item in a queue is grantable and requests are returned in the order they were made.
    • Locks are scoped to an origin, and the API is available only in secure contexts (HTTPS).
    • The W3C draft terminates the locks and pending requests of an unloaded document, so a closed leader tab does not hold the lock forever. The draft calls the handling of terminated workers "vaguely defined", and MDN does not describe a crash, so do not design for guarantees beyond that.

    Figure 2. The leader polls once for everyone; when it closes, the next tab takes over

    sequenceDiagram accTitle: Leader election with a Web Lock accDescr: Three tabs request the same lock. Tab 1 is granted it and becomes the leader. At each interval tab 1 polls the server once and broadcasts the count with a sequence number. Tabs 2 and 3 wait in the queue and adopt the count. Tab 1 closes, its lock is released, tab 2 is granted it, polls the server and broadcasts the next sequence number, which tab 3 adopts. participant T1 as Tab 1 participant L as Lock "unread-poller" participant T2 as Tab 2 participant T3 as Tab 3 participant S as Server T1->>L: request (granted: leader) T2->>L: request (waits) T3->>L: request (waits) T1->>S: poll T1-->>T2: unread, seq 1 T1-->>T3: unread, seq 1 Note over T1: tab closes, lock released L->>T2: granted: leader T2->>S: poll T2-->>T3: unread, seq 2

    How to read this: the lock decides who works, and the channel carries the result. The sequence number continues across the hand-over, which is the point of the failure example below.

    Realistic example: the shop header badge

    The header shows a sign-in state and an unread badge on every page, and users often have several pages open. Each tab requests the lock unread-poller. The holder polls on a timer and posts unread messages. The others render what they receive and do not poll. The lab's second scenario compares the two designs in its model: with every tab polling, 12 requests reach the fake server over 4 intervals and 3 tabs, and with a leader, 4. These are counts from a model, not measurements.

    Catching up a late tab

    A message is an event, so a tab that opens later has no badge value until the next poll. The lab's tabs send hello when they open. The leader answers by posting its current value, and the late tab adopts it because its own seq is lower. The alternative is to write the last value to storage (see the persistence lesson) and read it on start.

    Figure 3. A late tab asks, and the leader answers

    sequenceDiagram accTitle: A late tab catches up accDescr: A new tab opens and broadcasts hello. The leader receives it and broadcasts its current unread value with its sequence number. The new tab adopts the value because its own sequence number is lower. participant N as New tab participant C as Channel participant L as Leader tab N->>C: hello C-->>L: hello L->>C: unread, count 7, seq 1 C-->>N: unread, count 7, seq 1 Note over N: seq 1 is higher than 0, adopt

    How to read this: the new tab starts with nothing, and the first useful message arrives two deliveries later. Until then, show a neutral state.

    Failure example: the new leader nobody believes

    If a new leader starts numbering at 1, the others already hold a higher number and drop its messages as stale. The count in tab 3 freezes at the old value while the leader shows the new one. The fix is that a tab numbers its next poll after the highest seq it has seen. The lab's third scenario prints both versions.

    Trade-offs

    Choice Gain Cost
    BroadcastChannel for events Simple, no storage write, works in workers Late tabs miss events; you write the protocol
    storage event Works with a value that survives reloads Writes to a synchronous store; the writing tab hears nothing
    One polling tab (Web Lock) Server load does not grow with tab count Hand-over logic; the leader may be a background tab
    Every tab polls No coordination code Load grows with open tabs
    Shared worker One owner of state and connections Different lifecycle; check support

    Build it: sign-out, a leader and a late tab

    Goal. Run a model of a channel and a lock manager through five scenarios and check each against the rules above.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no React, no DOM, no browser.

    cd examples/frontend
    pnpm install
    cd labs/cross-tab-sync
    pnpm test           # 15 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo, and compare it with the output below.
    2. In scenario 2, all tabs end with the same value, but the request counts differ.
    3. In scenario 3, compare continueSequence=true and false: in the second, tab 3 stays at the old value.

    Expected output, captured from a real run (Node 26.13.1, 2026-11-30):

    === 1. sign out in one tab, every tab follows
    before delivery: tab-1 signed in=false  tab-2 signed in=true  tab-3 signed in=true
    after delivery:  tab-1 signed in=false  tab-2 signed in=false  tab-3 signed in=false
    messages delivered: 2 (the sender's own channel gets none)
    
    === 2. polling cost: every tab polls, or only the leader polls (4 intervals, 3 tabs)
    every tab polls: server requests=12  messages posted=0  tab-1=8(seq 4)  tab-2=8(seq 4)  tab-3=8(seq 4)
    leader only:     server requests=4  messages posted=4  tab-1=8(seq 4)  tab-2=8(seq 4)  tab-3=8(seq 4)
    
    === 3. the leader closes: the next tab takes the lock (continueSequence on and off)
    continueSequence=true
      interval 1: leader=tab-1  tab-1=2(seq 1)  tab-2=2(seq 1)  tab-3=2(seq 1)
      tab-1 closed: leader=tab-2  waiting=[tab-3]
      interval 2: server unread=5, requests=2
                  tab-2=5(seq 2)  tab-3=5(seq 2)
    continueSequence=false
      interval 1: leader=tab-1  tab-1=2(seq 1)  tab-2=2(seq 1)  tab-3=2(seq 1)
      tab-1 closed: leader=tab-2  waiting=[tab-3]
      interval 2: server unread=5, requests=2
                  tab-2=5(seq 1)  tab-3=2(seq 1)
    
    === 4. a tab opens late and asks the leader for the current value
    just opened:        tab-3=0(seq 0)
    hello delivered:    tab-3=0(seq 0) (the leader's answer is queued)
    answer delivered:   tab-3=7(seq 1)
    
    === 5. what the channel and the receiver refuse
    post a function:        DataCloneError
    unknown version, a string, a wrong field type: ignored by tab-1=3, tab-2=3; still signed in: true
    post after close:       InvalidStateError

    What the lab does not show. No browser, no real BroadcastChannel or navigator.locks, no timing and no crash. The lock manager grants a lock at once and holds it until the tab closes, whereas the real API calls a callback later and releases the lock when its promise settles. The counts are outputs of a model with made-up intervals.

    Break it. In test/crossTab.test.ts, the test "a new leader that restarts its sequence at 1 is ignored by the others (the bug)" passes continueSequence: false. Change it to true and the test fails, because tab 3 now receives the new value. Change it back.

    In practice: a header badge that froze after a tab closed

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A storefront shows an unread-notifications badge in its header. Users keep several tabs open, and the notifications endpoint is rate-limited per user. With three tabs open, polling every interval makes three requests per user and sometimes hits the limit (illustrative).

    Starting architecture

    Figure 4. Starting point: every tab polls on its own

    Starting architecture: each tab polls the same endpoint and tabs do not know about each otherTab 1 to Notifications (GET); Tab 2 to Notifications (GET); Tab 3 to Notifications (GET)Tab 1: pollsTab 1pollsTab 2: pollsTab 2pollsTab 3: pollsTab 3pollsNotifications: rate limitedNotificationsrate limitedGETGETGET

    How to read this: request volume grows with the number of open tabs, which the team does not control.

    Options considered

    Option What it fixes What it costs Risk
    Longer polling interval Fewer requests Slower badge Still grows with tabs
    Leader tab with a Web Lock, results broadcast One request per interval per user Hand-over and message code A bug in hand-over freezes every other tab
    Shared worker polls for all One owner, no election Different lifecycle; support to check Another moving part

    The decision

    Field Decision record
    Context Several tabs poll one rate-limited endpoint.
    Decision Tabs request the lock unread-poller. The holder polls and broadcasts { v, type, from, seq, count }. Receivers adopt only a higher seq, ignore unknown messages, and answer nothing except hello. A new leader continues the sequence from the highest it has seen.
    Consequences, good Request count no longer grows with tabs; messages are versioned.
    Consequences, bad Sequence rule and hand-over need tests; a background tab may poll less often if the browser throttles its timers.
    Revisit when Several features need the same leader (consider a shared worker), or users need the badge on another device (move to server push).

    Rollout and verification

    1. Ship the message parser first, so tabs on the old build ignore the new message types.
    2. Test the hand-over: open three tabs, close the leader, and check that the other two keep updating.
    3. Watch requests per user as tab counts vary, and log when the leader changes.

    The 2 a.m. failure

    Support reports that the badge in older tabs stays at a number the user already cleared. After a user closes the first tab, the others show a stale count while the newest tab shows the right one (illustrative). The new leader restarted its seq at 1 and the other tabs, holding a higher number, dropped every message as stale.

    First three checks: (1) log seq on send and receive and look for a send lower than the receiver's; (2) check which tab holds the lock; (3) reproduce by closing the first tab. Mitigation: continue the sequence from the highest number seen. Follow-up: add the hand-over test above.

    Architect's notes

    • Treat the channel like a network. Version the message and ignore what you do not understand.
    • Apply locally, broadcast once, never rebroadcast. The sender does not hear itself, and a receiver does not speak for it.
    • Let a lock choose the worker. Do not elect a leader with messages.
    • Show a neutral state until the first message. A late tab has not missed an update, it has missed all of them.

    Common mistakes

    • Rebroadcasting what you received, which makes a message storm.
    • Assuming delivery is instant or ordered across tabs. Delivery is a later task.
    • No version in the message, so an old tab chokes on a new shape.
    • Treating a message as state, so late tabs show nothing.
    • Sending functions or DOM nodes, which throw DataCloneError.

    Key takeaways

    • A BroadcastChannel sends a copy to every other same-origin object on the same name, later, and not to the sender.
    • The API has no semantics: define a versioned message contract and validate what arrives.
    • Use a sequence number to ignore stale messages, and continue it when a new tab takes over.
    • A message is an event: a late tab must ask (hello) or read persisted state.
    • A Web Lock chooses one tab for shared work; a channel carries the result.
    • Locks of an unloaded document are terminated, but do not rely on behaviour the specs do not describe.

    Practice exercises

    Exercise 1 — Starter (45 min): Add a theme-changed message to the lab's contract, handle it without rebroadcast, and write a test that sends it from one tab and checks the other two.

    Exercise 2 — Intermediate (2 hours): Give the leader a leaving message on close, and show in a test that the next leader polls before its first scheduled interval.

    Exercise 3 — Advanced (half day): Two tabs may both change the cart. Explain why the seq rule loses a change, then sketch a message that carries an operation instead of a value.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments