System design · Concept 11

Frontend Architecture

Rendering strategies, the BFF pattern, caching from browser to CDN, state management, real-time updates, Core Web Vitals, micro-frontends and SPA auth for React and Angular teams.

19 min read

In short

  • CSR behind a login; SSR or SSG plus edge caching for public pages
  • A BFF aggregates and shapes, without business rules
  • Only shared responses at the edge; per-user is private
  • Server state in a query cache, filters in the URL
  • Live data: snapshot, deltas, resync on reconnect

In a design review, the frontend is often drawn as one box labelled "SPA". In practice it holds many decisions that change latency, cost and security: where HTML gets rendered, which layer caches what, how live data reaches the screen, and where tokens live. This lesson covers the decisions a React or Angular team makes, and the trade-offs to say out loud.

Rendering strategies

StrategyHow it worksFirst content (LCP)SEOServer costGood fit
CSR (client-side rendering)Server sends an empty shell plus JS; the browser fetches data and rendersSlowest on a cold visit: download, parse and run JS, then fetch dataWeakLowest: static files on a CDNApps behind sign-in: back-offices, dashboards, admin tools
SSR (server-side rendering)Server renders HTML per request; the browser then hydrates itFast, but TTFB includes your server and data callsStrongCompute on every requestPublic pages that are personalized or change often
SSG / prerenderingHTML is rendered at build timeFastest: plain files from the CDNStrongBuild time onlyMarketing pages, docs, catalog pages that rarely change
ISR / revalidationPrerendered pages are regenerated in the background after N seconds or on demandFast (CDN)StrongSmallLarge catalogs that change hourly
Streaming SSRServer sends the HTML shell at once and streams slow sections as their data arrivesShell immediately, slow parts laterStrongCompute per requestPages with one slow data source

Hydration attaches event handlers and state to server-rendered HTML. Until it finishes, the page looks ready but clicks may do nothing, which hurts INP. Hydration mismatches happen when the server renders something different from the client: new Date(), Math.random(), window checks or locale formatting. They show up as console errors, and the framework may throw away the server HTML for that part and render it again on the client, which wastes the SSR work and can flicker.

  • React: Next.js (App Router with Server Components and streaming through Suspense and loading.tsx), React Router in framework mode, or a plain Vite SPA. React 18+ hydrates selectively: Suspense boundaries split the page into chunks that hydrate separately, and the chunk the user interacts with goes first.
  • Angular: ng add @angular/ssr adds SSR and prerendering. provideClientHydration() reuses the server DOM instead of re-rendering, withEventReplay() replays clicks made before hydration, and incremental hydration (on by default with provideClientHydration() since Angular 22; earlier versions opt in with withIncrementalHydration()) lets @defer (hydrate on viewport) hydrate sections only when needed.
  • Hosting: CSR and SSG output is just static files, so it goes in object storage or a static host behind a CDN: S3 with CloudFront, Blob Storage or Static Web Apps with Front Door, Cloud Storage with Cloud CDN, or a platform such as Netlify, Vercel or Cloudflare Pages. SSR needs a Node runtime: run it on containers or app hosting (ECS/Fargate, App Service or Container Apps, Cloud Run) behind the CDN, and let the CDN cache pages that aren't personalized. Check what a managed static host supports before you pick it: some run SSR only for certain frameworks or only as a preview feature, and some serve Angular as static files only, so Angular SSR goes on your own containers.

Rule of thumb: behind a login, CSR is usually right. For public pages that must rank in search and load fast on phones, prerender or SSR them and cache at the edge.

Backend for Frontend (BFF)

A BFF is a thin backend owned by the frontend team and shaped for one experience (web, mobile, wallboard). It sits between the browser and the domain services.

                  ┌─────────────────────┐
 Angular SPA ───► │ Web BFF             │ ──► Orders API
                  │ aggregate · shape · │ ──► Catalog API
 Mobile app ───►  │ auth · cache        │ ──► Pricing API
   (own BFF)      └─────────────────────┘ ──► Queue / push service
