Skip to content

    Frontend System Design

    Front-End Case Study: Multi-Tenant Application

    Design a multi-tenant B2B front end end to end: strict tenant resolution, scoped keys, layered config, a safe workspace switch, and a lab with tests.

    By Published 22 min read

    • frontend-system-design
    • case-study
    • multi-tenancy
    • enterprise
    • state-management
    Share

    Case studyadvancedReact labFrontend System Design

    Before this: How to Read and Reproduce a Front-End Case Study, Multi-Tenant UI Architecture

    What you'll learn: By the end of this case you will be able to design the front end of one application that serves many customer companies: how it finds the tenant and what it does when it cannot, how every cache and storage key names its tenant and user, how per-tenant configuration is layered and validated, what happens in the client when a person who belongs to several tenants switches between them, and how to test for leaks with two tenants. You will also run the design as a pure TypeScript core with a thin React shell, against a fake server that decides membership.

    A hotel with one front desk and many floors works only if the desk always knows which floor it is serving. The risky moment is not the check-in. It is the guest who asks to move to another floor while the porter is still carrying the first floor's luggage down the corridor. A multi-tenant front end has the same desk, the same corridor and the same porter. Most of this case is about that moment: the switch, and the late arrivals that belong to the floor you just left.

    Frame. This is an educational reference design, not the verified internal architecture of any company. The running product is an invented help-desk application used by several customer companies ("tenants"): each has its own name, brand colour, plan and tickets, and some people (consultants, agency staff) work for more than one tenant. No company is named. Every name, colour, plan and latency is illustrative, unless a source is linked. The concepts (resolving a tenant, scoping caches, layered configuration) are taught in Multi-Tenant UI Architecture, which has no lab of its own; this case applies them to one product and runs them in a lab.

    The core idea

    Three statements carry the design.

    1. The tenant is part of the identity of every piece of client state. Not only the request: the cache entry, the storage key, the configuration and the screen. A value that does not say whose it is can end up in front of the wrong person.
    2. The tenant in the browser is a selector, never proof. The page can say which tenant it wants. The server decides, from its own records, whether this person belongs to it. OWASP's Multi-Tenant Security Cheat Sheet says to treat client-supplied tenant identifiers as selectors only, and to bind tenant context to a server-verified identity and current membership.
    3. A switch is a boundary, and boundaries need a version number. Everything started before the switch belongs to the old tenant. The client gives each tenant session an epoch and refuses any answer from an earlier one.

    Requirements and targets

    Requirements. A person opens the app on their tenant's address, sees that tenant's branded workspace and tickets, and can switch to another tenant they belong to. A person who is not a member of a tenant sees nothing of it. Plan features appear only where the plan has them. The colours a customer chooses must stay readable. Preferences (such as density) are remembered per tenant. Signing out leaves nothing of any tenant in memory. Out of scope: single sign-on per tenant (see Enterprise SSO, Audit and Compliance in the UI), tenant onboarding and billing, support impersonation, and the server's data isolation, which is the back end's job and is covered in Multi-Tenancy: Tenant Data and Isolation.

    Targets (all illustrative):

    Target Value Why it is a target
    Data of tenant A visible under tenant B never, not even briefly The defining rule of the product
    A host that is not a known tenant refused, no default tenant A default tenant is a leak waiting for a typo
    "Not yours" versus "does not exist" indistinguishable on screen Do not confirm that a tenant exists
    Brand text contrast at least 4.5:1 WCAG 1.4.3 for normal text
    Brand colour against the page at least 3:1 WCAG 1.4.11 for interface components
    Tenants per build many, one build Variation is configuration, not a fork

    Architecture

    Figure 1. The browser side of the tenant application

    The browser resolves the tenant, the shell store loads configuration and data from an API that verifies membership, and every key it keeps names the tenantAddress to Tenant resolver (Host header); Tenant resolver to Shell store (tenant id); Shell store to Thin view (state); Shell store to Scoped keys (cache, storage); Shell store to API (tenant id as selector)ONE BUILD, MANY TENANTSAddress: host and pathAddresshost and pathTenant resolver: once, strictlyTenantresolveronce, strictlyShell store: epoch, config, ticketsShell storeepoch, config,ticketsScoped keys: tenant, user, nameScoped keystenant, user,nameThin view: switcher, brand tokensThin viewswitcher, brandtokensAPI: verifies membershipAPIverifiesmembershipHost headertenant idstatecache, storagetenant id as selector

    How to read this: the resolver turns the address into a tenant id once, and hands it to the store. The store keeps every cache and storage entry under a key that names the tenant and the user. The API, drawn with a warning tone, is where membership is decided: it receives the tenant id as a selector and checks it against its own records.

    The store is plain TypeScript with no DOM. The view is a few dozen lines of React that read it with useSyncExternalStore; React's documentation says repeated calls to getSnapshot must return the same value while the store has not changed, so the store replaces its state object only when something changes.

    Data and state

    Data Owner Keyed by Lives in
    Which tenant the address names The resolver The request Computed once per navigation
    Tenant record (name, plan, brand, switched-off features) The server Tenant id Fetched on entry, merged into config
    Merged configuration (features, theme tokens, copy, density) The shell store Tenant id The store, never persisted as a whole
    Tickets The server Tenant id and user The store and a client cache
    User preferences (density) The person Tenant, user, name Web storage, through scoped keys
    Epoch The shell store None A counter in memory
    Tenants the person may switch between The server User A session response

    The store has a status: idle (no tenant yet), loading, ready, not found, or error.

    Figure 2. States of the tenant session

    stateDiagram-v2 accTitle: States of the tenant session in the shell accDescr: The session starts idle. Switching to a tenant moves to loading and starts a new epoch. Loading ends in ready, not found or error. From any of those a new switch returns to loading, discarding everything of the previous tenant. Signing out returns to idle from any state. [*] --> idle idle --> loading: switch to a tenant loading --> ready: answers for this tenant and epoch loading --> not_found: server answers 404 loading --> error: failure or answer about another tenant ready --> loading: switch (new epoch) not_found --> loading: switch (new epoch) error --> loading: switch (new epoch) ready --> idle: sign out not_found --> idle: sign out error --> idle: sign out loading --> idle: sign out

    How to read this: every arrow into loading starts a new epoch and clears the old tenant's data first, so no state shows one tenant's content under another's header. "Not found" is a final state for that tenant, not a retry loop.

    Resolve the tenant once, and strictly

    There are three common shapes, and the browser treats them differently. MDN says two URLs have the same origin only if protocol, port and host match, and that web storage and IndexedDB are separated by origin: script in one origin cannot read or write the storage of another. So a subdomain per tenant (acme.desk.example) and a custom domain give each tenant its own storage; a path per tenant on one host (app.desk.example/t/acme) shares one origin, and your own code must keep tenants apart. MDN describes cookies differently: a cookie with a Domain attribute is available to that domain and all its subdomains, while one without it is host-only. The concept lesson works through this in detail; here the question is what the resolver must refuse.

    Illustration 1, the minimal example: a global "current tenant"

    The shortest design keeps the tenant in a module variable and reads it everywhere:

    let currentTenant = "t_acme";
    export const ticketsUrl = () => `/api/tenants/${currentTenant}/tickets`;
    export async function loadTickets(): Promise<Ticket[]> {
      const response = await fetch(ticketsUrl());
      return response.json();
    }
    export function switchTenant(id: string) { currentTenant = id; }

    It looks harmless and has three problems. The variable changes under a request already in flight, so the answer to a request started for Acme is shown after the switch to Bravo, because nothing ties the answer to the tenant it was for. Any cache keyed by the path or the call name shares one entry across tenants. And no code anywhere says what happens to values the old tenant left behind. The rest of this case replaces the variable with a resolver that returns a result, a store that owns an epoch, and keys that carry the tenant.

    What the resolver refuses

    The lab's resolveTenant(directory, { host, pathname }) normalises the host (case, port, trailing dot), checks custom domains by exact match, then the path form on the app host only, then the subdomain form. A miss is a refusal with a reason, never a default tenant. It also refuses reserved labels such as www, nested labels and look-alike hosts that merely contain the product's domain.

    Expected output, captured from a real run (the host and path in, the result out):

    acme.desk.example/tickets                tenant t_acme via subdomain
    BRAVO.desk.example:8443/tickets          tenant t_bravo via subdomain
    help.acme-grocers.example/tickets        tenant t_acme via custom-domain
    app.desk.example/t/bravo/tickets         tenant t_bravo via path
    app.desk.example/t/ghost/tickets         refused: unknown tenant
    app.desk.example/tickets                 refused: no tenant in the path
    ghost.desk.example/                      refused: unknown tenant
    www.desk.example/                        refused: reserved label
    a.b.desk.example/                        refused: nested label
    desk.example.evil.test/                  refused: not a tenant host
    acme.desk.example./                      tenant t_acme via subdomain

    The last line shows a trailing dot resolving like the plain host; desk.example.evil.test is refused because the check is on the suffix, not on "contains". The tenant slug in the path is honoured only on the app host, so acme.desk.example/t/bravo/x resolves to Acme, not Bravo. This resolver is a teaching model, not a router.

    Keys that name their tenant and user

    Anything the browser keeps for a tenant goes through one function, scopeKey({ tenantId, userId }, name), which returns tenant:user:name. Both ids are validated against a short alphabet, because an id that contained the separator could forge another scope's prefix (a tenant named t_acme:ava would collide with a user's keys). The user is in the key because a shared computer can hold two people's data for the same tenant. scopedStorage wraps a storage object so a scope can read, write, remove and clear only its own keys, and purgeOtherTenants removes every tenant's keys except one, for use on a shared origin. OWASP's cheat sheet says to include the tenant identifier in every cache key whose value or authorization varies by tenant, and MDN says each origin has its own localStorage area, so the discipline matters most in the path-per-tenant shape.

    Expected output, captured from a real run (two tenants on one shared storage):

    == keys that name their tenant, on one shared origin ==
    stored keys: t_acme:ava:density, t_bravo:ava:draft
    acme sees density=compact draft=null; bravo sees density=null draft=Re: wrong item
    forged scope refused: invalid scope id
    after acme.clear(): t_bravo:ava:draft
    purgeOtherTenants(keep t_acme) removed 1 key, left: []

    A test covers a subtler case: clearing user ava's keys must not touch user avalon's, because a prefix check without the final separator would match both. The same function names service-worker caches and the in-memory client cache; MDN says CacheStorage maps string names to Cache objects reachable from a service worker or from the page, so on a shared origin the tenant belongs in the cache name too (see Service Worker Caching Strategies).

    Illustration 2, the realistic example: configuration in layers

    Product defaults come first, then what the plan grants, then the tenant's own settings, then the person's preferences. Three rules are worth stating, because each prevents a real mistake.

    • A tenant can switch features off but never add one. Features are the plan's list minus the tenant's switched-off entries. An unknown plan fails closed to the smallest set, and the merge records a warning.
    • Tenant settings are input. A customer typed the colours. They are validated when saved and validated again when read, because stored data can be old, edited or wrong. The check is that each value is a hex colour, that text on the brand colour reaches 4.5:1, and that the brand colour against the white page reaches 3:1. WCAG 1.4.3 (level AA) requires at least 4.5:1 for normal text and 3:1 for large text; WCAG 1.4.11 (level AA) requires at least 3:1 for interface components and graphical objects against adjacent colours. A brand that fails falls back to the product colours and is reported, instead of shipping unreadable buttons.
    • The result is data on the root element. MDN says custom properties are scoped to the element they are declared on and are used with var(), so the shell sets --brand and --on-brand on its root and every component that reads them follows. The Design Tokens and Theming lesson covers token design; this lab reuses its contrast code by import.

    Expected output, captured from a real run (three tenants; the compact density is one person's preference, applied to Acme):

    == layered configuration ==
    t_acme: features=[tickets,reports,sla-timers] brand=#0b5cad on=#ffffff density=compact
    t_bravo: features=[tickets] brand=#8a3b00 on=#ffffff density=comfortable
    t_candy: features=[tickets,reports] brand=#1f3a5f on=#ffffff density=comfortable
      warning: brand rejected: text on the brand colour is 1.42:1, needs 4.5:1; brand colour on the page is 1.42:1, needs 3:1

    Acme's business plan gives three features and a compact density from the person's preference. Bravo's starter plan gives one. The third tenant picked a yellow with white text: 1.42:1, far below 4.5:1, so it receives the product's own colours and a warning; the tenant also switched off sla-timers and the output shows it gone. The ratios are computed by the contrast formula of WCAG 2.2, not typed in.

    The switch is a boundary

    When the person picks another workspace, the shell store does five things in order: it bumps the epoch; it aborts anything in flight; it deletes the old tenant's cache entries; it publishes a state with no configuration, no tickets and no reports, so nothing of the old tenant stays on screen even for a moment; and it asks the server for the new tenant's configuration and tickets. Every answer is checked against the epoch it started in.

    The abort is a courtesy: MDN says AbortController.abort() aborts an asynchronous operation before it completes, but a proxy or a fake can ignore it and an answer can already be on its way. The epoch check is what keeps the screen correct. A third check sits behind it: a 200 answer must be about the tenant that was asked for, and an answer about another tenant is discarded. That last check is a design choice (defence in depth against a bad cache key at an edge or a routing fault), not something a source requires.

    Figure 3. A switch while the first tenant's answer is still on its way

    sequenceDiagram accTitle: Switching tenant while an answer is still in flight accDescr: The person is in Acme and picks Bravo before Acme's answer has arrived. The shell increments the epoch, aborts the Acme requests, clears the Acme cache entries and the screen, and asks for Bravo. If the server ignored the abort, the Acme answer arrives later and is dropped because it belongs to an earlier epoch. The Bravo answer is shown. participant P as Person participant S as Shell store participant A as API P->>S: open Acme (epoch 1) S->>A: config and tickets for Acme P->>S: pick Bravo before Acme answers S->>S: epoch 2, abort, purge Acme entries, clear screen S->>A: config and tickets for Bravo A-->>S: Bravo answers (shown) A-->>S: Acme answers (only if the abort was ignored) Note over S: epoch 1 is not the current epoch, so the Acme answers are dropped

    How to read this: the clear-screen step happens before the new request, not after the new answer. The late Acme answer is judged by its epoch, not by when it arrived.

    Illustration 3, the failure case: the porter arrives late

    The lab's server ignores the abort on purpose, as a proxy that does not cancel would. The consultant opens Acme, whose answers take 300 ms (illustrative), and after 100 ms picks Bravo, whose answers take 50 ms.

    Expected output, captured from a real run (the endpoint ignores the abort):

    == switching workspace while an answer is still on its way ==
    t=   0  switch   t_acme   first tenant
    t=   0  request  t_acme   config
    t=   0  request  t_acme   tickets
    -- ava picks Bravo Mart before Acme has answered
    t= 100  switch   t_bravo  from t_acme
    t= 100  request  t_bravo  config
    t= 100  request  t_bravo  tickets
    t= 150  response t_bravo  config 200
    t= 150  response t_bravo  tickets 200
    t= 300  drop     t_acme   config answer for an earlier tenant
    t= 300  drop     t_acme   tickets answer for an earlier tenant
    tenant=t_bravo status=ready brand=#8a3b00 tickets=[B-201,B-202] message="2 tickets"
    cache keys: [t_bravo:ava:tickets]
    server calls: 4

    The Bravo answers arrive at t=150 and are shown. The Acme answers arrive at t=300 and are dropped, one drop line each. The final line of the screen summary shows Bravo's tickets only, and the client cache holds one entry, t_bravo:ava:tickets: the Acme entry was purged at the switch and the late answer never wrote a new one. The server handled four requests, which is the price of an ignored abort; the screen is correct regardless.

    Figure 4. What a response may do to the screen

    flowchart TD accTitle: Deciding what a response may do to the screen accDescr: A response is first compared with the current epoch; an old epoch is dropped. A 404 shows workspace not found. Another failure status shows an error. A 200 that names a different tenant than the one asked for is discarded as an error. Only a 200 for the asked tenant and the current epoch is merged and shown. A["Response arrives"] --> B{"Same epoch as now?"} B -- "no" --> D1["Drop it"] B -- "yes" --> C{"Status?"} C -- "404" --> N["Show workspace not found"] C -- "other failure" --> E["Show an error, keep nothing"] C -- "200" --> F{"About the tenant we asked for?"} F -- "no" --> E F -- "yes" --> G["Merge config, cache tickets, show"]

    How to read this: only one path reaches the screen with data. Each of the others ends in a state that shows nothing of any tenant.

    Not yours, or not there: one answer

    When the server answers 404 for a tenant the person does not belong to, and also for a tenant that does not exist, the screen must not tell the two apart. OWASP's cheat sheet makes the same point for objects: it recommends returning 404 rather than 403 so the response does not reveal that the object exists in another tenant. In the lab, the server fake takes membership from its own table, and the shell shows the same text for both.

    Expected output, captured from a real run (the person is a member of Acme only):

    == a workspace that is not yours looks like one that does not exist ==
    -- ben asks for t_bravo
    t=   0  switch   t_bravo  first tenant
    t=   0  request  t_bravo  config
    t=   0  request  t_bravo  tickets
    t= 100  response t_bravo  config 404
    t= 100  response t_bravo  tickets 404
    tenant=t_bravo status=not-found brand=- tickets=[-] message="Workspace not found"
    -- ben asks for t_nowhere
    t=   0  switch   t_nowhere first tenant
    t=   0  request  t_nowhere config
    t=   0  request  t_nowhere tickets
    t= 100  response t_nowhere config 404
    t= 100  response t_nowhere tickets 404
    tenant=t_nowhere status=not-found brand=- tickets=[-] message="Workspace not found"

    The two summaries are identical apart from the tenant id the person typed. The test compares the status, the message, the configuration and the tickets of both runs and requires them to be equal. The other half of the rule: a 200 answer about a different tenant than the one asked for is an error, not data.

    Expected output, captured from a real run (a faulty edge answers with Bravo's data for an Acme request):

    == an answer about the wrong tenant is discarded ==
    t=   0  switch   t_acme   first tenant
    t=   0  request  t_acme   config
    t=   0  request  t_acme   tickets
    t= 100  response t_acme   config 200
    t= 100  response t_acme   tickets 200
    t= 100  mismatch t_acme   answer was about t_bravo
    tenant=t_acme status=error brand=- tickets=[-] message="Could not load this workspace"

    The mismatch is logged, the screen shows an error, and nothing of Bravo is cached or displayed. This is the check that turns a silent leak into a loud failure.

    Features: hidden on the screen, refused by the server

    A feature flag from a plan is a courtesy in the interface. The shell shows the Reports button only when the merged configuration has that feature, and the server refuses the request anyway. That matters because the screen's copy of the configuration can be wrong, old or edited in developer tools. RBAC and ABAC on the UI covers the model.

    Expected output, captured from a real run (a starter plan, then a business plan):

    == a feature the plan does not include: the screen hides it, the server refuses it ==
    t=   0  switch   t_bravo  first tenant
    t=   0  request  t_bravo  config
    t=   0  request  t_bravo  tickets
    t= 100  response t_bravo  config 200
    t= 100  response t_bravo  tickets 200
    reports button offered on starter plan: false
    t=1000  request  t_bravo  reports
    t=1100  response t_bravo  reports 403
    server answered reports with 1 call; screen state: unavailable
    t=2000  purge    t_bravo  1 cache entry
    t=2000  switch   t_acme   from t_bravo
    t=2000  request  t_acme   config
    t=2000  request  t_acme   tickets
    t=2100  response t_acme   config 200
    t=2100  response t_acme   tickets 200
    t=3000  request  t_acme   reports
    t=3100  response t_acme   reports 200
    business plan: reports ready, summary="3 tickets"

    Look at three details. The button is not offered on the starter plan, yet a hand-made call reaches the server and gets a 403; the screen then says reports are not available, in the same words it would use for a missing feature. On the switch to Acme, the old tenant's cache entry is purged and the reports state starts over, so a "not available" from Bravo does not follow the person into Acme. And on the business plan the same call returns a summary.

    Sign out

    Signing out is the largest boundary. The store bumps the epoch, aborts, purges the active tenant's cache entries, clears the whole cache, forgets the tenant list and returns to idle. A late answer after sign-out changes nothing.

    Expected output, captured from a real run:

    == sign out ==
    t=   0  switch   t_acme   first tenant
    t=   0  request  t_acme   config
    t=   0  request  t_acme   tickets
    t= 100  response t_acme   config 200
    t= 100  response t_acme   tickets 200
    before: cache keys [t_acme:ava:tickets]
    t=1000  purge    t_acme   1 cache entry
    after:  cache keys [] tenant=- status=idle brand=- tickets=[-] message=""

    Preferences saved through scopedStorage stay in web storage under their scoped keys: they are the person's settings, not tenant data, and whether to remove them at sign-out is a product decision. Anything that is tenant data must not be there.

    The interface and accessibility

    Say where you are. The workspace switcher is a labelled select ("Workspace") with the tenant names, and the page heading carries the tenant's name, so a consultant always knows which customer's data is in front of them. A branded header colour alone is not enough: it fails for people who cannot see it and for a tenant whose brand is the product default.

    Announce the change. A switch replaces most of the page. A polite status line says "Loading workspace" and then "3 tickets"; WCAG 4.1.3 (Status Messages, level AA) asks that status messages can be presented by assistive technology without receiving focus, and its understanding document gives "Searching..." and a results count as examples. The main region sets aria-busy while loading; MDN describes it as indicating that an element is being modified, so assistive technology may wait before informing the user. Where keyboard focus goes after a switch (the heading, or the switcher itself) is a design decision to test with users; the lab asserts roles and text and says nothing about speech or focus order.

    Brand and contrast. The 4.5:1 and 3:1 checks run when a tenant saves its colours and again when the configuration is merged. That is the only reliable place: a tenant's chosen colour on a background you do not control can fail even if both look fine to the tenant.

    Delivery and performance

    The first paint should already carry the right brand, or the page flashes the product colours and then the tenant's. That argues for sending the tenant's tokens with the first HTML, which makes the HTML tenant-specific and therefore a caching question: MDN says Vary makes responses be cached separately by the request headers it lists, and Cache-Control: private allows storage only in a private cache such as a browser's. A shared cache that stores tenant HTML under one URL without varying on the host is a leak, which the concept lesson's closing scenario walks through; see also HTTP Caching for the Front End. One build for all tenants keeps the bundle the same for everyone and the per-tenant payload small: a configuration object and a handful of tokens. Do not add per-tenant code branches to the bundle; each is a fork in disguise. See Runtime Configuration and Environments for configuration that changes without a rebuild.

    Failure modes

    Failure What the person sees Response
    Unknown or look-alike host A "not found" page, never a default tenant Strict resolver with a reason
    Switch during a slow request The new tenant only Epoch check; abort is a courtesy
    Server ignores the abort Nothing wrong The epoch check still drops the answer
    Not a member, or no such tenant "Workspace not found" for both Same wording; the server answers 404 for both
    An answer about another tenant An error, no data Discard and log a mismatch
    Unreadable tenant brand The product colours Validate on save and on read; warn
    Plan feature called directly "Not available" Server refuses; screen hid the button as a courtesy
    Shared computer, two people Each sees only their own preferences User in every scoped key
    Sign out with a request in flight A signed-out screen New epoch; late answers ignored
    Stale tenant list A switch to a tenant the person left The server answers 404; the screen says not found

    Trade-offs

    Decision Choice Cost Revisit when
    Tenant in the address Subdomain, with a path fallback Wildcard certificate and DNS; path shares an origin A customer needs its own domain
    Where the tenant lives in code Resolved once into the store Every module must take it from there Many entry points appear
    Cache keys Tenant and user in every key A helper everyone must use A client cache library supplies it
    Switch Purge, clear screen, new epoch The new workspace always starts cold Switching is so frequent that warm caches matter
    Wrong-tenant answers Discard as an error A defensive check the server should make unnecessary The edge and the API are proven consistent
    Brand input Validate, fall back A customer may dislike the fallback A design system offers accessible brand ranges
    Features Hide and enforce twice Two places in step One shared policy source exists

    Build it

    The lab is examples/frontend/labs/multi-tenant-app-core: a pure TypeScript core and a thin React shell. It imports the virtual clock from the autocomplete-combobox lab and the contrast formula from the design-tokens-theming lab instead of copying them. Time is a virtual clock that moves only when a test says so, and the server is a deterministic fake with latencies the test chooses. The files are resolve.ts, scope.ts, config.ts, server.ts, tenantApp.ts (the store), sample.ts (invented tenants and people) and TenantShell.tsx (the view).

    cd examples/frontend/labs/multi-tenant-app-core
    pnpm test          # 33 tests
    pnpm typecheck
    node src/demo.ts   # prints the blocks shown in this lesson

    The 33 tests passed in the run made for this lesson: 27 in test/core.test.ts (resolution, scoped keys, layered configuration and brand validation, the switch, not-found, mismatch, features, density, sign out) and 6 in test/react.test.tsx. The React tests render into jsdom with Testing Library and check the heading, the tickets, the brand tokens on the root element, the labelled workspace switcher listing only the person's tenants, that a switch clears the first tenant's content, that the Reports button exists only on a plan with it, and Strict Mode. jsdom is a JavaScript model of the DOM, not a browser: there are no real origins, cookies, CDN, service workers or screen readers.

    Break it. In tenantApp.ts, in switchTo, comment out purge(previous); (the first of two calls). In the run made for this lesson the test "clears the screen at once on a switch" failed, because the old tenant's cache entry survived. Revert it. A second experiment: change the condition in aboutTenant to if (false) {, and the test "discards an answer that is about a different tenant than the one asked for" fails. Revert that too.

    The output blocks above are verbatim excerpts of examples/frontend/golden/multi-tenant-app-core.txt, captured with node examples/frontend/tools/capture-golden.mjs.

    In practice: a consultant sees the wrong customer for a moment

    The situation

    A help-desk product grows from one customer to eight. Agency staff work for several customers and switch many times a day. A support lead reports that after switching, the previous customer's ticket subjects sometimes show under the new customer's name for a second or two, and a screenshot proves it.

    Starting architecture

    • Tenant in the path of a single host, so one origin holds every tenant's storage.
    • A module-level current tenant read by every fetch helper.
    • A client cache keyed by the call name, and a switch that only changes the variable.

    Options considered

    1. Clear the cache on every switch, nothing else.
    2. Move to a subdomain per tenant so the browser separates storage, keep the module variable.
    3. Put the tenant in every key, make the switch an epoch with abort, purge and a cleared screen, and discard any answer about another tenant.

    The decision

    Option 3 first, then option 2 as a migration. Clearing the cache does not stop a request already in flight from landing after the clear. A subdomain per tenant helps storage and service workers but does nothing about a late answer inside one tab. The epoch and the keys make both failures impossible in the client, and the subdomain move then adds browser-level separation.

    Rollout and verification

    The team writes the failing test first: a fake server where Acme answers slowly and Bravo quickly, and a switch in between. The old code shows Acme's tickets under Bravo; the new code does not. A second test uses two tenants and the same call and asserts different data, which a one-tenant test cannot see. It then ships behind a flag, with a log line for every dropped answer and every mismatch, and watches both.

    The 2 a.m. failure

    After a release, an upstream layer begins to ignore client aborts. Traffic rises because abandoned requests run to completion, and a few answers still arrive late. Because the store drops any answer from an earlier epoch, the screen stays correct and the alert is about request volume, not about a leak. The on-call engineer checks the drop log, confirms none of the dropped answers reached the screen, and opens a ticket with the layer's owner.

    This is a realistic scenario, not a case history.

    The other side of this topic

    The server holds the real isolation: where each tenant's rows live, how the tenant is bound to every query, and how membership is verified on every request. The client's discipline (keys, epochs, strict resolution) reduces what a bug can show, but only the server can refuse data. The case for the server side is in Multi-Tenancy: Tenant Data and Isolation.

    Architect's notes

    • Build every key through one function, so nobody types a raw one.
    • Give each tenant session an epoch, and check it before applying any answer.
    • Clear the screen before loading the new tenant, not after.
    • Never default to a tenant. Unknown means not found, with a reason in the log.
    • Test with two tenants always. A one-tenant test cannot see a leak.
    • Treat a tenant's branding as input: validate on save and on read.

    Common mistakes

    • A module-level "current tenant" that changes under requests in flight.
    • A cache or storage key without the tenant, or without the user on a shared computer.
    • Abort as the only guard. A request that cannot be cancelled still lands.
    • A different message for "not yours" and "not there". It confirms what exists.
    • Trusting the tenant in the URL as proof of membership.
    • Hiding a feature and forgetting the server check.
    • Accepting any colour a customer types.

    Key takeaways

    • Every piece of client state names its tenant (and user); one helper builds the keys.
    • The tenant in the browser is a selector; the server decides membership.
    • A switch starts a new epoch: abort, purge, clear the screen, then load; answers from an earlier epoch are dropped.
    • Not yours and not there look the same, and an answer about the wrong tenant is an error.
    • Configuration is layered data, validated when saved and when read.
    • Test with two tenants, a slow answer and a switch in between.
    • Say what the lab cannot show: real origins, cookies, CDNs and screen readers.

    Practice exercises

    Exercise 1: Beginner (30 minutes). Run the lab's demo and, for each block, write which rule of the shell produced each line (resolution, scoped key, epoch, uniform 404, mismatch).

    Exercise 2: Intermediate (2 hours). Persist the last active tenant per user through scopedStorage, and decide what a deep link to a tenant the person is not in should do. Write the tests first.

    Exercise 3: Intermediate (2 hours). Add a time-limited trial feature to a tenant record and test the boundary with the virtual clock.

    Exercise 4: Advanced (3 hours). Score this case against the ten-part rubric from the case study method lesson, and write the paragraph that would raise its lowest part.

    Official documentation

    In this course

    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