When a web email client is open in several tabs, which state should sync between them, which must not, and how would you carry it?
answer
- account state versus tab state
- sign-out reaches every tab
- never sync the open draft
- send notices, not copies
- the server stays the truth
basics
~20 sSync what describes the account, not the tab: sign-out, read flags and unread counts, preferences. Never sync the open draft, selection or filters. Post small change notices on a BroadcastChannel, treat them as hints, and revalidate from the server.
solid answer
~50 sI split state into **account state**, which every tab must agree on, and **tab state**, which belongs to one window. Sign-out, a conversation marked read, unread counts and preferences such as the reading-pane layout are account state; the open thread, search filters, scroll position and the draft being written are tab state and must not sync. To carry it I would post small notices on a `BroadcastChannel`: "signed out", "conversations c-981 and c-977 changed". Every other same-origin tab receives them; the sender does not, so it applies its own change directly. A receiving tab either patches its cached records or marks them stale and refetches. The `storage` event is the alternative when the value is already persisted, such as the layout preference, but it fires only on a storage write. Either way the notice is a hint: a tab that was not listening must still revalidate from the server.
code
javascript · 22 linesconst channel = new BroadcastChannel('mail-app');
function signOut() {
clearInMemoryMailData(); // this tab will not receive its own message
channel.postMessage({ v: 1, type: 'signed-out' });
location.assign('/signed-out');
}
function afterMarkRead(ids) {
channel.postMessage({ v: 1, type: 'conversations-changed', ids });
}
channel.onmessage = (event) => {
const msg = event.data;
if (msg.v !== 1) return; // ignore formats this build does not know
if (msg.type === 'signed-out') {
clearInMemoryMailData();
location.assign('/signed-out');
} else if (msg.type === 'conversations-changed') {
markStale(msg.ids); // refetch or patch from the server, not from the message
}
};go deeper
Recall that several tabs of the same app do not share memory, and that signing out in one must still sign out the others.
Sort the email client's state into account state and tab state, then choose between BroadcastChannel and the storage event and say what each delivers to whom.
Design for the tab that missed the message: notices as hints, revalidation on becoming visible, sign-out detected from responses, and the draft guarded against two editors.
Set the cross-tab contract for the app: a versioned message format, which features may post, and how a mixed-build fleet of open tabs stays safe during a deploy.
## Account state versus tab state A user with the email client open in three tabs expects some things to be true everywhere and others to be private to one window. The design starts by sorting state into two kinds: - **Account state** describes the user's mailbox or session and has one correct value at any moment. Tabs must converge on it. - **Tab state** describes what one window is doing. Two tabs legitimately differ. | State | Sync across tabs? | Why | |---|---|---| | Signed out, or signed in as someone else | **yes, immediately** | a tab still showing mail after sign-out is a privacy bug | | A conversation's read flag, labels, folder | **yes** | the same mailbox; the other tab's list is now wrong | | Folder unread counts | **yes, by refetch** | server-carried numbers; a notice tells the tab to refresh | | Reading-pane layout, theme | **yes** | preferences describe the user, not the window | | Open thread, folder, search filters | **no** | each tab is a different view; that is why the user opened it | | The draft being composed | **no** | two tabs writing one body would overwrite each other | | Scroll position, open menus | **no** | purely per window | `sessionStorage` is partitioned per tab and per origin, so anything kept there is per-tab by construction and is not shared with the other open tabs. ## Carrying the notice: BroadcastChannel or the storage event Two browser mechanisms reach other same-origin tabs; how each delivers is its own topic, and the design only needs their shape. | | `BroadcastChannel` | `storage` event on `localStorage` | |---|---|---| | Trigger | an explicit `postMessage` on a named channel | a write to `localStorage` | | Reaches | every other channel object with that name in same-origin windows, tabs, frames and workers | other documents sharing the storage area, never the window that wrote | | Payload | any structured-cloneable value | a change to one stored key/value pair | | Fits | notices with no reason to persist: "signed out", "these ids changed" | values already persisted, such as the layout preference | For this app, `BroadcastChannel` carries the change notices and sign-out; the preference can ride either, and many teams let the persisted preference's own `storage` event do it. The message format is the app's to design: the channel defines no protocol. ## Send notices, not copies - Post **what changed**, as ids and a type, not the changed records. Each tab already has a client cache of server data; it can patch the record it holds or mark the entry stale and refetch. - Keep messages small and versioned, so a tab running an older build ignores what it does not understand instead of mis-applying it. - Remember the sender does not receive its own message; the tab that acted updates itself directly, as it would with one tab. - Keep payloads to ids rather than message bodies: any same-origin script can listen on the channel, and each tab can read the data through its own authenticated requests. ## The stale second tab A notice is a hint, not a log. There is no replay for a tab that opened later or was not listening, so: 1. On becoming visible again, a tab revalidates the entries it is showing from the server. 2. On any request that answers "not signed in", a tab treats it as sign-out even if it missed the broadcast. 3. Counts are always replaced by the server's figure when they next arrive; a local delta from another tab's notice is only a bridge. The server remains the single source of truth; cross-tab messages only shorten the time a tab is wrong. ## The draft that must not sync If the same server draft is open in two tabs, syncing keystrokes between them produces two editors overwriting each other. Better designs: - open a draft in only one tab and show "open in another tab" elsewhere; - or let both edit and save with a version, so the second save is rejected and the user chooses. Which tab performs a shared background job, such as the one syncing loop, is a separate leader-election decision made with Web Locks, and belongs with the offline design.
- Why not sync by writing the whole mailbox state into localStorage and listening for the storage event?Web Storage is synchronous, so serialising a mailbox on every change blocks the main thread; it persists mail to disk that nobody asked to persist; and every tab then parses the whole blob on every write. Send a small notice instead and let each tab refetch what it shows.
- A user signs in as a different account in tab B while tab A shows the old account's inbox. What should tab A do?Treat it like sign-out: drop every in-memory record, stop showing mail, and reload into the new session. A broadcast "account changed" with the new account id lets it respond immediately; a request that comes back for a different user than the tab expects is the backstop if the message was missed.
- Expects the storage event to fire in the tab that wrote the value
- Syncs the open draft's keystrokes between tabs
- Keeps the session flag in sessionStorage and expects other tabs to see it
- Posts full conversation records on the channel instead of ids
- Assumes a tab that missed a broadcast is still up to date