Final StretchOrdered learning track

Production Checklist, Decision Matrix, and Final Skill Map

Learn Multiple Tab Orchestration and Web Worker In Action - Part 072

Final production checklist, API decision matrix, maturity model, skill map, exercises, and closing synthesis for advanced multiple tab orchestration and Web Worker systems.

27 min read5332 words
Prev
Finish
Lesson 7272 lesson track60–72 Final Stretch
#browser#web-worker#service-worker#architecture+15 more

Part 072 — Production Checklist, Decision Matrix, and Final Skill Map

Ini adalah bagian terakhir dari series.

Kita tidak akan menambah API baru. Kita akan merapikan seluruh materi menjadi decision matrix, checklist, maturity model, dan skill map. Tujuannya sederhana: setelah membaca 71 part sebelumnya, kamu harus bisa mengambil keputusan desain dengan cepat dan defensible.

Seorang engineer top-tier bukan hanya tahu new Worker() atau new BroadcastChannel(). Ia bisa menjawab:

  • siapa owner side effect ini?
  • state mana yang durable dan mana yang volatile?
  • apa yang terjadi bila tab freeze di tengah workflow?
  • apa yang terjadi bila worker crash setelah partial progress?
  • apakah message ini boleh duplicate?
  • apakah stale response bisa merusak session?
  • bagaimana cara membuktikan sistem ini aman lewat test?
  • bagaimana cara debug incident di production?

Itulah fokus final map ini.


1. Complete System Map

This is the operating model:

  1. UI talks to runtime, not directly to raw browser coordination APIs.
  2. Runtime owns lifecycle and cross-tab rules.
  3. Workers execute bounded compute.
  4. Service Worker coordinates network/cache/update.
  5. IndexedDB stores durable control state.
  6. BroadcastChannel signals changes.
  7. Web Locks elect/serialize local owners.
  8. Server still owns real business correctness.

2. The Core Invariants

If you remember only one section, remember this.

InvariantMeaning
No secret broadcastBroadcastChannel/storage event must not carry auth secrets.
No global side effect without ownershipRefresh, logout, replay, cache promotion, migration need lock/lease/owner.
No trust in cleanupTab close/freeze/crash may skip cleanup; recovery must rely on TTL/generation/reconciliation.
No state transition without generationSession/cache/worker/outbox transitions need monotonic epoch or equivalent stale guard.
No retry without idempotencyNetwork retry and offline replay need stable idempotency key.
No worker without backpressureWorker pool must have bounded queue, timeout, cancellation, and payload policy.
No cache update without versioningCache names/manifests must be versioned and promoted safely.
No migration without multi-tab policyIndexedDB upgrades can be blocked by old open tabs.
No production orchestration without observabilityTrace/message/lock/queue/session metrics are mandatory.
No correctness from BroadcastChannel aloneBroadcastChannel is signal, not durable store, not lock, not authority.

3. API Decision Matrix

Use this when deciding primitive.

NeedPreferMaybeAvoid
Send volatile signal to same-origin tabsBroadcastChannelstorage event fallbackIndexedDB polling only
Private request-response pipeMessageChannel / MessagePortdirect Worker postMessageBroadcastChannel RPC for sensitive data
CPU-heavy per-tab workDedicated Workerworker poolmain thread long task
Shared live hub across tabsSharedWorkerBroadcastChannel + IDBService Worker as always-on hub
Network/cache interceptionService Workerpage fetch wrapperSharedWorker
Cross-tab mutual exclusionWeb LocksIndexedDB lease fallbacklocalStorage claim without fencing
Durable metadataIndexedDBserver statelocalStorage for complex state
Large binary payloadOPFS / transferable ArrayBufferIndexedDB blob referencehuge structured clone object
Static/API response artifact cacheCache APIOPFS for custom blob layoutlocalStorage
Offline command replayIndexedDB outbox + Web LocksBackground Sync triggerin-memory queue
Render-heavy canvasOffscreenCanvas in workermain-thread canvas with chunkingDOM-heavy worker fantasy
Shared memory low-latency data planeSharedArrayBuffer + Atomicstransferable buffersJSON message loop
Update all tabs about logoutBroadcast metadata + durable markerstorage event fallbacktoken broadcast
Prevent notification duplicatesactive-tab arbitration + dedupe storeService Worker visibility/focus checkeach tab shows independently