A BFF shouldA BFF should not
Aggregate the 5 calls a screen needs into 1 round tripHold business rules (pricing, eligibility); those belong in domain services
Shape and trim responses for its clientBecome a shared "god API" that every client depends on
Translate protocols: gRPC or messaging inside, JSON and WebSockets or SSE outsideDuplicate logic that other BFFs also need (move it into a service)
Keep tokens server-side and give the browser a cookie (see Auth)Add a hop for a screen that calls one API anyway
Cache per screen, apply per-user rate limits, read feature flags

Implementation options: ASP.NET Core minimal APIs (with YARP for plain proxying), a Node service, or a GraphQL gateway (Hot Chocolate in .NET, Apollo in Node) when many screens need different shapes of the same data. An API gateway (API Gateway, API Management, Apigee, Kong) stays in front of the domain services for keys, quotas and policies, but it's not a place for screen-specific aggregation logic.

Caching from the browser to the CDN

 Component state ─► Server-state cache ─► Service worker ─► HTTP cache ─► CDN ────────► BFF cache ─► API
 (memory)           (TanStack Query, …)   (Cache Storage)   (browser)     (edge POP)    (Redis)

The HTTP headers decide what the browser and the CDN may keep:

DirectiveMeaning
max-age=NFresh for N seconds in any cache
s-maxage=NOverrides max-age for shared caches (CDN) only
public / privateprivate means only the user's browser may store it, never a CDN
no-cacheStore it, but revalidate with the server before every use (cheap 304 with an ETag)
no-storeDon't store it anywhere
immutableNever revalidate while fresh
stale-while-revalidate=NServe stale for up to N seconds while refreshing in the background
ETag + If-None-MatchRevalidation: 304 Not Modified instead of the body

Recipes for a React or Angular app:

ResourceHeaderWhy
Hashed bundles (main.8c1f2a.js)public, max-age=31536000, immutableA new deploy means new file names, so old files can be cached forever
index.htmlno-cacheThe one file whose name never changes; revalidating is cheap
Shared reference data (countries, depots)public, max-age=60, s-maxage=300, stale-while-revalidate=60Same for every user, so the CDN can absorb it
Per-user API responsesprivate, no-cache plus an ETagNever cached at the edge; revalidation still saves bandwidth
Sensitive data (payments, PII)no-storeNothing left behind on shared machines

Set these where the files are served: object metadata on S3, Blob Storage or Cloud Storage, the static host's config file (staticwebapp.config.json, netlify.toml, vercel.json), or CDN rules. Most CDNs honour the origin's Cache-Control, so a private response isn't cached at the edge, but check the settings that override it: CloudFront applies a cache policy's minimum TTL even to private responses when that minimum is above 0, Cloud CDN's FORCE_CACHE_ALL mode ignores private, and Front Door and other CDNs have similar override rules. Don't vary CDN caching on Cookie or Authorization; if a response depends on the user, it shouldn't be in a shared cache at all.

