Summary#
Frontend system design is about architecting the part of a product that runs in the user's browser. That includes:
- how HTML is produced: on the server, at build time, or in the browser;
- how data is fetched, cached and kept fresh;
- how much JavaScript is shipped, and when;
- how the code is split into components and owned by teams;
- how the experience stays fast, accessible and observable on real devices and real networks.
Backend design asks "how do we serve 100,000 requests per second?". Frontend design asks "how do we make each of those requests feel instant on a three-year-old phone on a train?".
The main levers:
- Rendering strategy: CSR, SSR, SSG, ISR, streaming, islands.
- A data layer that treats server data as a cache.
- Layered caching: HTTP cache, CDN, in-memory, IndexedDB, and service workers for offline.
- Performance budgets measured with Core Web Vitals. LCP measures loading, INP responsiveness and CLS visual stability.
- Code splitting and lazy loading.
- A component architecture backed by a design system, and micro-frontends when many teams share one page.
- Accessibility and frontend observability, as non-negotiable quality attributes.
The page ends by designing a news feed and an autocomplete UI end to end, the two most common frontend design interview questions.
Why It Exists#
For a long time "system design" meant servers, and the frontend was treated as a thin view layer. That stopped being true once web applications grew into products like Gmail, Figma, Google Docs and Facebook. Their frontends hold large amounts of state, run hundreds of thousands of lines of JavaScript, talk to dozens of APIs, work offline, and are built by hundreds of engineers at once. The frontend is now a distributed system in its own right:
- It runs on hardware you don't control. A flagship laptop and a budget Android phone can differ by 5–10× in JavaScript execution speed, and networks range from fibre to congested 3G.
- It's the last hop of every latency budget. A backend that answers in 50 ms is wasted if the page then spends 3 seconds downloading, parsing and executing JavaScript before anything is visible or clickable.
- It holds a cache of server state that can go stale, conflict and need invalidation, which brings back every caching problem from the server side (Caching Fundamentals).
- It has a release and ownership problem. Many teams ship into one page, and a single bad deploy breaks the whole experience.
- It's where users with disabilities succeed or fail, and in many countries accessibility is a legal requirement.
Performance has a measurable business impact. A widely cited 2016 Google study of mobile sites found that 53% of visits were abandoned if a page took longer than three seconds to load. Since 2021, Google Search has also used Core Web Vitals as a page-experience ranking signal.
That's why companies such as Meta and Google run dedicated frontend system design interviews. Senior frontend engineers are expected to reason about these trade-offs as rigorously as backend engineers reason about databases.
How It Works#
A modern web frontend has the same layers as any distributed system. It has a delivery edge (CDN), a server tier that may render HTML or aggregate APIs (often a backend-for-frontend), and a rich client. That client has its own layers:
- a component tree that renders UI;
- a state and data layer that caches server data;
- a service worker that can intercept network requests;
- telemetry that reports what users actually experience.
The sections below go through each layer in the order a design discussion usually takes:
- how HTML gets to the screen;
- how data flows;
- how it's cached;
- how fast it must be;
- how code is split;
- how the code base is organised;
- how it's made accessible and observable.
The final two sections combine everything into end-to-end designs.
Rendering strategies: CSR, SSR, SSG, ISR, streaming and islands#
The first architectural decision is where and when HTML is produced. Every option trades time to first byte, time until content is visible, time until the page is interactive, freshness, personalisation and server cost against each other.
Client-side rendering (CSR).
- How it works. The server sends a nearly empty HTML shell plus a JavaScript bundle. The browser downloads and runs the JavaScript, the app fetches data from APIs, and only then does content appear. This is the classic single-page application (SPA), built with Create React App, a Vite React app, or Angular.
- Pros:
- Hosting is trivial: static files on a CDN, with no rendering servers.
- Navigation after the first load is fast and app-like.
- Clear separation from the backend.
- Cons:
- Slow first load. Nothing meaningful appears until JavaScript downloads, parses, executes and fetches data. That's a chain of round trips, painful on slow phones.
- Weaker SEO and link previews for crawlers and social-media scrapers that don't run JavaScript well.
- Large bundles hurt every metric.
- Fits: apps behind a login where SEO doesn't matter and sessions are long: dashboards, admin tools, editors like Figma.
Server-side rendering (SSR).
- How it works. For each request, the server runs the components with fresh data and returns full HTML, which the browser can paint immediately. The same JavaScript then downloads and hydrates the page. Hydration means re-running the components in the browser to attach event handlers and make the HTML interactive.
- Pros:
- Fast first contentful paint and good LCP.
- Full SEO.
- Personalised content on first paint.
- Cons:
- Rendering servers to run and scale. Each request costs CPU, often 10–100 ms of render time.
- TTFB includes data fetching and rendering.
- The "uncanny valley". Between paint and hydration the page looks ready but doesn't respond to clicks. That hurts INP and frustrates users.
- Fits: dynamic, personalised pages that must load fast and be indexable: e-commerce product pages, news feeds, search results.
Static site generation (SSG).
- How it works. HTML is rendered at build time for every page and served from a CDN like any static file.
- Pros:
- The fastest possible TTFB (served from the edge in tens of milliseconds).
- No servers, near-zero cost, excellent resilience. A static file can't crash under load.
- Cons:
- Content is only as fresh as the last build.
- Build time grows with page count: 100,000 product pages can take a long time to build.
- No per-user content in the HTML.
- Fits: documentation (like this handbook), blogs, marketing pages.
Incremental static regeneration (ISR).
- How it works. A hybrid that Next.js introduced in 2020. Pages are generated statically, but each carries a revalidation interval. The first request after the interval still gets the cached (stale) page, while the server regenerates it in the background. That's the stale-while-revalidate idea applied to whole pages. On-demand revalidation lets a CMS webhook purge and rebuild one page as soon as its content changes.
- Pros: static-level speed, with freshness measured in seconds to minutes and no full rebuilds.
- Cons:
- Users can see stale pages within the window.
- It needs a platform that supports regeneration, so it doesn't work as a pure static export.
- Cache-invalidation bugs become page bugs.
- Fits: large catalogues and content sites where pages change occasionally and staleness of a minute is acceptable.
Streaming SSR.
- How it works. Instead of waiting for all data before sending any HTML, the server flushes the page in chunks. The shell (header, navigation, layout, skeletons) goes out immediately. Each slow section streams in as its data resolves, with a small inline script that slots it into place.
- History. Facebook's BigPipe (2010) pioneered this by splitting pages into "pagelets" flushed independently. React 18 (2022) made it mainstream with Suspense boundaries and streaming server rendering APIs, and frameworks such as Next.js and Remix build on it.
- Pros:
- TTFB and first paint no longer wait for the slowest API.
- Sections can hydrate selectively, in priority order, with sections the user interacts with first hydrated first.
- Cons:
- Status codes and headers are committed before all data is known, so errors after the first flush must be handled in-page.
- Some proxies and CDNs buffer responses and break streaming.
- Fits: pages that combine fast and slow data sources, such as a product page whose recommendations call is slow.
Islands architecture and partial hydration.
- How it works. Most of a content page is static HTML that needs no JavaScript. Islands render the whole page on the server (or at build time) but ship and hydrate JavaScript only for the interactive components, the "islands": a search box, a carousel, a cart button. The rest stays plain HTML.
- History. The term "component islands" came from Etsy frontend architect Katie Sylor-Miller in 2019. Jason Miller (creator of Preact) popularised it in 2020, and Astro is built around it.
- Pros: JavaScript cost is proportional to interactivity, not page size, which gives excellent INP and LCP on content-heavy sites.
- Cons:
- Islands don't share state easily.
- It's a poor fit for app-like pages where everything is interactive.
Related ideas:
- React Server Components (RSC). Components run only on the server and send a serialised UI description instead of code, so their dependencies never reach the browser. "Client components" are marked explicitly. This gives islands-style savings inside a React app, as in the Next.js App Router.
- Resumability. Qwik goes further and avoids hydration entirely. The server serialises enough state into the HTML that the browser can attach handlers lazily, on first interaction.
- Edge rendering. SSR runs in CDN edge functions close to the user, cutting TTFB for global audiences. It's limited by edge runtime constraints and by the distance from the edge to the data (Edge Computing and Edge Functions).
Comparing the options. The timings are typical for a mid-range phone on 4G. Real numbers depend on payload sizes.
| Strategy | TTFB | Content visible | Interactive | Freshness | Server cost |
|---|---|---|---|---|---|
| CSR | Very fast (static shell) | Slow: after JS plus API calls | After content | Live | None for HTML |
| SSR | Slower (render plus data) | Fast | After hydration | Live | Per request |
| SSG | Fastest (CDN) | Fastest | After hydration | At build time | None |
| ISR | Fastest (CDN) | Fastest | After hydration | Seconds to minutes stale | Occasional regeneration |
| Streaming SSR | Fast (shell first) | Progressive | Progressive, selective hydration | Live | Per request |
| Islands | Fast (static or SSR) | Fast | Fast: little JS | Depends on base | Low |
How to choose.
- Does the page need SEO or a fast first paint for anonymous users? If not, and sessions are long, CSR is fine.
- Is the content the same for everyone and slow to change? Use SSG, or ISR if it changes on its own schedule.
- Is it personalised or fast-changing? Use SSR, streamed if some data sources are slow.
- Is it mostly content with a few widgets? Use islands or server components to cut JavaScript.
Real apps mix strategies per route: a static marketing site, an ISR product catalogue, SSR search results and a CSR account dashboard, all in one Next.js app. In an interview, choose per page type and justify it with the metric you're optimising.
State management and data fetching#
Kinds of state. The biggest simplification in modern frontend architecture is realising that "state" is several different things, each with a natural home:
| Kind | Examples | Natural home |
|---|---|---|
| Server state (a cache of backend data) | Feed posts, user profile, search results | A query cache: TanStack Query, SWR, Apollo Client, Relay, RTK Query |
| URL state | Current route, filters, search query, page or cursor | The URL itself, through the router |
| Local UI state | Is this dropdown open, hover, input text being typed | Component state (useState) |
| Form state | Field values, validation errors, dirty flags | A form library or component state |
| Global client state | Theme, auth session, feature flags, a shopping cart before checkout | A small store (Context, Zustand, Redux, signals) |
| Persistent client state | Drafts, offline queue, cached data across sessions | IndexedDB or localStorage |
The common mistake is to push everything into one global store, such as Redux in its 2016 heyday. Server data then gets copied into the store, and you end up writing your own caching, deduplication, refetching and invalidation. Treating server state as a cache, owned by a query library, removes most of that code. What's left in global state is usually small.
Put shareable state in the URL. Filters, sort order, the open tab and the search query belong in the URL. That makes back and forward buttons, refresh, deep links and sharing work for free, and makes server rendering of that view possible.
Server state as a cache. Query libraries implement, on the client, the caching patterns covered in Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind:
- Keys. Every query has a key such as
["feed", userId]or["post", postId]. Components that ask for the same key share one cache entry and one network request. - Stale-while-revalidate. Cached data is shown immediately, even if stale, while a background refetch updates it. Freshness is controlled with
staleTime, and unused entries are garbage-collected after a timeout. - Request deduplication. Ten components mounting at once with the same key produce one request. This is the client-side twin of request coalescing ("single flight"), which prevents cache stampedes on servers.
- Refetch triggers. Window focus, network reconnect, polling intervals and explicit invalidation after a mutation.
- Retries with backoff for transient failures, and cancellation when a component unmounts or a newer request supersedes an older one.
Normalised versus document caches.
- Document caches. TanStack Query and SWR store each response as a blob under its key. That's simple and predictable. The weakness is that the same post appears in the feed response and the post-detail response, so a like updated in one isn't reflected in the other unless you update or invalidate both.
- Normalised caches. Apollo Client and Relay, both GraphQL clients, split responses into entities keyed by type and ID (
Post:123). Every query that referencesPost:123sees the update at once. The cost is cache complexity, and the need for stable IDs and schema knowledge. - The usual choice. Use document caches with deliberate invalidation for REST apps, and normalised caches for data-dense GraphQL apps such as Facebook's own product, which motivated Relay.
Data-fetching patterns that matter for performance:
- Avoid request waterfalls. A parent fetches the user, renders, then a child fetches the user's posts, then a grandchild fetches comments. That's three sequential round trips. On a 150 ms mobile RTT, that's nearly half a second of pure waiting.
- Fetch in parallel at the route level, so loaders run before rendering.
- Let the server aggregate: a BFF or GraphQL can return everything for a screen in one request (API Gateway and Backend-for-Frontend).
- Use Relay-style query hoisting, where each component declares its data needs as fragments, composed into one query per screen.
- Choose the API style for the client. REST is simple and HTTP-cacheable. GraphQL lets the client ask for exactly the fields a screen needs, which suits many screens over shared entities (API Styles: REST, gRPC, GraphQL and More). A BFF shapes responses per client type (web and mobile).
- Cursor pagination. Feeds and lists use an opaque cursor: "give me N items after this one". A timestamp of the oldest item seen works for reverse-chronological feeds. Offsets break when new items are inserted at the top: you'd see duplicates or skip items. The API returns
itemsplus anextCursor, and the client stores pages in order. - Prefetching. Start fetching data for the likely next screen on hover or viewport entry, or after the current screen settles, so navigation feels instant.
Optimistic updates. When a user likes a post, update the UI immediately. Then send the request, and roll back with an error message if it fails.
- Snapshot the cached post.
- Write the optimistic value (liked, count + 1).
- Send the mutation with an idempotency key, so a retry doesn't double-like. Better still, make the operation naturally idempotent with "set liked = true" rather than "increment". See Idempotency and Safe Retries.
- On success, replace the optimistic value with the server's response. On failure, restore the snapshot and tell the user.
Optimistic updates suit low-risk, high-success actions (likes, follows, reordering, marking as read). They're wrong for payments or anything where showing success falsely does harm. For those, show a pending state.
Real-time updates. Some state must be pushed: chat messages, notifications, live counters, collaborators' cursors. The choice of transport is covered in Polling, Long Polling, SSE, WebSockets and Webhooks:
- SSE for one-way server-to-client streams (notifications, LLM tokens);
- WebSockets for two-way, low-latency traffic (chat, multiplayer);
- polling when updates are rare and simplicity matters.
On the client, pushed events should update the same query cache the rest of the UI reads from. Write the new message into the conversation's cache entry, or invalidate the key. Then there's one source of truth, not a parallel real-time store. Reconnection must refetch or replay anything missed while disconnected, using a "since cursor" or a sequence number (Pattern: Pushing Realtime Updates).
Large collaborative state. Editors like Google Docs or Figma keep a local document model that applies changes instantly and syncs operations with a server. They use operational transformation or CRDTs to merge concurrent edits (Conflict Resolution, OT and CRDTs). That's the extreme end of "client state", where the frontend is a replica in a distributed database.
Client caching and offline: HTTP cache, storage and service workers#
Client-side caching stores data on the user's device, saving network round trips entirely. It's the fastest cache there is, because a disk or memory read on the device takes microseconds to a few milliseconds, against 50–300 ms for a network round trip. It's also the cache the backend controls least. Once a response is cached on millions of devices, you can't purge it. You can only make sure future responses are versioned correctly. So client caching is designed around immutability and revalidation.
Several caches stack between the user and the origin:
- in-memory caches inside the app (the query cache above);
- the browser's HTTP cache and back/forward cache;
- service worker caches and IndexedDB;
- the CDN edge;
- the origin's own caches.
Geography makes the CDN essential. A user in India fetching an image from an origin in Virginia pays about 250–300 ms per round trip, while a nearby CDN edge answers in about 20–40 ms (Content Delivery Networks (CDN)).
The HTTP cache: the free, built-in layer. Response headers tell the browser and CDNs what to do:
| Header | Meaning | Use for |
|---|---|---|
Cache-Control: public, max-age=31536000, immutable | Cache for a year; never revalidate | Content-hashed assets such as app.3f9a1c.js and images with versioned URLs |
Cache-Control: no-cache plus ETag | May store, but must revalidate each time; the server answers 304 Not Modified if the ETag still matches | HTML documents, frequently changing JSON |
Cache-Control: max-age=60, stale-while-revalidate=300 | Fresh for 60 s; for 5 more minutes serve stale while refetching in the background | Semi-dynamic API responses and pages |
Cache-Control: private | Only the user's browser may cache it, not shared CDNs | Personalised responses |
Cache-Control: no-store | Never store | Sensitive data (banking pages, tokens) |
s-maxage | A separate lifetime for shared caches (CDNs) | Letting the CDN cache longer than browsers |
The golden pattern: hashed assets forever, HTML always revalidated.
- Build output gets content hashes in filenames. A new deploy creates new URLs, so assets can be cached for a year and never invalidated.
- The HTML page is revalidated on every load, so it always points at the current hashes. That gives you instant cache busting with no purge.
- Never cache HTML with a long
max-age. Users would be stuck on an old release, and old HTML can reference asset files you've deleted from the server. - During rollouts, keep the previous release's assets online for a while, because tabs that are already open will still request them.
The back/forward cache (bfcache). It keeps whole pages in memory, so back and forward navigation is instant. Pages lose eligibility if they use unload handlers or certain APIs, so avoid those.
On-device storage options:
| Storage | Characteristics | Use for |
|---|---|---|
| In-memory (JS heap) | Fastest; lost on reload | Query cache, UI state |
| localStorage, sessionStorage | Synchronous, strings only, about 5 MB per origin; blocks the main thread | Tiny preferences (theme); avoid for data and never for tokens |
| IndexedDB | Asynchronous, structured, indexed, large (a share of free disk) | Offline data, drafts, outboxes, large caches; usually through a wrapper such as Dexie or idb |
| Cache Storage API | Stores Request and Response pairs; used by service workers | Offline app shell, cached API responses, images |
| Cookies | Sent with every request; about 4 KB | Session identifiers (HttpOnly, Secure, SameSite), not app data |
Storage is not guaranteed. Browsers evict data under storage pressure, and Safari deletes script-writable storage for sites the user hasn't interacted with for seven days of browser use (installed home-screen web apps are treated differently). navigator.storage.persist() can request durable storage. Design offline features to tolerate eviction, with the server as the source of truth.
Never put access tokens in localStorage. Any XSS can read them. Prefer HttpOnly cookies with CSRF protection, or tokens kept only in memory (Security Fundamentals for System Design).
Service workers: a programmable proxy in the browser. A service worker is a script that runs separately from your page, in its own thread with no DOM access. It can intercept every network request the page makes, from its scope. It's what makes offline web apps and installable progressive web apps (PWAs) possible. Twitter Lite, launched in 2017, is a well-known early example. Service workers require HTTPS.
The lifecycle is where most bugs live:
- Register. The page calls
navigator.serviceWorker.register('/sw.js'). - Install. The worker precaches the app shell: the HTML shell, core JS and CSS, fonts and an offline page.
- Activate. The worker deletes caches from older versions and takes control of pages.
- Fetch. It intercepts requests and answers each with a strategy.
- Update.
- When
sw.jschanges, the new worker installs in the background but waits until every tab using the old one is closed. Otherwise two versions of your app would share caches. - You can skip waiting and claim open pages immediately, but then open pages run old code against new caches. The common approach is a "New version available, reload" prompt.
- A broken service worker can pin users to a bad version, so always ship a kill switch: a no-op worker that clears caches and unregisters.
- When
Caching strategies per request type, usually implemented with Google's Workbox library:
Offline-first writes.
- Write locally first. Write the user's action to an IndexedDB outbox with a client-generated ID, and show it in the UI right away as pending.
- Sync later. When connectivity returns, replay the outbox in order with idempotency keys, so a retried "send message" never posts twice. The Background Sync API helps in Chromium browsers. Elsewhere, retry on the
onlineevent or on the next app launch. - Resolve conflicts. If the server state changed meanwhile, decide the policy: last-writer-wins for simple fields, server-wins with a "your change couldn't be applied" message, or merge (CRDTs for collaborative documents).
- Show sync status honestly: "Saved", "Saving…", "Offline, will sync" and "Sync failed, retry".
The same pattern appears in mobile apps. Strava, for example, records a run on the device while offline and uploads it later (Mobile System Design).
What not to cache on the client:
- Authorisation-sensitive data on shared devices. Clear caches on logout.
- Anything that must be strongly consistent, such as stock levels at checkout or account balances.
- Large media you can't bound. Set maximum entries and sizes, or you'll exhaust the quota and lose everything.
Cache invalidation on the client is harder than on the server because you can't reach the cache. Rely on versioned URLs, short TTLs and revalidation, and let the server be the arbiter.
Performance budgets and Core Web Vitals#
Performance work needs targets, or it becomes an endless list of micro-optimisations. Two tools provide them: Core Web Vitals define what to measure from the user's point of view, and performance budgets turn those targets into limits your build and CI enforce.
Core Web Vitals. These are Google's three user-centric metrics. Each is judged at the 75th percentile of real page loads, separately for mobile and desktop.
| Metric | Measures | Good | Poor |
|---|---|---|---|
| LCP (Largest Contentful Paint) | Loading: when the largest image or text block in the viewport is rendered | ≤ 2.5 s | > 4 s |
| INP (Interaction to Next Paint) | Responsiveness: the latency from a tap, click or key press to the next frame being painted; roughly the worst interaction over the visit | ≤ 200 ms | > 500 ms |
| CLS (Cumulative Layout Shift) | Visual stability: how much visible content unexpectedly moves | ≤ 0.1 | > 0.25 |
INP replaced the older First Input Delay (FID) as a Core Web Vital in March 2024. FID measured only the delay before the first interaction's handler started. INP measures the full latency of interactions throughout the visit, which is a much harder bar.
Supporting metrics:
- TTFB (time to first byte). Good is about 0.8 s or less. It reflects server, CDN and network time.
- FCP (first contentful paint). Good is about 1.8 s or less.
- TBT (total blocking time). A lab proxy for INP: the sum of the main-thread "long task" time beyond 50 ms per task.
What each metric breaks down into. This tells you what to fix:
- LCP = TTFB + resource load delay + resource load duration + element render delay.
- A slow server means a high TTFB.
- An LCP image discovered late (set from JavaScript, or lazy-loaded by mistake) means high load delay.
- A large unoptimised image means a long load duration.
- Render-blocking CSS and JavaScript, or a CSR app that renders after fetching, means high render delay.
- INP = input delay + processing time + presentation delay.
- Input delay comes from the main thread being busy with other work, such as hydration, third-party scripts or a long task.
- Processing time is your event handlers.
- Presentation delay is rendering and layout after the handler, with large DOMs and expensive style recalculation making it worse.
- The rule of thumb: keep every main-thread task under 50 ms, and yield to the browser between chunks of work so input can be handled.
- CLS causes:
- images and videos without width and height (or
aspect-ratio); - ads and embeds that load late without reserved space;
- web fonts swapping and changing text size;
- banners injected above existing content;
- new feed items inserted at the top while the user is reading.
- images and videos without width and height (or
Lab versus field data. You need both, because lab data is reproducible but synthetic, and field data is real but noisy.
- Lab tools run a page in a controlled environment: Lighthouse, WebPageTest, Chrome DevTools. Lighthouse's mobile preset simulates a slow 4G link (about 150 ms RTT and 1.6 Mbps) on a CPU throttled 4×. Use lab tools in CI and for debugging.
- Field data comes from real users. That's RUM (real user monitoring) with the
web-vitalslibrary in your own telemetry, or Google's Chrome UX Report (CrUX). Field data decides whether you meet the Core Web Vitals, and it reveals what lab tests miss: slow devices, poor networks, long sessions, real interactions.
Performance budgets. These are explicit limits, checked automatically:
- Metric budgets. "p75 LCP ≤ 2.5 s on mobile; p75 INP ≤ 200 ms", tracked from RUM per page type.
- Quantity budgets. For example:
- critical-path JavaScript ≤ 170 KB compressed;
- total page weight ≤ 1 MB;
- LCP image ≤ 150 KB;
- at most 2 web-font files;
- at most 3 third-party origins.
- Timing budgets in CI. For example, Lighthouse CI asserting a TBT of 200 ms or less on the key pages.
- Enforcement.
- Tools like
size-limitor bundle-size checks fail a pull request that adds 30 KB to the main bundle. - Lighthouse CI fails a pull request that regresses LCP in the lab.
- The PR description must justify any budget increase.
- Tools like
Worked example: why JavaScript budgets matter. On the slow 4G profile (1.6 Mbps, about 200 KB/s):
critical JS 400 KB compressed → download ≈ 2.0 s (+ ~150 ms RTT per extra round trip)
same JS decompressed ≈ 1.4 MB → parse + compile + execute on a mid-range phone ≈ 1–2 s
CSR: LCP waits for both, plus an API round trip → LCP ≈ 4–5 s (poor)
cut critical JS to 150 KB, SSR the HTML, preload hero image → LCP ≈ 2 s (good)Bytes of JavaScript are the most expensive bytes on the web. They must be downloaded, decompressed, parsed, compiled and executed on the main thread, while an image of the same size only needs decoding, usually off the main thread.
Bundle splitting and lazy loading#
The goal: ship only the code needed for what the user is doing now, and fetch the rest just in time.
Splitting techniques:
- Route-based splitting. Each route gets its own chunk, so
/settingscode never loads on/feed. Frameworks like Next.js do this automatically. It's the highest-value, lowest-effort split. - Component-level splitting. Heavy, rarely used components are loaded on demand with dynamic
import()(React.lazyplus Suspense in React): a rich-text editor, a chart library, a video player, a date picker, a modal behind a button.- Trigger the load on intent, such as hover or focus of the button, to hide the latency.
- Show a skeleton while loading.
- Vendor and shared chunks. Third-party libraries change less often than app code, so put them in separate long-cached chunks. Modern bundlers use granular chunking: modules shared by several routes go into shared chunks, without one giant vendor file that every page downloads.
- Tree shaking. Bundlers remove unused exports from ES modules. It only works when libraries ship ES modules and mark themselves side-effect-free. Import specific functions, not whole utility libraries.
- Watch the dependency graph. A date library with every locale, or a full icon set, can add hundreds of kilobytes by accident. Bundle analysers such as webpack-bundle-analyzer and source-map-explorer make this visible, so review them on every major dependency change.
- Don't over-split. HTTP/2 and HTTP/3 make many small requests cheap, but hundreds of tiny chunks still cost request overhead and hurt compression ratios. Aim for a modest number of meaningful chunks.
Lazy loading beyond code:
- Images and iframes below the fold. Use
loading="lazy", but never on the LCP image. Give the hero imagefetchpriority="high"and, if it's discovered late, apreloadhint. - Responsive images.
srcsetandsizeslet a phone download a 400-pixel image instead of a 2,000-pixel one. Use modern formats (AVIF, WebP) via an image CDN that resizes on the fly. - Fonts.
- Subset them to the characters you use and self-host them.
- Preload the one or two critical files.
- Use
font-display: swaporoptional, with size-adjusted fallbacks to avoid layout shift.
- Third-party scripts (analytics, chat widgets, ads).
- Load with
deferor after the page is interactive, and audit their cost regularly. - They're often the largest contributor to poor INP, and you don't control their code.
- Consider moving them to a web worker, or loading them only on pages that need them.
- Load with
- Off-screen work. Defer non-urgent work until the browser is idle (
requestIdleCallback). Usecontent-visibility: autoto skip rendering of off-screen sections.
Resource hints:
preconnectto critical third-party origins (DNS, TCP and TLS ahead of time);preloadfor critical late-discovered resources (the hero image, a critical font);modulepreloadfor JavaScript modules needed soon;prefetchfor likely next-navigation resources, at low priority.
Each hint competes for bandwidth, so preload only what's on the critical path.
Component architecture and design systems#
A large frontend is a tree of components: self-contained units of markup, style and behaviour. Good component architecture keeps that tree understandable as it grows to thousands of components and hundreds of contributors.
Principles that scale:
- Separate presentation from data.
- Presentational components (Button, Avatar, PostCard) take props and render. They have no data fetching and no knowledge of APIs, which makes them reusable and testable in isolation.
- Container or feature components (FeedContainer) fetch data, handle state and compose presentational components.
- Hooks such as
useFeed()capture data logic, so you don't need wrapper components for it.
- Prefer composition over configuration. A
Cardthat accepts children (header, body, actions) beats aCardwith 40 boolean props for every variant. Compound components (Tabs,Tabs.List,Tabs.Panel) share implicit state while leaving layout to the caller. - Colocate. Keep a component's styles, tests, stories and data requirements (a GraphQL fragment, say) next to it, and organise by feature (
feed/,search/,profile/) rather than by file type (components/,reducers/). Ownership then follows folders. - Keep boundaries explicit. Features import from the design system and shared utilities, but not from each other's internals. Lint rules or monorepo tooling such as Nx project boundaries enforce this.
- Use a layered model. Atomic Design (Brad Frost) names the layers: atoms (button, input), molecules (search field), organisms (header), templates and pages. The vocabulary helps teams agree on where a component belongs.
Design systems. A design system is the shared product of design and engineering: principles, design tokens, a component library, patterns and documentation. It's what makes 50 teams' screens look and behave like one product. Well-known public examples include Google's Material Design, Shopify's Polaris, IBM's Carbon and Atlassian's design system.
What a design system provides:
- Design tokens. Named values (
color.text.primary,space.4,radius.md) stored once (as JSON) and compiled to CSS variables, platform constants and design-tool styles. Changing a token changes the product everywhere, which is how theming and rebranding stay tractable. - Accessible, headless behaviour. The hard parts of a menu, dialog, combobox or date picker are focus management, keyboard support and ARIA. Headless libraries (Radix UI, React Aria, Headless UI, Ariakit) implement that behaviour once, without styling, and the design system skins it. That's the single most effective way to make a large product accessible.
- Documentation and a playground. Storybook (or similar) shows every component state, with usage guidance and do's and don'ts.
- Quality gates:
- visual regression tests (Chromatic or Playwright screenshots), which catch unintended style changes;
- automated accessibility checks (axe);
- interaction tests.
- Versioning and distribution.
- Publish as a versioned package with semantic versioning and changelogs, plus codemods for breaking changes.
- Decide between one version everywhere, which is easy in a monorepo and keeps consistency, and independent versions per app, which gives teams autonomy at the cost of visual drift and duplicate bundles.
- The design-system team runs like a product team, with consumers, roadmaps, support and adoption metrics.
Styling at scale.
- The main approaches: CSS Modules, utility-first CSS (Tailwind, which this handbook uses) and zero-runtime CSS-in-JS (vanilla-extract, compiled styles). All avoid global-name collisions and work well with server rendering.
- Runtime CSS-in-JS (styled-components, Emotion) adds JavaScript work during render and complicates streaming SSR and server components. Many teams have moved away from it for performance-critical apps.
Micro-frontends#
Micro-frontends apply the microservices idea to the frontend. A page or app is split into independently developed, tested and deployed pieces, each owned end to end by one team. The term spread from ThoughtWorks' Technology Radar around 2016. In its usual definition, each team owns a business capability across UI, BFF and services: checkout, search, recommendations.
Integration approaches:
| Approach | How | Pros | Cons |
|---|---|---|---|
| Build-time packages | Each micro-frontend is an npm package composed into one app at build time | Simple; one optimised bundle; type safety | Not independently deployable: every change needs a host release |
| Server-side composition | A layout service stitches HTML fragments from team services, via edge-side includes (ESI) or a composition server | Fast first paint; SEO-friendly; teams deploy independently | Shared client state and hydration across fragments are hard |
| Runtime JS composition (Module Federation, single-spa, import maps) | A host shell loads remote bundles at runtime and mounts them by route or slot | True independent deploys; shared dependencies loaded once | Runtime version conflicts; harder debugging; risk of duplicate frameworks |
| iframes | Each piece runs in its own iframe | Strong isolation (CSS, JS, security) | Poor performance, awkward resizing and focus, accessibility and deep-linking problems |
| Web Components | Each team ships custom elements with Shadow DOM | Framework-agnostic; style encapsulation | SSR and accessibility friction; cross-component events must be designed |
Webpack 5's Module Federation (2020) made runtime composition practical. A host declares "remotes", and the remotes expose modules. Shared libraries such as React are negotiated so they load once, provided the versions are compatible. Zalando's Project Mosaic is a well-known server-side composition example: it assembled pages from fragments owned by different teams.
What a micro-frontend architecture must define:
- A thin shell that owns routing, authentication, the global layout, the design system version and telemetry.
- Contracts between pieces. Use URL parameters, custom DOM events or a small typed event bus, not a shared global store that couples the teams again.
- A dependency policy. Ideally one framework and one major version, shared singletons for React and the design system, and budget checks so each micro-frontend's bundle cost is visible.
- Independent CI/CD with contract tests and the ability to roll back one piece without the others (CI/CD and Deployment Strategies).
- Consistent cross-cutting behaviour: error boundaries per piece (so one failing widget doesn't blank the page), shared observability tags per team, and shared accessibility standards.
When they're worth it. Micro-frontends solve an organisational problem: dozens of teams blocked on one release train, or a legacy app being migrated piece by piece (the strangler-fig pattern). Below roughly 5–10 teams on one surface, they usually cost more than they save: duplicate dependencies, inconsistent UX, slower pages and complex debugging. A well-structured modular monolith in a monorepo, with enforced feature boundaries and one deploy, gives most of the benefits. The same reasoning applies on the backend (Monolith vs Microservices).
Accessibility#
Accessibility (a11y) means people with disabilities can perceive, understand, navigate and operate the product. That includes blind users with screen readers, low-vision users who zoom to 200–400%, users who navigate only by keyboard or switch device, deaf users, and people with cognitive or motor impairments. The World Health Organization estimates about 1.3 billion people, roughly 1 in 6, live with a significant disability. Many more have temporary or situational limits: a broken arm, bright sunlight, a baby in one arm.
Accessibility is also a legal requirement in many markets. The US ADA has driven lawsuits over inaccessible websites, and the European Accessibility Act has applied to many consumer digital products since June 2025. Teams should treat it as a system quality like security, not a final-sprint polish item.
The standard: WCAG. The Web Content Accessibility Guidelines (WCAG 2.2, published 2023) organise requirements under four principles, POUR:
- Perceivable. Text alternatives for images, captions for video, sufficient colour contrast, and information not conveyed by colour alone.
- Operable. Everything works with a keyboard, focus is visible, there are no keyboard traps, users have enough time, and nothing flashes dangerously.
- Understandable. Clear labels and errors, predictable behaviour, and the page language declared.
- Robust. Valid semantics that assistive technologies can parse, with the correct name, role and value for every control.
Requirements are graded A, AA and AAA, and AA is the usual target in law and procurement. Concrete AA numbers include:
- a contrast ratio of 4.5:1 for normal text, and 3:1 for large text and UI component boundaries;
- content that reflows without horizontal scrolling at 320 CSS pixels wide (about 400% zoom);
- pointer targets of at least 24 × 24 CSS pixels, new in WCAG 2.2.
Engineering practices that make accessibility scale:
- Semantic HTML first.
- A
buttonelement is focusable, activates on Enter and Space, and announces itself as a button. - A
divwith a click handler does none of that. - Use real headings (
h1–h6in order), landmarks (header,nav,main), lists, tables for tabular data, andlabelelements tied to inputs.
- A
- ARIA only to fill gaps. The first rule of ARIA is not to use it when a native element exists, because incorrect ARIA is worse than none. Use it for widgets HTML lacks (tabs, comboboxes, tree views), following the WAI-ARIA Authoring Practices patterns for roles, states and keyboard behaviour.
- Keyboard and focus management.
- Every interaction must work with Tab, Shift+Tab, Enter, Space, Escape and the arrow keys where the pattern calls for them.
- When a dialog opens, move focus into it, trap focus inside, and return focus to the trigger on close.
- On client-side route changes, move focus to the new page's heading or announce the change. SPAs otherwise leave screen-reader users on a page that silently changed.
- Provide a "skip to content" link.
- Announce dynamic content. Use
aria-liveregions for updates that happen without a page load:- "12 results available" in an autocomplete;
- "New posts available" in a feed;
- form errors;
- toasts. Use polite announcements for most updates and assertive ones only for urgent errors.
- Respect user preferences. Honour
prefers-reduced-motion(no parallax or auto-playing animation),prefers-color-schemewhere supported, user font sizes (rem units, layouts that tolerate 200% text) and forced-colours modes. - Media. Alt text that conveys purpose (decorative images get empty alt text), captions and transcripts, and no auto-playing audio.
- Build it into the system.
- Accessible behaviour lives in the design system's headless components, so feature teams get it by default.
- Linting (eslint-plugin-jsx-a11y) and automated checks (axe in unit, Storybook and end-to-end tests) catch the roughly one-third of issues machines can detect.
- Manual testing with a keyboard and real screen readers (VoiceOver, NVDA, JAWS, TalkBack) catches the rest. Recruit users with disabilities for research where possible.
The WebAIM Million survey, an automated scan of the top million home pages, consistently finds detectable WCAG failures on well over 90% of them. Low contrast, missing alt text, empty links and unlabelled form inputs top the list. These are cheap to fix and easy to prevent with a design system and CI checks.
Frontend observability#
Backend dashboards can be green while users suffer. Telemetry has to come from the browser, because many problems only exist there:
- a CDN edge serving stale HTML;
- a third-party script blocking the main thread;
- a JavaScript error in one browser version;
- a slow Android device;
- an API that's fast from the data centre but slow from India.
What to collect:
| Signal | How | Use |
|---|---|---|
| Core Web Vitals and timings | The web-vitals library (with attribution builds), Navigation and Resource Timing, Long Animation Frames | p75 LCP, INP and CLS per route, device and country; find the element or script responsible |
| JavaScript errors | window.onerror, unhandledrejection, framework error boundaries; tools like Sentry | Error rate per release, stack traces de-minified with source maps |
| API calls from the client | Wrap fetch: latency, status, size, retries | Client-observed API latency, including mobile network time the backend can't see |
| Distributed traces | Send the W3C traceparent header from the browser (OpenTelemetry web SDK) | Follow one slow click from browser to BFF to services (Observability: Logs, Metrics and Traces) |
| Product and UX events | Custom events: search submitted, post liked, checkout step | Funnels, feature adoption, correlation with performance |
| Session replay (sampled) | Record DOM changes, not video | Reproduce confusing bugs, with masking of all inputs and PII by default |
| Synthetic monitoring | Scripted Lighthouse or Playwright runs from several regions | Catch regressions before users do; a baseline unaffected by user mix |
Design rules for the telemetry pipeline:
- Tag every event with release version, route, device class, browser, effective connection type, country, and the feature flags or experiments active. Most investigations come down to "which slice got worse?".
- Send reliably without hurting performance.
- Batch events.
- Flush on
visibilitychange(page hidden) withnavigator.sendBeaconorfetchwithkeepalive.unloadis unreliable on mobile and breaks the bfcache. - Never block rendering or interaction on telemetry.
- Sample deliberately.
- Keep all errors (deduplicated by fingerprint).
- Sample performance beacons (10% of sessions is plenty at scale).
- Keep session replay very sparse, or trigger it on error.
- Use first-party endpoints. Ad and tracking blockers drop requests to well-known analytics domains, which skews data, so route telemetry through your own domain where policy allows. Respect consent requirements (GDPR and ePrivacy cookie consent) for anything beyond strictly necessary telemetry.
- Upload source maps privately to the error tracker at build time. Don't serve them publicly unless you're happy to expose source.
- Alert on symptoms by release. Examples:
- "Error rate for release 2026.12.03 is 3× the previous release."
- "p75 INP on /feed rose 40 ms since this morning's deploy." Tie alerts to automatic rollback or feature-flag kill switches.
- Watch percentiles, not averages. p75 matches Core Web Vitals, and p95 or p99 find the users with the worst experience.
Designing a news feed UI end to end#
Frontend design interviews usually follow a structure like the widely used RADIO framework: Requirements, Architecture, Data model, Interface (API), Optimisations. It mirrors the backend flow in The System Design Interview Framework, but asks client-side questions. Here it's applied to a Facebook- or Twitter-style feed.
Requirements.
- Functional:
- show a reverse-chronological (or ranked) feed of posts from followed accounts;
- infinite scroll;
- create a post;
- like and comment;
- images and video in posts;
- a "new posts" indicator.
- Non-functional:
- fast first load (p75 LCP ≤ 2.5 s on mobile);
- smooth scrolling at 60 frames per second;
- interactions under 200 ms INP;
- works on low-end phones;
- accessible;
- tolerates flaky networks.
- Consistency. About a minute of staleness is acceptable for a feed. That allows caching and background refresh, matching a backend that is itself eventually consistent.
Architecture.
Data model on the client. Normalise:
postskeyed by post ID;userskeyed by user ID;- the feed as an ordered list of post IDs per page, plus
nextCursor.
A like updated on posts[123] then shows everywhere that post appears, in the feed, the detail view and a profile. Each post carries media width and height from the API, so the layout reserves space before images load, giving zero CLS.
Interface (API).
GET /feed?cursor=…&limit=20returnsitemsandnextCursor. The cursor encodes the position of the oldest item seen. For a reverse-chronological feed that can be a timestamp plus post ID as a tie-breaker. For a ranked feed it's an opaque server-side token.POST /postscarries a client-generated ID, so retries are idempotent.PUT /posts/{id}/likeandDELETE /posts/{id}/likeare naturally idempotent, so a double-click doesn't double-count.- An SSE stream or a light poll every 30–60 s returns the count of new posts, not the posts themselves.
On the backend, the server typically serves the first pages from a precomputed feed of the most recent few hundred post IDs per user. Readers rarely scroll beyond that, and deep pages can fall back to slower queries. The full backend story is in Design a News Feed (Facebook / Twitter).
Optimisations, the part that decides the interview:
- First load.
- SSR or stream the shell and the first page of posts (5–10), so the first post's text or image is the LCP element and appears without waiting for JavaScript.
- Preload the first image with high fetch priority.
- Hydrate the feed before secondary widgets.
- Embed the first page's data in the HTML, so the client cache starts warm and doesn't refetch.
- Infinite scroll.
- Put a sentinel element a screen or two above the end of the list, watched by an
IntersectionObserver. When it becomes visible, fetch the next page. - Only one page request may be in flight at a time.
- On failure, show an inline retry button instead of spinning forever.
- Provide a "load more" button as an accessible alternative, and don't trap keyboard users in endless content: footers and landmarks must stay reachable.
- Put a sentinel element a screen or two above the end of the list, watched by an
- Virtualisation (windowing).
- The problem. After 500 posts at roughly 150 DOM nodes each, the page holds 75,000 nodes. Memory, style recalculation and layout grow until scrolling janks and INP suffers.
- The fix. Render only the posts in and near the viewport, plus an overscan of a few items, and replace the rest with spacer height. Libraries include react-window, react-virtuoso and TanStack Virtual.
- Variable heights must be measured (ResizeObserver) and cached. Scroll anchoring must hold position when heights above the viewport change.
- Trade-off. Browser find-in-page and some screen-reader navigation only see rendered items. Mitigate with
aria-setsizeandaria-posinseton feed items (the ARIAfeedrole exists for exactly this), or by virtualising only beyond a threshold.
- New posts without layout shift.
- Never insert new posts above the user's reading position. Show a "5 new posts" pill. Tapping it scrolls to the top and inserts them.
- Announce the pill politely to screen readers.
- This avoids CLS and respects the user's place.
- Media.
- Lazy-load images and video below the fold, and use responsive
srcsetfrom an image CDN. - Show tiny blurred placeholders (BlurHash-style) inside reserved aspect-ratio boxes.
- Autoplay video only when muted, at least half visible, and allowed by
prefers-reduced-motion. Pause it when it scrolls out of view.
- Lazy-load images and video below the fold, and use responsive
- Interactions.
- Optimistic likes, with rollback on failure.
- Lazy-load comments on demand.
- Code-split the composer's rich editor and emoji picker, loading them when the composer gets focus.
- Keep handlers small, and defer analytics work to idle time so taps stay under 200 ms.
- Navigation. Keep the feed cache and restore scroll position when the user goes to a post and comes back, which is one of the most noticed details on mobile web. Supporting the bfcache helps.
- Offline and flaky networks. Show cached posts immediately with a "you're offline" banner. Queue new posts and likes in an outbox, with idempotent replay.
- Telemetry.
- Impressions. Count a post as seen when at least 50% of it is visible for at least one second. That mirrors the industry's display-ad viewability standard, and IntersectionObserver makes it cheap.
- Ranking feedback. Batch impressions and send them with a beacon. They feed the ranking system (Design a Recommendation System (Twitter For You)).
- Performance. Track LCP, INP and long animation frames per route.
- Accessibility.
- Each post is an
articlewith an accessible name (author and time). - Every action button has a label ("Like post by Ana, 12 likes").
- The like state is exposed with
aria-pressed. - Keyboard shortcuts (J and K to move between posts) are discoverable and can be turned off.
- Each post is an
Designing an autocomplete (typeahead) UI end to end#
Requirements.
- Suggestions appear as the user types, within about 100–200 ms of a pause.
- Keyboard and screen-reader support.
- Recent searches.
- Highlighted matches.
- Works on mobile.
- The backend must not be flooded with requests.
Key design decisions:
- Debounce input. Wait for a short pause (150–300 ms) before requesting. At 5 keystrokes per second, no debounce means 5 requests per second per user. A 200 ms debounce usually cuts that to 1–2 per typing burst. Throttling, sending at most one request per interval, suits cases where suggestions should update during continuous typing.
- Set a minimum query length of 1–2 characters, and trim and normalise case before using the query as a cache key.
- Cancel stale requests and ignore out-of-order responses. The response for "ap" can arrive after the one for "app" and overwrite the newer results. Abort superseded requests with
AbortController, and only apply responses whose query still matches the current input. - Cache on the client. An in-memory LRU map from normalised query to results makes backspacing and retyping instant, and an HTTP cache with a short max-age lets the CDN absorb popular prefixes. Prefetch suggestions for the empty and single-letter states.
- Server contract.
GET /suggest?q=app&limit=8returns the top suggestions in under 100 ms at the server. The backend is usually a prefix index (a trie with top-k per node, or a search engine's completion suggester) fed by query logs (Design Search Autocomplete (Typeahead)). - Rendering.
- Highlight the matched part.
- Render suggestion text as text, never as HTML, to avoid XSS from user-generated queries.
- Mix in recent searches, stored locally and capped at about 10, and allow users to remove them.
- Input edge cases.
- Ignore input events during IME composition (Chinese, Japanese and Korean input) until composition ends.
- Handle paste.
- Avoid fighting the mobile keyboard. Use
inputmodeandenterkeyhint, and don't steal focus.
- Accessibility: the ARIA combobox pattern.
- The input has
role="combobox",aria-expanded,aria-controls(pointing at the listbox) andaria-autocomplete="list". - Suggestions are in a
listboxofoptionelements. - Arrow keys move the active descendant (
aria-activedescendant) while focus stays in the input. Enter selects, Escape closes. - A polite live region announces "8 suggestions available".
- The input has
When to Use It#
Treat the frontend as a system to design, not a view to decorate, when:
- First impressions drive the business. Landing, product, search and article pages, where LCP and SEO affect conversion and acquisition. Design the rendering strategy and budgets up front.
- The app is large and long-lived:
- more than about 100,000 lines of frontend code;
- several teams;
- years of expected life. Component boundaries, a design system and ownership rules prevent it from turning into an unmaintainable ball of shared state.
- Users are on mobile networks and mid-range devices. This is most consumer products globally. JavaScript budgets and splitting decide whether the product is usable.
- Data is rich and interactive: feeds, dashboards, editors, chat. State management, caching, optimistic updates and real-time sync become core design topics.
- Offline or poor connectivity is part of the use case. Field workers, travel and emerging markets call for service workers, IndexedDB and outbox sync.
- Regulation or procurement requires accessibility, as in the public sector, finance, education and anything sold into the EU under the European Accessibility Act.
- You're in a frontend system design interview. Use the structure on this page: requirements, architecture, data model, API, then optimisations across performance, accessibility, offline and observability.
When NOT to Use It#
Pick something else instead when:
- It's a small internal tool with a handful of users. A server-rendered app (Rails, Django, Laravel) with a sprinkle of JavaScript, or a low-code tool, is faster to build and maintain than an SPA with a state library and micro-frontends.
- The content is mostly static. Use a static site generator or islands framework, not a client-rendered SPA that ships megabytes of JavaScript to show text.
- There are fewer than 5–10 teams on one surface. Skip micro-frontends. A modular monolith with enforced boundaries delivers independence without runtime composition costs.
- The product is pre-product-market-fit. Don't build a bespoke design system or an elaborate offline architecture before you know users want the product. Adopt an existing component library (Material UI, Radix with Tailwind, Chakra) and revisit later.
- You're tempted to add a global store "for scalability". Use a query cache for server state and the URL for shareable state first. Most apps then need little else.
- You'd cache data that must be strongly consistent (balances, inventory at checkout, permissions) on the client. Fetch it fresh, and let the server decide.
How to Implement It#
- Write down requirements and budgets.
- Who are the users (devices, networks, countries, assistive tech)?
- Which pages matter most?
- Set targets: p75 LCP ≤ 2.5 s, INP ≤ 200 ms and CLS ≤ 0.1 on mobile, a critical-JS budget, and WCAG 2.2 AA.
- Choose a rendering strategy per route type.
- SSG or ISR for content and catalogues;
- streaming SSR for personalised, SEO-relevant pages;
- CSR for authenticated app-like areas;
- islands or server components to minimise JavaScript on content pages. Pick a framework that supports this mix (Next.js, Remix or React Router, Nuxt, SvelteKit, Astro).
- Design the data layer.
- Server state goes in a query cache (TanStack Query, SWR, Apollo or Relay), with keys, stale times and invalidation rules.
- Shareable state goes in the URL.
- Use cursor pagination, a BFF or GraphQL to avoid waterfalls, optimistic updates for low-risk mutations, and idempotency keys.
- Pick a real-time transport where needed.
- Set up caching and offline.
- Hashed assets with a one-year
immutablecache; HTML revalidated on every load. - A CDN, and an image CDN.
- If offline matters: a service worker with Workbox strategies, an IndexedDB outbox, an update prompt and a kill switch.
- Hashed assets with a one-year
- Build the component architecture.
- Use design tokens and a headless, accessible component library.
- Organise folders by feature, with lint-enforced boundaries.
- Keep Storybook, visual regression and axe checks in CI.
- Consider micro-frontends only when team count and release coupling justify them.
- Enforce performance in CI.
- Route and component splitting, plus a bundle-size check per pull request.
- Lighthouse CI on key pages.
- Reviews of third-party scripts.
- Image and font policies.
- Instrument from day one. RUM with Web Vitals and attribution, error tracking with private source maps,
traceparentpropagation, release and flag tags, and alerts on per-release regressions wired to rollback or flag kill switches.
Snippet: an autocomplete hook with debounce, cancellation, stale-response protection and an LRU cache.
import { useEffect, useRef, useState } from "react";
const cache = new Map<string, string[]>(); // insertion order gives cheap LRU
const MAX = 100;
export function useSuggestions(input: string, delayMs = 200) {
const [items, setItems] = useState<string[]>([]);
const latest = useRef("");
useEffect(() => {
const q = input.trim().toLowerCase();
latest.current = q;
if (q.length < 2) { setItems([]); return; }
const hit = cache.get(q);
if (hit) { cache.delete(q); cache.set(q, hit); setItems(hit); return; } // refresh LRU order
const ctrl = new AbortController();
const timer = setTimeout(async () => {
try {
const res = await fetch(`/api/suggest?q=${encodeURIComponent(q)}&limit=8`, { signal: ctrl.signal });
if (!res.ok) return;
const data: string[] = await res.json();
cache.set(q, data);
if (cache.size > MAX) cache.delete(cache.keys().next().value as string); // evict oldest
if (latest.current === q) setItems(data); // ignore out-of-order responses
} catch (e) {
if ((e as Error).name !== "AbortError") setItems([]);
}
}, delayMs);
return () => { clearTimeout(timer); ctrl.abort(); }; // new keystroke cancels timer and request
}, [input, delayMs]);
return items;
}The cleanup function makes each keystroke cancel both the pending debounce timer and any in-flight request. The latest ref is a second guard against responses that arrive late. Rendering, highlighting and the ARIA combobox behaviour belong in a separate presentational component, ideally the design system's headless combobox.
| Technology | Fits when |
|---|---|
| Next.js (App Router, RSC), Remix or React Router, Nuxt, SvelteKit | You need per-route SSR, SSG, ISR and streaming in one framework |
| Astro, Eleventy | Content-heavy sites; islands architecture with minimal JavaScript |
| Vite, webpack 5 (Module Federation), Rspack, Turbopack, esbuild | Bundling and splitting; webpack or Rspack Module Federation for runtime micro-frontends |
| TanStack Query, SWR, RTK Query | Server-state caching for REST and RPC APIs |
| Apollo Client, Relay, urql | GraphQL with normalised caches; Relay for fragment colocation at large scale |
| Zustand, Redux Toolkit, signals (Preact, Solid, Angular) | Small amounts of genuinely global client state |
| Workbox, Dexie (IndexedDB) | Service-worker caching strategies; structured offline storage and outboxes |
| Radix UI, React Aria, Headless UI, Ariakit | Accessible headless primitives for a design system |
| Storybook, Chromatic, Playwright, axe-core | Component docs, visual regression, end-to-end and accessibility tests |
| Lighthouse CI, WebPageTest, size-limit | Lab performance and bundle budgets in CI |
| web-vitals, Sentry, Datadog RUM, OpenTelemetry web SDK | Field Web Vitals, error tracking with source maps, browser-to-backend tracing |
| Image CDNs (Cloudinary, imgix, Cloudflare Images, Next.js Image) | Responsive resizing, AVIF and WebP conversion, lazy loading |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| CSR (SPA) | Simple static hosting; app-like navigation; clean API boundary | Slow first load; weak SEO; large JS hurts INP | Authenticated, long-session apps (dashboards, editors) |
| SSR (streaming) | Fast first paint; SEO; personalised HTML; progressive loading | Rendering servers to run; hydration cost; error handling after first flush | Personalised or fast-changing pages that must load fast |
| SSG or ISR | CDN-speed; cheap; resilient | Staleness; build-time growth; no per-user HTML | Content, docs, catalogues |
| Islands or server components | Minimal JS; excellent INP | Harder cross-island state; newer tooling | Content-heavy pages with small interactive parts |
| Document query cache | Simple, predictable keys | Same entity duplicated across responses; manual invalidation | REST APIs, most apps |
| Normalised cache | One update shows everywhere | Complexity; needs IDs and a schema | Data-dense GraphQL apps |
| Optimistic updates | Instant-feeling UI | Rollback UX; wrong for high-stakes actions | Likes, follows, reordering, read state |
| Service worker offline | Works offline; instant repeat loads | Lifecycle and update bugs; stale-version risk; testing burden | PWAs, flaky-network users, field apps |
| Virtualised lists | Constant DOM size; smooth scroll | Find-in-page and assistive-tech caveats; height measurement complexity | Feeds and tables beyond a few hundred rows |
| Shared design system | Consistency; accessibility by default; speed | Central team cost; versioning and adoption work | Many teams and screens; long-lived products |
| Micro-frontends | Independent deploys and ownership | Duplicate dependencies; inconsistent UX; runtime complexity | Many teams blocked on one release train; incremental migrations |
Common Pitfalls#
- Shipping an SPA for content. A marketing or article page that needs 600 KB of JavaScript to show text. Use SSG, SSR or islands.
- Lazy-loading the LCP image, or injecting it from JavaScript, so the browser discovers it late. Mark it high priority and render it in the HTML.
- Request waterfalls from nested components each fetching their own data. Fetch at the route level, in parallel, or aggregate on the server.
- Copying server data into a global store, then re-implementing caching, deduplication and invalidation by hand. Use a query cache.
- Caching HTML for a long time, which strands users on old releases and points them at deleted assets. Revalidate HTML, and cache only hashed assets for long periods.
- Service worker without a kill switch. A buggy worker can pin users to a broken version until they clear site data.
- Tokens in localStorage, readable by any XSS. Use HttpOnly cookies or in-memory tokens.
- Ignoring INP. Big hydration bursts, heavy third-party scripts and long event handlers make taps feel broken even after a fast load. Break up long tasks, and defer non-critical work.
- Layout shift from late content: images without dimensions, ads without reserved slots, posts inserted above the reader.
- Unbounded DOM in infinite lists. Thousands of rendered posts on a phone. Virtualise.
- Out-of-order responses in autocomplete, where old results overwrite new ones. Abort stale requests, and check the current query before applying results.
divbuttons and missing labels. Inaccessible controls, keyboard traps in dialogs, and SPA route changes that screen readers never hear about.- Micro-frontends too early. Paying for runtime composition, duplicated React copies and inconsistent design for a three-team product.
- Measuring only in the lab. A green Lighthouse score on a developer laptop while p75 field INP on Android is poor. Use RUM.
Real-World Examples#
- Facebook BigPipe (2010). Facebook split pages into independently rendered "pagelets" and flushed them over one HTTP response as each was ready. That's the ancestor of today's streaming SSR with Suspense.
- Facebook, React, GraphQL and Relay. React (open-sourced 2013), GraphQL (open-sourced 2015) and Relay came out of Facebook's need to build data-dense UIs with many teams. Relay's colocated fragments compose one query per screen to avoid waterfalls. Facebook's 2020 rebuild of facebook.com described how the team used React, Relay, data-driven code splitting and atomic CSS to shrink what each page downloads.
- Airbnb Hypernova (2016). Airbnb open-sourced Hypernova, a service for server-rendering React components so pages could paint before JavaScript loaded. It's an early example of SSR as a separate tier.
- Twitter Lite (2017). A progressive web app using a service worker for caching and offline support, aimed at users on slow and expensive mobile networks.
- Etsy and Astro: islands. The "component islands" idea came from Etsy's frontend architecture work and became the core of Astro, which ships zero JavaScript by default for non-interactive parts.
- GitHub. GitHub removed jQuery from github.com in 2018, moving to standard browser APIs and web components. It's a well-known example of server-rendered HTML with progressive enhancement at large scale.
- Figma. Figma runs its rendering engine, written in C++, in the browser via WebAssembly, drawing to a canvas. That's the far end of client-side architecture, where the frontend is effectively a desktop-class application.
- Design systems. Google's Material Design, Shopify's Polaris and IBM's Carbon are public design systems with tokens, accessible components and usage guidance, built to keep many teams' products consistent.
- Zalando Project Mosaic. Server-side composition of pages from fragments owned by different teams. It's one of the early large-scale micro-frontend architectures.
Case studies that use this pattern#
- Design a News Feed (Facebook / Twitter): the backend for the feed UI designed above, with fan-out, precomputed feeds and cursor pagination.
- Design Search Autocomplete (Typeahead): the trie and top-k backend behind the autocomplete UI.
- Design a Collaborative Editor (Google Docs): a client-side document model, OT or CRDT sync, and offline editing.
- Design a Chat System (WhatsApp): real-time transport, optimistic sends with client IDs, and offline outboxes.
- Design a Video Streaming Platform (YouTube / Netflix): adaptive streaming players, CDN delivery and client-side performance on many devices.
In the Interview#
Common follow-ups:
Q: SSR or CSR for this page? It depends on who loads it and what matters. Public, SEO-relevant or first-impression pages get SSR (streamed if data sources vary in speed) or SSG and ISR if the content is shared. Logged-in, app-like screens with long sessions can be CSR. I'd mix per route, and use server components or islands to keep JavaScript small where interactivity is limited.
Q: How do you keep the feed smooth after 1,000 posts? Virtualise the list so only visible items plus an overscan are in the DOM. Measure and cache variable heights, keep scroll anchoring, and release media for off-screen items. Paginate with cursors and a sentinel, keep only a bounded number of pages in memory, and refetch older pages if the user scrolls back far.
Q: The page is fast in Lighthouse but users complain. What do you do? Look at field data. Check RUM p75 by device, route, country and release, and use attribution to find the LCP element, the slow interactions behind INP and the shifting elements behind CLS. Common culprits are third-party scripts, hydration bursts, slow APIs seen from distant regions, and low-end devices. Fix those and verify in the field, not only in the lab.
Q: How would you make the app work offline? Add a service worker that precaches the app shell, uses cache-first for hashed assets, network-first with fallback for HTML, and stale-while-revalidate for semi-fresh data. Put data in IndexedDB and writes in an outbox with client IDs and idempotent replay. Define a conflict policy and show sync status clearly. Handle storage eviction and service-worker updates with a prompt and a kill switch.
Q: When would you use micro-frontends? When many teams (roughly 5–10 or more) ship to one surface and are blocked by a shared release, or when migrating a legacy app piece by piece. I'd use a thin shell, shared singletons for the framework and design system, explicit contracts between pieces, and per-piece CI/CD and error boundaries. Otherwise, a modular monolith with lint-enforced boundaries.
Q: How do you build the autocomplete so it doesn't hammer the backend or show wrong results? Debounce at about 200 ms, set a minimum query length, cache results client-side in an LRU keyed by normalised query, and use short CDN caching for popular prefixes. Abort superseded requests and apply only responses that match the current input. Implement the ARIA combobox pattern with a live region announcing the result count.
Q: How do you make a large product accessible, not just one page? Put accessibility into the platform: semantic HTML, a design system built on headless accessible primitives, tokens with compliant contrast, lint and axe checks in CI, focus management on route changes, and regular manual screen-reader testing. Track issues like bugs with severity and owners, and target WCAG 2.2 AA.
Deep Dive: The critical rendering path and the cost of hydrationShow
From bytes to pixels. When HTML arrives, the browser:
- Parses HTML into the DOM incrementally. A preload scanner looks ahead in the raw HTML and starts fetching images, scripts and stylesheets it discovers. That's why resources referenced directly in HTML load sooner than ones injected by JavaScript.
- Parses CSS into the CSSOM. CSS is render-blocking: the browser won't paint until the CSS it knows about has loaded, otherwise content would flash unstyled. Keep critical CSS small (inline it if it's tiny), and load non-critical CSS without blocking.
- Handles scripts.
- A classic
scripttag withoutdeferorasyncis parser-blocking. HTML parsing stops while it downloads and executes, because it might calldocument.write. deferscripts download in parallel and execute in order after parsing.asyncscripts execute as soon as they arrive.- Module scripts are deferred by default.
- A classic
- Renders. It builds the render tree (DOM plus styles), runs layout (geometry), paints layers and composites them on the GPU.
- Animating
transformandopacitytouches only compositing. - Animating
width,toporheightforces layout on every frame.
- Animating
Why LCP depends on discovery. If the hero image is in the HTML with high fetch priority, it starts downloading within the first round trip of the HTML. If a CSR app creates it after downloading and running a bundle and fetching data, it might not even be requested until 2–3 seconds in. Everything in "How It Works" about SSR, preload and avoiding lazy-loading the LCP image follows from this.
What hydration actually does. With SSR the HTML is already on screen, but it's inert. Hydration has to:
- download the component code for everything on the page;
- run every component again in the browser to rebuild the virtual tree and its state;
- walk the existing DOM, matching it against that tree and attaching event listeners.
The work is proportional to the number of components on the page, not just to the interactive ones. Suppose a page has 3,000 component instances, and hydrating each costs about 0.1 ms on a mid-range phone. That's a 300 ms block of main-thread work, during which taps queue up. That's the uncanny valley, and why SSR pages can have poor INP.
If the server's HTML and the client's first render differ, hydration finds a mismatch. Typical causes are dates rendered in different time zones, random IDs, and checks of window during render. React then patches or re-renders that subtree, which costs time and can flash content.
Ways to reduce hydration cost, from incremental to radical:
- Selective or progressive hydration. With streaming and Suspense boundaries, React hydrates sections independently and prioritises the one the user is interacting with. The total work is the same, but it's chunked and reordered, so input isn't blocked by one giant task.
- Islands and partial hydration. Only interactive components ship code and hydrate. Static content never re-runs, so the work is proportional to interactivity.
- Server components. Components marked server-only never ship code to the browser. Their output arrives as a serialised tree (the RSC payload) that the client merges in without hydrating it. Client components inside them hydrate normally.
- Resumability (Qwik). The server serialises the listeners and the state each one needs into the HTML. The browser hydrates nothing at load and fetches a handler's code only when that interaction happens. The trade-off is a small delay on first interaction while code loads, and a programming model that has to serialise closures.
The interview takeaway. "SSR makes it fast" is only half the story. SSR fixes LCP, but the hydration that follows can harm INP. A strong design says how the JavaScript that hydrates is kept small and chunked.
Deep Dive: The main thread, INP and scheduling workShow
The event loop in one paragraph. The browser runs JavaScript, style, layout and paint for a page on one main thread. It repeatedly takes a task from a queue (an event handler, a timer callback, a network callback, a parsing chunk) and runs it to completion. Then it drains microtasks (promise callbacks), and roughly every 16.7 ms on a 60 Hz display it may run a rendering step: animation-frame callbacks, style, layout, paint. A task can't be interrupted. If it runs for 300 ms, no input is handled and no frame is painted for 300 ms. Tasks over 50 ms are called long tasks, and they're the root cause of most poor INP.
INP arithmetic. A user taps "Like" while a 180 ms hydration task is running, 60 ms into it.
input delay = 180 − 60 = 120 ms (waiting for the running task to finish)
processing = 35 ms (click handler: state update + analytics call)
presentation delay = 45 ms (re-render 40 components, style, layout, paint)
INP for this tap ≈ 200 ms (right at the 'good' threshold)Each part has its own fixes:
- Input delay.
- Break long tasks into pieces under 50 ms and yield between them, with
scheduler.yield()where available, orsetTimeout(0)orMessageChannelas fallbacks. - Chunk hydration, and defer third-party scripts.
- Break long tasks into pieces under 50 ms and yield between them, with
- Processing time.
- Do the visible update first and defer everything else: analytics, logging and prefetching after the next paint, or at idle time.
- Avoid synchronous
localStorageand layout reads in handlers.
- Presentation delay.
- Re-render less: memoise, keep state local, and avoid putting fast-changing state at the top of the tree.
- Keep the DOM small (virtualisation), and avoid layout thrashing (interleaved reads and writes of geometry).
- Use
content-visibilityfor off-screen sections.
Concurrent rendering. React 18 can mark updates as non-urgent with startTransition. Rendering of, say, a filtered list happens in interruptible slices, and a newer keystroke can abandon an in-progress render. The input stays responsive and the list catches up. That's scheduling within one thread: it doesn't make work cheaper, it makes urgent work go first.
Moving work off the main thread. Web Workers run JavaScript in parallel threads without DOM access. They suit:
- parsing large JSON;
- search indexing (this handbook builds its search index at build time and queries it in the browser);
- image processing, diffing, cryptography;
- running third-party scripts via proxies.
The cost is message passing, because data is copied (structured clone) unless transferred.
Debounce and throttle, quantified. For a user typing in bursts of 6 characters at 5 characters per second, then pausing:
no limiting : 6 requests per burst
throttle 300 ms : about 4 requests per burst (one per 300 ms window while typing)
debounce 200 ms : 1 request per burst (fires 200 ms after the last key)
perceived latency : debounce adds the 200 ms wait + network ≈ 200 + 60 = 260 ms after the pauseDebounce minimises requests. Throttle gives steady updates during continuous input, which suits scroll-linked effects or live previews. Many autocompletes combine a short debounce with an instant result from the client cache.
Virtualisation sizing. With a viewport 800 px tall, items about 400 px tall and an overscan of 3 items each side:
rendered items ≈ ceil(800 / 400) + 1 + 2 × 3 = 9 items
DOM nodes ≈ 9 × 150 ≈ 1,350 instead of 150 × (all loaded posts)Rendering work stays constant however far the user scrolls. That's what keeps INP and memory flat on long sessions.
Deep Dive: Version skew, cache coherence and cross-tab consistencyShow
A frontend is a distributed client fleet. Millions of browser tabs run different versions of your code, each holding its own cache of server data. Three consistency problems follow.
1. Version skew between client and server. A user opens the app at 09:00 and leaves the tab open. At 11:00 you deploy release 42, which renames an API field and removes old chunks. The 09:00 tab, still on release 41, then:
- calls the API with the old field;
- lazily loads
settings.41ab.js, which no longer exists, and gets a 404 and a blank screen.
Mitigations:
- Keep APIs backward compatible across at least a couple of releases. Use additive changes, tolerant readers, and versioned endpoints for breaking changes (API Design Best Practices). A BFF owned by the frontend team can absorb some skew.
- Keep old asset versions available for days after a deploy. Some platforms offer "skew protection" that routes a client's requests to the deployment it was loaded from.
- Detect staleness. The app compares its build ID against a lightweight version endpoint, or a header on API responses. When it's behind, it prompts a reload, or reloads automatically on the next navigation.
- Handle chunk-load failures. Catch failed dynamic imports and reload the page once, guarded against loops.
- Mind the service worker. It can pin a whole tab to an old release, so the update flow must cooperate with this detection.
2. Cache coherence after mutations. The client holds cached copies of server data, so every mutation must say which cached entries it invalidates. There are four common strategies, from simple to precise:
- Invalidate by key prefix after a mutation, for example everything under
["feed"]after creating a post. It's simple, at the cost of extra refetches. - Update in place from the mutation's response, where the server returns the updated entity and the client writes it into the cache. It's precise and saves a round trip.
- Normalised entity updates, where one write to
Post:123updates every view. Relay and Apollo use this. - Server-pushed invalidation over a real-time channel: "post 123 changed" becomes an invalidation or patch event. This is needed when other users' actions should appear promptly.
Choose freshness per data type, as on the server. A feed can be a minute stale. Notification counts should update within seconds via push. A checkout total must always be fetched fresh.
3. Consistency across tabs. Two tabs of the same app each have their own memory cache. If a user logs out in tab A, tab B must not keep showing private data. If they change a setting, both tabs should agree. Options:
- BroadcastChannel to publish "logged out", "invalidate key X" or "new version available" to every tab of the origin;
- the
storageevent on localStorage writes, which is the older approach; - a shared worker or the service worker as a coordination point;
- Web Locks to elect one tab as the leader that holds the single real-time connection and relays events to the others. That saves server connections, since some users keep 10 tabs open.
4. Offline replay and ordering. An outbox replayed after reconnecting must preserve causality: "create post" before "edit post". Each entry carries a client ID, so the server can deduplicate retries. When the server rejects an entry (it was deleted meanwhile, or permissions changed), the client must surface the conflict rather than drop it silently. For collaborative data, CRDTs make merges automatic. For business data, the server stays the arbiter, and the client presents the outcome.
These are the same problems as replicated databases (versioning, invalidation, replication lag, conflict resolution), just running on millions of devices you can't reach directly. Bring that framing to an interview and it signals senior-level understanding (Consistency Models).
Key Takeaways#
- The frontend is a distributed system running on devices and networks you don't control. Design it with explicit requirements: target devices, networks, SEO, accessibility and offline.
- Choose a rendering strategy per route. CSR suits apps, SSR (streamed) suits personalised pages, SSG or ISR suits content, and islands or server components keep JavaScript small. SSR fixes LCP, but hydration can hurt INP.
- Treat server state as a cache (query keys, stale-while-revalidate, deduplication, invalidation), put shareable state in the URL, keep global state small, and avoid request waterfalls with route-level fetching or a BFF.
- Cache in layers:
- hashed assets immutable for a year;
- HTML always revalidated;
- a CDN, plus an image CDN;
- service workers and IndexedDB outboxes for offline. Plan for eviction, updates and a kill switch.
- Budget performance with Core Web Vitals at p75: LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1. Enforce JavaScript and bundle budgets in CI, and verify with field RUM, not only lab scores.
- Split code by route and on interaction, lazy-load below-the-fold media, prioritise the LCP resource, and keep main-thread tasks under 50 ms.
- Scale the code base with feature-based components and a design system built on tokens and accessible headless primitives. Adopt micro-frontends only when team scale and release coupling justify them.
- Build accessibility (WCAG 2.2 AA) and observability into the platform: vitals, errors with source maps, traces, and release tags tied to rollback.
- For feeds and autocomplete, the interview-winning details are cursor pagination, virtualisation, a "new posts" pill instead of layout shift, optimistic idempotent actions, debounced and cancellable requests, out-of-order protection, and the ARIA combobox and feed patterns.