4. API Capability Map

Decision heuristic:

  • If the data must survive reload, do not rely on BroadcastChannel.
  • If the operation must not duplicate, do not rely on presence alone.
  • If the payload is huge, do not structured-clone object graphs casually.
  • If the work touches DOM, it cannot run in normal worker.
  • If the work needs background network/cache coordination, consider Service Worker.
  • If the work needs true server-side correctness, do not pretend browser locks are enough.

5. Lifecycle Checklist

Browser lifecycle is hostile to naive code.

Event/StateWhat to doWhat not to assume
visibilitychange to hiddenpause non-critical work, flush small telemetry, reduce heartbeatpage will definitely unload
visible/focus restorereconcile session, presence, cache update, outbox, stale datalocal memory is current
pagehidebest-effort BYE/shutdownasync cleanup will finish
bfcache restorerevalidate runtime generation/session/cachepage was freshly loaded
frozen/discardedrecover on next visible/startuptimers kept running accurately
tab closedexpire via TTL/leaseBYE message was sent
worker terminatedreject pending tasks, restart if safeworker finished current operation
Service Worker controllerchangereconcile app/SW versionold/new worker share same state
IDB versionchangeclose old connection or prompt reloadmigration can always proceed immediately

Production rule:

Cleanup is optimization. Reconciliation is correctness.


6. Message Protocol Checklist

Every message family should answer these questions.

QuestionRequired answer
What is the message kind?stable string enum
Is it command, event, query, or response?explicit category
Is it durable?yes/no
Can it duplicate?yes/no + dedupe strategy
Can it arrive late?yes + expiration/generation guard
Can it reorder?yes + sequence/generation guard
Does it contain secret?preferably no; if yes, justify private channel
Does it need ACK?yes/no
Does it need retry?yes/no + timeout
Does it need idempotency key?yes for side effects
What is the version compatibility story?schema/protocol version
How is it observed?traceId/messageId/telemetry fields

Envelope minimum:

{
  protocolVersion,
  appId,
  appVersion,
  kind,
  scope,
  messageId,
  traceId,
  sender,
  issuedAt,
  expiresAt,
  generation,
  idempotencyKey,
  payload
}

Anti-patterns:

  • raw object broadcast without kind/version;
  • treating message event as trusted;
  • no messageerror handling;
  • using local clock as business ordering authority;
  • sending object instances and expecting prototypes/methods to survive structured clone;
  • no expiry for event-like messages;
  • no stale guard for responses.

7. Worker Checklist

Before introducing worker, ask whether it improves the actual bottleneck.

AreaChecklist
WorkloadCPU-bound or blocking enough to justify worker
Ownershipmain thread owns UI, worker owns computation only
Payloadclone/transfer/shared memory decision made
Queuebounded queue and max in-flight count
Cancellationqueued and running task behavior defined
Timeoutevery task has deadline
Errorerror DTO, worker error, messageerror, poison task policy
Restartgeneration token and pending rejection
Memorypayload size budget, buffer reuse, cleanup
Observabilityqueue depth, task latency, failure code, payload size
Deploymentmodule worker path, CSP, MIME, sourcemap, CDN path tested

Worker is good for:

  • parsing large CSV/JSON;
  • building search index;
  • diffing large documents;
  • compression/decompression;
  • image/canvas processing;
  • Wasm compute;
  • rule evaluation;
  • crypto/hash workloads via WebCrypto/Wasm/native APIs where appropriate.

Worker is not magic for:

  • DOM operations;
  • network latency;
  • bad state model;
  • too many small tasks with high message overhead;
  • memory explosion from clone-heavy payload;
  • cross-tab correctness by itself.