Service workers add a programmable cache inside the browser, for offline support and instant repeat loads. Angular has @angular/service-worker (ngsw-config.json with assetGroups and dataGroups using the freshness or performance strategy). React apps usually use Workbox (CacheFirst, NetworkFirst, StaleWhileRevalidate). The classic bug is users stuck on an old version, so handle updates explicitly (Angular's SwUpdate, Workbox's waiting worker) and ship a kill switch (Angular's safety-worker.js).

Deploys and lazy chunks: if a deploy deletes the old hashed files, a user who loaded the old index.html gets a failed import when they navigate to a lazy route (ChunkLoadError). Keep the previous release's assets around for a few days, and reload the page when a chunk fails to load.

State management

Most "state management" pain comes from mixing different kinds of state in one store.

KindExamplesLives inReactAngular
Server stateOrders, products, the current userA cache of server data, keyed by queryTanStack Query, RTK Query, SWRServices with signals, resource() / httpResource() (stable since Angular 22; experimental in 19-21), TanStack Query for Angular
Local UI stateIs the menu open, input textThe componentuseState, useReducerComponent fields, signal()
Shared client stateSelected tenant, theme, a multi-step wizardA small storeContext (for rarely changing values), Zustand, Redux ToolkitA service with signals, NgRx SignalStore, NgRx Store
URL stateFilters, sort, page, selected tabThe URLuseSearchParamsRouter query params, withComponentInputBinding()
Form stateValues, validation, dirty/touchedThe form libraryReact Hook FormTyped Reactive Forms
Live stateCounters and lists pushed by the serverA store fed by a streamuseSyncExternalStore over a socket storeRxJS streams into signals (toSignal)

Rules that hold up:

  • Server data isn't app state. It's a cache of something the server owns, so it needs deduplication, freshness rules, background refetch and invalidation after mutations. A server-state library does that per query key. Copying responses into Redux or NgRx means rebuilding that cache by hand, usually badly.
  • Derive, don't duplicate: computed(), useMemo or selectors instead of storing values you can calculate.
  • Put shareable state in the URL, so deep links and the back button work.
  • Reach for Redux or NgRx when many components change shared client state in complex ways and you want strict patterns and devtools. For most CRUD screens it's overhead.

Real-time updates

OptionDirectionLatencyInfrastructureAfter a disconnectGood fit
Short pollingClient pulls every N sUp to N sOne request per client per N s, mostly unchanged dataNatural: every poll is a fresh readLow-frequency data, small audiences, a fallback
Long pollingServer holds the request until data arrivesLowHeld requestsNaturalLegacy fallback
SSE (EventSource)Server → clientLowOne HTTP stream per client. On HTTP/1.1 a browser allows only ~6 connections per origin, shared across tabsBuilt in: reconnects and sends Last-Event-IDFeeds, notifications, progress
WebSocketsBoth waysLowestStateful connections on your servers, plus a backplane to broadcast across instancesDIYChat, collaboration, games
Managed real-time service (API Gateway WebSocket APIs or AppSync, Azure SignalR Service or Web PubSub, Firebase Realtime Database, Ably, Pusher)BothLowManaged: the service holds the connections and fans messages out; billed per connection and per messageClient SDKs reconnect; most don't replay what was sent while a client was goneMany clients needing push, without running sockets and a backplane yourself

A managed real-time service holds the client connections, so app servers stay stateless and need no backplane. It comes in two shapes. Either your app keeps its server-side hub and the service proxies the connections to it (Azure SignalR Service in Default mode does this for ASP.NET Core SignalR hubs), or there's no long-running server at all: your backend publishes through the service's API, and the service calls your functions on events such as connect and disconnect (API Gateway WebSocket APIs with Lambda, Web PubSub event handlers, Ably or Pusher webhooks). Either way, group or channel membership is decided on the server, or carried in a token the server signed, never by what the client asks for, so authorization stays on the server. These services bill per message as well as per connection, so message size and rate are a cost decision too.

Browsers can't set an Authorization header on a WebSocket or EventSource, so clients (SignalR's among them) put the token in the query string. Keep those tokens short-lived and keep query strings out of your logs.

