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.
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
| Strategy | How it works | First content (LCP) | SEO | Server cost | Good fit |
|---|---|---|---|---|---|
| CSR (client-side rendering) | Server sends an empty shell plus JS; the browser fetches data and renders | Slowest on a cold visit: download, parse and run JS, then fetch data | Weak | Lowest: static files on a CDN | Apps behind sign-in: back-offices, dashboards, admin tools |
| SSR (server-side rendering) | Server renders HTML per request; the browser then hydrates it | Fast, but TTFB includes your server and data calls | Strong | Compute on every request | Public pages that are personalized or change often |
| SSG / prerendering | HTML is rendered at build time | Fastest: plain files from the CDN | Strong | Build time only | Marketing pages, docs, catalog pages that rarely change |
| ISR / revalidation | Prerendered pages are regenerated in the background after N seconds or on demand | Fast (CDN) | Strong | Small | Large catalogs that change hourly |
| Streaming SSR | Server sends the HTML shell at once and streams slow sections as their data arrives | Shell immediately, slow parts later | Strong | Compute per request | Pages 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
Suspenseandloading.tsx), React Router in framework mode, or a plain Vite SPA. React 18+ hydrates selectively:Suspenseboundaries split the page into chunks that hydrate separately, and the chunk the user interacts with goes first. - Angular:
ng add @angular/ssradds SSR and prerendering.provideClientHydration()reuses the server DOM instead of re-rendering,withEventReplay()replays clicks made before hydration, and incremental hydration (on by default withprovideClientHydration()since Angular 22; earlier versions opt in withwithIncrementalHydration()) 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 should | A BFF should not |
|---|---|
| Aggregate the 5 calls a screen needs into 1 round trip | Hold business rules (pricing, eligibility); those belong in domain services |
| Shape and trim responses for its client | Become a shared "god API" that every client depends on |
| Translate protocols: gRPC or messaging inside, JSON and WebSockets or SSE outside | Duplicate 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:
| Directive | Meaning |
|---|---|
max-age=N | Fresh for N seconds in any cache |
s-maxage=N | Overrides max-age for shared caches (CDN) only |
public / private | private means only the user's browser may store it, never a CDN |
no-cache | Store it, but revalidate with the server before every use (cheap 304 with an ETag) |
no-store | Don't store it anywhere |
immutable | Never revalidate while fresh |
stale-while-revalidate=N | Serve stale for up to N seconds while refreshing in the background |
ETag + If-None-Match | Revalidation: 304 Not Modified instead of the body |
Recipes for a React or Angular app:
| Resource | Header | Why |
|---|---|---|
Hashed bundles (main.8c1f2a.js) | public, max-age=31536000, immutable | A new deploy means new file names, so old files can be cached forever |
index.html | no-cache | The one file whose name never changes; revalidating is cheap |
| Shared reference data (countries, depots) | public, max-age=60, s-maxage=300, stale-while-revalidate=60 | Same for every user, so the CDN can absorb it |
| Per-user API responses | private, no-cache plus an ETag | Never cached at the edge; revalidation still saves bandwidth |
| Sensitive data (payments, PII) | no-store | Nothing 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.
| Kind | Examples | Lives in | React | Angular |
|---|---|---|---|---|
| Server state | Orders, products, the current user | A cache of server data, keyed by query | TanStack Query, RTK Query, SWR | Services with signals, resource() / httpResource() (stable since Angular 22; experimental in 19-21), TanStack Query for Angular |
| Local UI state | Is the menu open, input text | The component | useState, useReducer | Component fields, signal() |
| Shared client state | Selected tenant, theme, a multi-step wizard | A small store | Context (for rarely changing values), Zustand, Redux Toolkit | A service with signals, NgRx SignalStore, NgRx Store |
| URL state | Filters, sort, page, selected tab | The URL | useSearchParams | Router query params, withComponentInputBinding() |
| Form state | Values, validation, dirty/touched | The form library | React Hook Form | Typed Reactive Forms |
| Live state | Counters and lists pushed by the server | A store fed by a stream | useSyncExternalStore over a socket store | RxJS 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(),useMemoor 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
| Option | Direction | Latency | Infrastructure | After a disconnect | Good fit |
|---|---|---|---|---|---|
| Short polling | Client pulls every N s | Up to N s | One request per client per N s, mostly unchanged data | Natural: every poll is a fresh read | Low-frequency data, small audiences, a fallback |
| Long polling | Server holds the request until data arrives | Low | Held requests | Natural | Legacy fallback |
SSE (EventSource) | Server → client | Low | One HTTP stream per client. On HTTP/1.1 a browser allows only ~6 connections per origin, shared across tabs | Built in: reconnects and sends Last-Event-ID | Feeds, notifications, progress |
| WebSockets | Both ways | Lowest | Stateful connections on your servers, plus a backplane to broadcast across instances | DIY | Chat, collaboration, games |
| Managed real-time service (API Gateway WebSocket APIs or AppSync, Azure SignalR Service or Web PubSub, Firebase Realtime Database, Ably, Pusher) | Both | Low | Managed: the service holds the connections and fans messages out; billed per connection and per message | Client SDKs reconnect; most don't replay what was sent while a client was gone | Many 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:
- 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.
- 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.)
- Back off with jitter, so 2,000 clients don't reconnect in the same second after a deploy.
- 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.
- Throttle in the client. Coalesce updates by key (latest wins) and render at most every 250-500 ms (
bufferTimeorauditTimein RxJS, or arequestAnimationFrameloop). Pause rendering when the tab is hidden (Page Visibility API).
// 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.
| Metric | Measures | Good | Common causes of a bad score | Typical fixes |
|---|---|---|---|---|
| LCP (Largest Contentful Paint) | Loading: when the main content appears | ≤ 2.5 s | Slow TTFB, render-blocking JS and CSS, CSR waiting for data, a large hero image | SSR 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 ms | Long tasks (> 50 ms), heavy re-renders, hydration, big lists | Split long tasks, startTransition, OnPush and signals, virtual scrolling, web workers |
| CLS (Cumulative Layout Shift) | Visual stability | ≤ 0.1 | Images without dimensions, late banners, font swaps | width/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-vitalslibrary sending to your monitoring or analytics tool, or Chrome UX Report data) is what users experience. - Budgets fail the build. Angular has
budgetsinangular.json; React and Vite projects use tools likesize-limitin 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 (
loadComponentandloadChildrenin Angular,React.lazywithSuspense), Angular@deferblocks 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,
NgOptimizedImagein Angular. - Network: Brotli, HTTP/2 or HTTP/3 (most CDNs enable them for every client),
preconnectto 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.
| Approach | How | Pros | Cons |
|---|---|---|---|
| Route-level split | The CDN or a reverse proxy sends /orders/* to one app and /billing/* to another | Simplest, fully independent | Full page load between apps; shared header and auth duplicated |
| Runtime federation | Module Federation (webpack, Rspack) or Native Federation (Angular's esbuild builds) loads remote modules at runtime | Feels like one SPA; shared dependencies loaded once | Version skew, runtime integration failures, complex tooling |
| Web components | Each team ships custom elements (Angular Elements, wrapped React components) | Framework-agnostic | Styling, SSR and event plumbing friction; several framework runtimes on one page |
| Iframes | Each slice in an iframe | Strongest isolation | Deep links, accessibility, responsive layout and shared auth all get harder |
| Build-time packages | Teams publish packages that one app composes | Type-safe and simple | Not 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.
// 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()])),
// 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, andscporroles. Register the exact redirect URIs with the identity provider, as a public client with no secret. - Storage: SPA libraries such as
oidc-client-tsand MSAL keep tokens insessionStorageby default (localStorageand 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 avoiddangerouslySetInnerHTMLandbypassSecurityTrustHtmlon 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-Controlper resource type; hashed assets immutable,index.htmlrevalidated, per-user responsesprivate - 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