8. Worker Pool Decision Matrix

SituationUse one workerUse poolAvoid worker
Single large parseyesmaybeno
Many independent CPU tasksmaybeyesno
Ordered stream processingyesmaybe with partitioningno
Huge shared memory pipelineyes with SABmaybe advancedno
UI-only data formatting small listnonoyes
Network calls onlynonousually yes
DOM measurement/renderingnonoyes, unless OffscreenCanvas case
Wasm heavy computeyesyesno

Sizing heuristic:

poolSize = min(4, max(1, hardwareConcurrency - 1))

But real sizing must consider:

  • device class;
  • memory pressure;
  • workload duration;
  • main-thread pressure;
  • other tabs from same app;
  • browser throttling;
  • battery/thermal constraints.

9. Cross-Tab Coordination Checklist

ConcernCorrect pattern
Presenceheartbeat + TTL + lifecycle reconciliation
Leader electionWeb Locks, or IndexedDB lease fallback with fencing
Single-flight requestlock + result handoff + stale guard
Token refreshlock + re-check freshness inside lock + metadata broadcast
Logoutdurable revocation marker + abort + cleanup + broadcast
Notification suppressiondedupe key + active surface policy + TTL store
Offline replaydurable outbox + idempotency + single owner
Cache promotionversioned manifest + safe point + SW/client broadcast
Migrationversion gate + blocked handling + user prompt/reload policy
Shared worker hubconnection registry + heartbeat + reconnect/resubscribe

Golden rule:

A tab can claim intent. A lock/lease establishes local ownership. A generation/fencing token protects receivers from stale owners.


10. Auth and Session Checklist

Auth/session is where multi-tab orchestration becomes security-critical.

Required:

  • no refresh token in BroadcastChannel payload;
  • no token in localStorage for high-security contexts unless threat model explicitly accepts it;
  • refresh is single-flight across tabs;
  • refresh result is fenced by session generation;
  • logout is durable before cleanup;
  • protected requests can be aborted;
  • 401 retry is bounded;
  • revocation wins over refresh;
  • bfcache restore revalidates session;
  • worker tasks do not keep stale secret/session context;
  • Service Worker does not become hidden auth authority unless deliberately designed;
  • tenant switch invalidates relevant projections/cache/outbox;
  • all session transitions observable.

Session state machine:


11. Storage Checklist

StorageUse forAvoid for
Memoryhot runtime statedurable truth
sessionStoragetab-scoped ephemeral hintscross-tab global session truth
localStoragetiny compatibility signal/legacy fallbacksecrets, large data, complex transaction
IndexedDBdurable metadata, outbox, projection, dedupehuge hot byte streams without design
Cache APIrequest/response artifacts, app shell, API cachearbitrary mutable database semantics
OPFSlarge files, staged payload, worker-heavy byte datametadata querying
Cookiesserver auth/session mechanismclient orchestration state

Rules:

  1. Control-plane metadata goes to IndexedDB.
  2. Data-plane large payload goes to OPFS/Cache or transferables.
  3. Durable state must have schema version.
  4. Migration must handle open tabs.
  5. Cleanup must be scoped by session/tenant/version.
  6. Quota/eviction must be treated as real failure.
  7. Sensitive data requires explicit retention policy.

12. Offline and Replay Checklist

ConcernRequired design
Command identityidempotency key generated before first attempt
Unknown outcomeretry same idempotency key, reconcile if necessary
Orderingdependency graph or aggregate sequence
OwnershipWeb Lock/lease around replay loop
Authpause/reconcile on 401/403/session transition
Conflictstore conflict state; do not silently overwrite
PayloadpayloadRef for large data
Retryexponential backoff + max attempts + dead-letter
Observabilityattempts, age, last error, owner, batch latency
Cleanupcompact acked/dead records according to policy

Delivery semantics map:

Desired phraseReality
exactly oncenot available end-to-end from browser alone
at most oncepossible, but may lose operation
at least oncepossible with durable retry, but duplicates possible
effectively onceidempotency + dedupe + reconciliation