Patterns that make live data trustworthy:

  1. Snapshot plus deltas with sequence numbers. Start the connection and buffer incoming deltas, fetch a snapshot that says which sequence number it reflects, drop buffered deltas at or below it and apply the rest. If a delta skips a number, fetch a new snapshot.
  2. Resync after every reconnect. Anything sent while you were disconnected is gone. (ASP.NET Core 8's stateful reconnect can cover a brief network blip, but not a laptop that slept for an hour.)
  3. Back off with jitter, so 2,000 clients don't reconnect in the same second after a deploy.
  4. Show freshness. Display "as of 10:42:05", send heartbeats that carry the time of the latest processed event, and grey out data older than your threshold. A connected socket doesn't prove the data is fresh.
  5. Throttle in the client. Coalesce updates by key (latest wins) and render at most every 250-500 ms (bufferTime or auditTime in RxJS, or a requestAnimationFrame loop). Pause rendering when the tab is hidden (Page Visibility API).
▶ Try
// SignalR client (works the same in Angular and React)
const connection = new HubConnectionBuilder()
  .withUrl('/hubs/ops', { accessTokenFactory: () => getAccessToken() })
  .withAutomaticReconnect({
    // exponential backoff up to 30 s, randomized ±50% so clients spread out; never give up on a wallboard
    nextRetryDelayInMilliseconds: (ctx) => Math.min(30_000, 1_000 * 2 ** ctx.previousRetryCount) * (0.5 + Math.random()),
  })
  .build();

connection.onreconnecting(() => status.set('reconnecting')); // show the banner, mark data stale
connection.onreconnected(() => resync());                    // fresh snapshot + buffered deltas

Performance budgets and Core Web Vitals

Google's Core Web Vitals are measured on real users at the 75th percentile of page loads.

MetricMeasuresGoodCommon causes of a bad scoreTypical fixes
LCP (Largest Contentful Paint)Loading: when the main content appears≤ 2.5 sSlow TTFB, render-blocking JS and CSS, CSR waiting for data, a large hero imageSSR or SSG, CDN, fetchpriority="high" on the hero image, smaller initial bundles
INP (Interaction to Next Paint)Responsiveness: input to the next frame, across all interactions≤ 200 msLong tasks (> 50 ms), heavy re-renders, hydration, big listsSplit long tasks, startTransition, OnPush and signals, virtual scrolling, web workers
CLS (Cumulative Layout Shift)Visual stability≤ 0.1Images without dimensions, late banners, font swapswidth/height or aspect-ratio, reserved space, preloaded fonts with font-display

INP replaced FID in March 2024. TTFB (good ≤ 0.8 s) and FCP (good ≤ 1.8 s) aren't Core Web Vitals but help diagnose a slow LCP.

  • Lab vs field: Lighthouse runs on one machine and is good for catching regressions in CI. Field data (the web-vitals library sending to your monitoring or analytics tool, or Chrome UX Report data) is what users experience.
  • Budgets fail the build. Angular has budgets in angular.json; React and Vite projects use tools like size-limit in CI, and Lighthouse CI can assert on lab metrics.
"budgets": [
  { "type": "initial", "maximumWarning": "400kB", "maximumError": "600kB" },
  { "type": "anyComponentStyle", "maximumWarning": "6kB", "maximumError": "10kB" }
]
  • Ship less JavaScript: lazy routes (loadComponent and loadChildren in Angular, React.lazy with Suspense), Angular @defer blocks for heavy widgets, tree-shakable imports, and a bundle analyzer before adding a dependency.
  • Images: modern formats (AVIF, WebP), explicit dimensions, lazy loading below the fold, NgOptimizedImage in Angular.
  • Network: Brotli, HTTP/2 or HTTP/3 (most CDNs enable them for every client), preconnect to your API origin, and few blocking requests before first paint.

Micro-frontends

Micro-frontends split one UI into slices that separate teams build and deploy independently.

ApproachHowProsCons
Route-level splitThe CDN or a reverse proxy sends /orders/* to one app and /billing/* to anotherSimplest, fully independentFull page load between apps; shared header and auth duplicated
Runtime federationModule Federation (webpack, Rspack) or Native Federation (Angular's esbuild builds) loads remote modules at runtimeFeels like one SPA; shared dependencies loaded onceVersion skew, runtime integration failures, complex tooling
Web componentsEach team ships custom elements (Angular Elements, wrapped React components)Framework-agnosticStyling, SSR and event plumbing friction; several framework runtimes on one page
IframesEach slice in an iframeStrongest isolationDeep links, accessibility, responsive layout and shared auth all get harder
Build-time packagesTeams publish packages that one app composesType-safe and simpleNot independent deploys: a modular monolith

Micro-frontends buy independent release trains. They cost consistency (one design system, one way to route and authenticate), performance (two copies of Angular or React on one page roughly doubles framework JS), and the type checking you lose at runtime boundaries. Many teams that ask for micro-frontends really need module boundaries, clear code ownership and CI that only builds what changed, which a monorepo tool such as Nx gives you for far less. They do earn their keep with several teams on genuinely separate release cycles, or during a strangler migration from one framework to another.

Auth in single-page apps

SPAs are public clients: they can't keep a secret, so they use the authorization code flow with PKCE over OpenID Connect (OIDC). The implicit flow is deprecated. The identity provider can be Cognito, Entra ID or Entra External ID, Google Cloud Identity Platform, or Auth0, Okta or Keycloak; let a certified OIDC client library do the protocol work. oidc-client-ts (with react-oidc-context in React) and angular-auth-oidc-client work with any of them, and providers also ship their own SDKs, such as Amplify for Cognito, MSAL for Entra ID and the Firebase Auth SDK.

▶ Try
// Angular (angular-auth-oidc-client): attach tokens only to your own API
provideAuth({
  config: {
    authority: 'https://login.example.com',
    clientId: 'orders-spa',
    redirectUrl: window.location.origin,
    responseType: 'code',                       // authorization code flow + PKCE
    scope: 'openid profile offline_access orders.read',
    silentRenew: true,
    useRefreshToken: true,
    secureRoutes: ['https://api.example.com/orders'],
  },
}),
provideHttpClient(withInterceptors([authInterceptor()])),
▶ Try
// React (react-oidc-context): try silently, fall back to an interactive sign-in only when required
const auth = useAuth();
async function getOrdersToken(): Promise<string> {
  try {
    const user = await auth.signinSilent(); // refresh token, no page change
    if (user) return user.access_token;
  } catch {
    // the provider needs the user: session expired, consent or MFA
  }
  await auth.signinRedirect(); // leaves the page
  throw new Error('Redirecting to sign-in');
}
  • Tokens: the ID token tells the SPA who signed in. The access token is for your API's scope, and the API validates its signature, aud, iss, and scp or roles. Register the exact redirect URIs with the identity provider, as a public client with no secret.
  • Storage: SPA libraries such as oidc-client-ts and MSAL keep tokens in sessionStorage by default (localStorage and memory are options). Any script running in your page can read them, so XSS is the real threat: use a strict Content Security Policy and avoid dangerouslySetInnerHTML and bypassSecurityTrustHtml on untrusted input.
  • Session length: providers often rotate refresh tokens issued to SPAs and cap how long they live, and browsers that block third-party cookies break silent renewal that relies on a hidden iframe. Expect an occasional redirect, and design for it.
  • Hiding a button is UX, not security. The API enforces every authorization rule.

The BFF alternative. The BFF becomes a confidential client: it runs the code flow server-side (ASP.NET Core's OpenID Connect handler, or a library such as Duende BFF), keeps tokens in a server-side session (Redis when you scale out) and gives the browser only an HttpOnly, Secure, SameSite cookie. Injected script can no longer steal tokens and use them from another machine, but it can still call the API as the user while the page is open. You also take on CSRF protection, session storage and an extra hop. The OAuth guidance for browser-based apps prefers this pattern for high-value apps; an OIDC library in the browser with short-lived tokens and a strict CSP remains common and acceptable for most internal tools.

When to use / trade-offs

  • CSR behind a login; SSG or SSR plus CDN caching for public, SEO-sensitive pages. SSR adds servers to run and hydration costs to INP.
  • A BFF when screens need data from several services, when you want tokens out of the browser, or when web and mobile need different shapes. Skip it when the SPA talks to one well-shaped API.
  • Cache aggressively at the edge only for responses that are the same for everyone. Anything per-user is private.
  • A server-state library before a global store. Add Redux or NgRx for complex shared client state, not for API data.
  • Polling is fine at small scale and as a fallback. A managed real-time service (API Gateway WebSockets, SignalR Service or Web PubSub, Firebase, Ably or Pusher) when many clients need push, and SSE when it's one-way and you control the server. Always design the resync path.
  • Budgets in CI catch regressions before users do; field data tells you whether users are actually fine.
  • Micro-frontends only for real organisational scaling problems; a modular monolith is cheaper.

Checklist

  • Rendering strategy per area (public vs signed-in) and where SSR would run
  • BFF scope: aggregation, auth, caching; no business rules
  • Cache-Control per resource type; hashed assets immutable, index.html revalidated, per-user responses private
  • State split: server state, client state, URL state, forms
  • Real-time transport, snapshot plus deltas with sequence numbers, reconnect with jitter, staleness shown
  • Core Web Vitals targets at p75, budgets enforced in CI, field monitoring
  • Auth code + PKCE via an OIDC client library (or a BFF with cookies), API-side authorization, CSP

Practise this concept

In the app: a short video and a 12-question concept check. Free with a GitHub account.

Open in the app