13. Service Worker Checklist

Service Worker is powerful but not a daemon.

Required:

  • app handles first load with no controller;
  • controllerchange handled;
  • update flow has safe point;
  • skipWaiting/clients.claim policy is deliberate;
  • cache names are versioned;
  • cache cleanup avoids deleting assets needed by old clients;
  • SW messages are schema-validated;
  • clients.matchAll() broadcast is filtered/scoped;
  • network strategy is per request class;
  • auth-sensitive response cache policy is strict;
  • offline fallback is intentional;
  • Background Sync has fallback;
  • SW lifecycle is tested in real browser;
  • DevTools/Application panel debugging runbook exists.

Do not use Service Worker as:

  • permanent background thread;
  • hidden global session brain without lifecycle recovery;
  • arbitrary compute worker;
  • blind cache-everything proxy;
  • secret store.

14. Security Checklist

Threat model must include XSS and compromised dependencies. Browser-local orchestration cannot fully protect against same-origin arbitrary script execution.

Required:

  • CSP with appropriate script-src, worker-src, connect-src;
  • no sensitive token in BroadcastChannel/storage event;
  • message schema validation at every boundary;
  • sender metadata treated as claim, not trusted identity;
  • MessagePort treated as capability;
  • worker scripts pinned to trusted origin/build path;
  • Service Worker registration scope reviewed;
  • Cache API does not store private responses accidentally;
  • IndexedDB/OPFS retention policy documented;
  • logout clears sensitive local state;
  • Clear-Site-Data use evaluated for emergency cleanup;
  • cross-origin isolation headers tested if using SharedArrayBuffer;
  • COOP/COEP impact on popups/OAuth/third-party embeds tested;
  • debug snapshot redacts payload/secrets;
  • telemetry redacts user data and tokens.

Risk framing:

ThreatMitigation
XSS reads same-origin storageminimize secret storage, CSP, Trusted Types, server-side session strategy
Message spoofingschema validation, generation, authorization check at receiver
Token broadcast leaknever broadcast token
Stale worker effectgeneration/fencing token
Service Worker cache poisoningintegrity/versioned manifest, trusted source, cache validation
Cross-tab logout misseddurable revocation marker + startup/visible reconciliation
Over-broad SW scopenarrow registration scope
Debug data leakredaction + gated debug mode

15. Performance Checklist

Budgets should be explicit.

BudgetExample threshold
Main-thread taskavoid 50ms+ long tasks
Broadcast payloadkeep small; send references for large data
Worker queue depthbounded per feature
Worker task timeoutper task class
Structured clone payloadmeasure before scaling
IndexedDB transaction durationshort, scoped
Cache promotionstaged, lock-protected
OPFS writechunked/staged
Session refreshsingle-flight and low retry
Outbox replaysmall batches
Telemetrysampled and redacted

Performance smell list:

  • JSON stringify/parse large payload repeatedly;
  • broadcasting full state snapshot on every change;
  • cloning huge object graph into worker;
  • too many workers on low-core device;
  • IndexedDB transaction open while waiting network;
  • Service Worker caching private API responses without policy;
  • worker progress events flooding main thread;
  • message protocol without payload size metrics;
  • retry storms after network recovery;
  • cache cleanup during active usage.

16. Observability Checklist

Minimum metrics:

MetricWhy
runtime starts/stopslifecycle visibility
tab count/presencemulti-tab context
message count by kindprotocol pressure
message validation failurescompatibility/security
messageerror countclone/deserialization issues
lock wait timecontention
lock hold timelong owner bug
worker queue depthoverload
worker task latency/failurecompute health
session refresh attemptsauth storm detection
logout propagation latencysecurity cleanup
outbox pending agesync health
cache version active/stagedupdate health
IDB blocked/versionchangemigration issue
Service Worker controllerchangeupdate lifecycle

Debug snapshot must include:

  • tab/runtime identity;
  • app/protocol version;
  • visibility/focus;
  • session state redacted;
  • worker queue status;
  • lock status if queryable;
  • outbox summary;
  • cache version summary;
  • last critical errors.

17. Testing Checklist

Test categories:

CategoryExample
Unitreducer ignores stale generation
Contractinvalid message rejected
Transport fakeduplicate/lost/reordered message
Workertimeout rejects pending task
Multi-page5 tabs trigger one refresh
Service Workerupdate available message reaches clients
IndexedDBmigration blocked by old connection
Offlinereplay recovers after owner crash
Securitytoken not present in broadcast/debug logs
Performanceno long task during import flow
Chaosleader dies mid-lock / replay resumes

Essential multi-tab tests:

  1. Open three tabs, all boot same user, presence converges.
  2. All tabs request token refresh, only one backend refresh occurs.
  3. Logout in one tab, all tabs abort protected request and transition to anonymous/revoked.
  4. Worker task result arrives after logout, result is ignored.
  5. Offline command enqueued in two tabs with same idempotency key, only one effective command is sent.
  6. Cache update arrives while old tab is active, app prompts safe reload instead of deleting active asset.
  7. IndexedDB upgrade blocked by old tab, old tab receives versionchange/prompt.
  8. BroadcastChannel message duplicated, reducer remains idempotent.
  9. Tab owner crashes during outbox replay, another owner resumes after lease expiry.
  10. bfcache restore revalidates session/cache state.

18. Deployment Checklist

Build/deploy pitfalls are real.

Required:

  • Worker script path works under production base URL;
  • module worker uses correct type: "module" where needed;
  • worker script served with correct MIME;
  • CSP worker-src allows worker origin;
  • source maps available to debugging policy;
  • Service Worker file is not incorrectly cached by CDN;
  • Service Worker scope is correct;
  • cache version includes build hash;
  • rollback plan handles old cache/SW state;
  • IndexedDB schema version compatible with rolling deploy;
  • app version included in messages;
  • old and new tabs compatibility window defined;
  • cross-origin isolation headers tested if needed;
  • OAuth/popup/third-party embeds tested if COOP/COEP enabled;
  • mobile/WebView compatibility tested if supported;
  • private/incognito behavior tested;
  • storage quota failure tested.

Smoke tests after deploy:

1. Load app fresh.
2. Open second tab.
3. Confirm BroadcastChannel communication.
4. Run worker task.
5. Run protected fetch.
6. Trigger token refresh simulation.
7. Trigger logout in one tab.
8. Verify all tabs clean session.
9. Confirm Service Worker controller/version.
10. Confirm cache manifest version.
11. Confirm IndexedDB version.
12. Confirm no CSP violation.

19. Incident Runbooks

19.1 Refresh Storm

Symptoms:

  • many /refresh calls per user;
  • token rotation failures;
  • sudden logout across tabs;
  • 401 retry spike.

Check:

  • Web Locks availability;
  • lock name mismatch across app versions;
  • refresh freshness re-check inside lock;
  • stale generation handling;
  • BroadcastChannel message validation failure;
  • old bundle compatibility.

Immediate mitigation:

  • increase refresh skew jitter;
  • disable automatic 401 retry loop;
  • force reload old tabs if needed;
  • server-side dedupe refresh if possible.

19.2 Worker Memory Explosion

Symptoms:

  • tab killed/discarded;
  • import/search freezes;
  • OOM on low-memory devices.

Check:

  • structured clone payload size;
  • object graph shape;
  • transferables used correctly;
  • queue depth;
  • worker count;
  • result size;
  • progress event frequency.

Immediate mitigation:

  • lower max worker count;
  • lower queue size;
  • chunk payload;
  • switch to transfer/reference;
  • disable feature for low-memory devices.

19.3 Cache Update Breaks App

Symptoms:

  • old HTML loads new JS or reverse;
  • chunk 404;
  • repeated reload prompt;
  • Service Worker stuck waiting.

Check:

  • CDN cache headers for SW file;
  • cache manifest active/staged;
  • old clients count;
  • skipWaiting policy;
  • cleanup deleting old chunks;
  • build hash mismatch.

Immediate mitigation:

  • stop aggressive cleanup;
  • serve previous assets longer;
  • prompt safe reload;
  • unregister/reset SW only as last resort.

19.4 IDB Migration Blocked

Symptoms:

  • app stuck loading;
  • blocked event;
  • some old tabs open;
  • new version cannot start.

Check:

  • old DB connections not closing on versionchange;
  • long-running transactions;
  • app version compatibility;
  • migration running too early.

Immediate mitigation:

  • show reload-all-tabs prompt;
  • close DB on versionchange;
  • lazy migrate record-level data;
  • delay destructive migration.

19.5 Logout Not Propagating

Symptoms:

  • one tab logged out, another still authenticated;
  • protected request after logout;
  • stale worker result updates UI.

Check:

  • durable revocation marker;
  • BroadcastChannel health;
  • session generation comparison;
  • bfcache restore reconciliation;
  • protected fetch abort registry;
  • worker generation guard.

Immediate mitigation:

  • force session revalidate on visible/focus;
  • server reject stale session generation;
  • clear local state on next startup;
  • add temporary polling of revocation marker if channel unreliable.

20. Maturity Model

LevelCapability
0Single-tab happy path, no worker, no cross-tab awareness
1Basic worker usage for heavy task
2BroadcastChannel logout/cache invalidation signal
3Typed message envelope and schema validation
4Presence + heartbeat + lifecycle reconciliation
5Web Locks for refresh/replay/cache/migration ownership
6Durable IndexedDB control plane + idempotent outbox
7Worker pool with bounded queue/cancellation/observability
8Service Worker cache/update orchestration with safe point
9Chaos-tested multi-tab runtime with security threat model
10Internal platform-grade orchestration runtime with SLO/runbook

A top-tier implementation is not “uses every API”. A top-tier implementation uses fewer primitives, but with clear invariants and failure recovery.


21. Skill Map


22. What You Should Be Able to Design Now

After this series, you should be able to design:

  1. Multi-tab auth refresh without refresh storm.
  2. Multi-tab logout/revocation propagation.
  3. Browser-side worker pool with bounded execution.
  4. Large file import pipeline using worker + transferables/OPFS.
  5. Offline outbox with idempotent replay.
  6. Cache update flow with Service Worker and safe reload.
  7. SharedWorker hub for live coordination.
  8. Browser-local event sourcing/projection model.
  9. IndexedDB migration strategy across open tabs.
  10. Cross-tab notification suppression.
  11. Service Worker client broadcast protocol.
  12. Web Locks leader election with fencing.
  13. SharedArrayBuffer ring buffer for low-latency worker pipeline.
  14. Debug/observability system for multi-context frontend.
  15. Chaos test suite for browser orchestration.

23. Interview-Level Questions You Can Now Answer

Use these as self-check.

Architecture

  1. Why is a browser app with multiple tabs similar to a distributed system?
  2. Why is BroadcastChannel not enough for leader election?
  3. Why does Web Locks still need fencing tokens for some workflows?
  4. When would you use SharedWorker over BroadcastChannel?
  5. When would you avoid Service Worker?

Reliability

  1. What happens if a leader tab dies mid-task?
  2. How do you prevent stale worker results from updating UI?
  3. How do you design token refresh with refresh token rotation?
  4. Why is exactly-once delivery unrealistic from browser alone?
  5. How do you recover outbox replay after crash?

Performance

  1. How do you decide clone vs transfer vs shared memory?
  2. Why can worker pool make performance worse?
  3. What metrics would you collect for worker task health?
  4. How do you avoid long tasks during large import?
  5. How does BroadcastChannel fanout affect performance?

Security

  1. Why should tokens not be broadcast?
  2. How does XSS affect browser-local orchestration security?
  3. What does CSP worker-src protect?
  4. What breaks when enabling COOP/COEP?
  5. How do you design logout cleanup defensibly?

Operations

  1. How do you debug Service Worker update stuck in waiting?
  2. How do you detect IDB migration blocked by old tab?
  3. How do you test multi-tab refresh single-flight?
  4. How do you reproduce a race condition deterministically?
  5. What does a useful debug snapshot include?

24. Final Exercises

These are intentionally implementation-heavy.

Exercise 1 — Token Refresh Coordinator

Build:

  • BroadcastChannel session bus;
  • Web Locks refresh lock;
  • session reducer with generation;
  • fake auth API with refresh token rotation;
  • Playwright test opening 5 tabs.

Invariant:

For one expiry window, backend refresh endpoint is called at most once per session generation.

Exercise 2 — Offline Outbox

Build:

  • IndexedDB outbox;
  • idempotency key generator;
  • replay lock;
  • retry/backoff;
  • fake network unknown outcome;
  • conflict state.

Invariant:

Every acknowledged command is marked acked exactly once locally, but network attempts may be more than once.

Exercise 3 — Worker Import Pipeline

Build:

  • CSV parser worker;
  • transferable ArrayBuffer path;
  • bounded queue;
  • progress throttling;
  • cancellation;
  • stale generation guard.

Invariant:

Canceling import prevents stale result from mutating current UI state.

Exercise 4 — Cache Update Safe Point

Build:

  • versioned cache manifest;
  • Service Worker update notification;
  • tab safe reload prompt;
  • old cache cleanup only after safe point.

Invariant:

No active tab references a deleted asset version.

Exercise 5 — Chaos Harness

Inject:

  • duplicate messages;
  • delayed messages;
  • owner tab crash;
  • worker crash;
  • IDB blocked migration;
  • Service Worker controllerchange;
  • network timeout.

Invariant:

System eventually reconciles without accepting stale session/cache/outbox effects.

25. Final Design Heuristics

Use these in real architecture reviews.

  1. Prefer explicit ownership over hope.
  2. Prefer durable markers over cleanup assumptions.
  3. Prefer small signals over large broadcasts.
  4. Prefer idempotent receiver over perfect sender.
  5. Prefer generation/fencing over timestamp guessing.
  6. Prefer bounded queues over unbounded responsiveness debt.
  7. Prefer versioned artifacts over mutable caches.
  8. Prefer schema validation over trusting same-origin scripts.
  9. Prefer safe reload over invisible dangerous update.
  10. Prefer measurable budgets over “it feels fast”.
  11. Prefer chaos tests over anecdotal confidence.
  12. Prefer server-side correctness for business-critical effects.

26. Common Wrong Conclusions

“Same-origin means safe.”

Wrong. Same-origin means browser allows access. It does not mean every same-origin script is trustworthy or every message is legitimate.

“BroadcastChannel solves multi-tab state.”

Wrong. It solves volatile signaling. State consistency still needs reducer, storage, idempotency, generation, and reconciliation.

“Web Locks gives me distributed consensus.”

Wrong. It gives same-origin local mutual exclusion. It does not coordinate across devices, browsers, users, or backend systems.

“Service Worker is a background daemon.”

Wrong. It is event-driven and lifecycle-managed by the browser. Design for wake/sleep/restart.

“Worker means faster.”

Wrong. Worker means off-main-thread execution. Data movement, memory, scheduling, and queue policy decide whether it is faster.

“Exactly once is required.”

Usually wrong framing. What you need is idempotency, dedupe, reconciliation, and clear unknown-outcome handling.


27. How to Explain This to a Team

When introducing this architecture internally, do not start with APIs. Start with failure modes.

A good pitch:

Our frontend is not a single runtime anymore. Users open multiple tabs. Workers run in separate contexts. Service Worker can update independently. Storage is shared and versioned. Network can fail after side effects. Therefore we need a small orchestration layer with message protocol, ownership, durable markers, generation guards, and observability.

Then show three concrete incidents the runtime prevents:

  1. Refresh token rotation storm.
  2. Duplicate offline replay.
  3. Stale logout/session state across tabs.

Then show the minimal architecture:

  • BroadcastChannel for signal;
  • Web Locks for local ownership;
  • IndexedDB for durable metadata;
  • Dedicated Worker for compute;
  • Service Worker for cache/network/update;
  • trace envelope for observability.

That is enough to get buy-in.


28. Final Production Readiness Gate

Before shipping a serious multi-tab/worker system, require this gate.

Architecture Gate

  • Runtime boundaries documented.
  • Ownership model documented.
  • State machine documented.
  • Failure model documented.
  • Compatibility matrix documented.

Security Gate

  • Threat model reviewed.
  • Token/storage policy reviewed.
  • CSP/worker-src reviewed.
  • Debug/telemetry redaction reviewed.
  • Logout cleanup reviewed.

Reliability Gate

  • Idempotency keys for side-effecting commands.
  • Generation/fencing for stale effects.
  • Lock/lease around global jobs.
  • Recovery path for tab/worker/SW crash.
  • IDB migration blocked handling.

Performance Gate

  • Worker queue bounded.
  • Payload movement budget measured.
  • Long task budget tested.
  • Cache/OPFS/IDB operations measured.
  • Multi-tab resource usage tested.

Observability Gate

  • Trace ID propagation.
  • Message metrics.
  • Lock metrics.
  • Worker metrics.
  • Session/outbox/cache metrics.
  • Debug snapshot.

Testing Gate

  • Unit tests.
  • Protocol contract tests.
  • Multi-tab browser tests.
  • Service Worker tests.
  • Chaos tests.
  • Deployment smoke tests.

29. Closing Synthesis

The browser has become a serious application runtime. But it is not a server process. It is not stable, not single-threaded in the way people casually assume, and not globally coordinated by default.

A top-level mental model:

Browser App = local cluster of unreliable actors
              + shared origin storage
              + volatile message channels
              + browser-managed lifecycle
              + network/server authority
              + user-driven navigation/visibility

From that model, the design follows naturally:

  • use workers for bounded execution;
  • use BroadcastChannel for volatile notification;
  • use MessagePort for explicit capability channels;
  • use Web Locks for local ownership;
  • use IndexedDB for durable control state;
  • use Cache API/OPFS for data-plane artifacts;
  • use Service Worker for network/cache/update events;
  • use generation/idempotency/fencing for correctness;
  • use observability and chaos tests to prove behavior.

This is the difference between demo-level frontend and production-grade browser systems engineering.


30. Series Completion

Series ini selesai di sini.

Total:

Part 001 sampai Part 072

Final coverage:

  • browser as distributed runtime;
  • execution context map;
  • main thread vs worker;
  • event loop and agent clusters;
  • origin/security model;
  • page lifecycle;
  • failure model;
  • message protocols;
  • Dedicated Worker;
  • SharedWorker;
  • Service Worker;
  • BroadcastChannel;
  • MessageChannel;
  • Web Locks;
  • leader election;
  • fencing token;
  • single-flight requests;
  • token refresh orchestration;
  • logout/revocation;
  • IndexedDB;
  • OPFS;
  • Cache API;
  • event sourcing;
  • WAL;
  • offline queue;
  • conflict resolution;
  • delivery semantics;
  • schema migration;
  • SharedArrayBuffer;
  • Atomics;
  • OffscreenCanvas;
  • WebAssembly;
  • scheduling;
  • performance budgeting;
  • observability;
  • debugging;
  • testing;
  • chaos engineering;
  • security threat model;
  • reference architecture;
  • build-from-scratch runtime;
  • final production checklist.

You now have the map, the primitives, the failure model, and the implementation direction.

The next leap is not reading more APIs. The next leap is building a small runtime, breaking it deliberately, measuring it, and tightening the invariants until it behaves under ugly real browser conditions.


References

Lesson Recap

You just completed lesson 72 in final stretch. Use the series map if you want to review the broader track, or continue directly into the next lesson while the context is still warm.

Continue The Track

Keep the momentum while the lesson is still fresh. Move backward for review or continue forward into the next concept.