Practice
All interview questions
100 questions across 11 chapters. Answer each one out loud first, then open it to compare.
1Networking
-
1.1"Walk me through how you'd approach a system you've never seen."
- Structure beats recall β you're graded on the frame, not on trivia.
- Every chapter here gives you one frame; memorise the frames, derive the details.
- If you can draw it, you can defend it under follow-up questions.
-
1.2"The page is slow. Where do you look first?"
- Open the waterfall, not the profiler β confirm it's network-bound before touching code.
- Count round trips and identify the longest dependency chain, not the biggest file.
- Report at p75 on real devices; averages hide the users who churn.
-
1.3"What happens when you type a URL and press Enter?"
- Name the six stages in order and say which are cacheable β that alone passes.
- Call out that the HTML streams: parsing overlaps with download.
- Land on the frontend lever: the critical path is HTML β CSS β render-blocking JS.
-
1.4"You migrated to HTTP/2 and nothing got faster. Why?"
- Check the bundling strategy: 1.1-era concatenation cancels multiplexing's benefit.
- Check the network: on lossy mobile links, TCP head-of-line blocking eats the gain.
- Check the origin: if TTFB is server-bound, the protocol was never the bottleneck.
-
1.5"PUT or PATCH β and why does it matter for retries?"
PUTreplaces the whole resource and is idempotent, so a timeout can be retried safely.PATCHapplies a delta and generally isn't, so retries need an idempotency key.- On flaky mobile networks, retry safety is a design decision, not a detail.
-
1.6"GraphQL removed over-fetching. What did it cost you?"
- HTTP caching:
POST /graphqlis opaque to CDNs, so caching moves into the client (normalized store) or needs persisted queries +GET. - Server performance becomes the client's problem β one careless nested query can hammer the database.
- You now own schema versioning, deprecation, and query governance.
- HTTP caching:
-
1.7"Why don't we just use gRPC from the browser?"
- The Fetch API gives no control over HTTP/2 framing, so raw gRPC is impossible.
- gRPC-Web works but needs a translating proxy and drops client-side streaming.
- The usual shape: browser β BFF (REST/GraphQL) β services (gRPC).
-
1.8"Design the API layer for a mobile-heavy social app."
- Mobile bandwidth + per-screen nesting β GraphQL at the edge, one query per screen.
- Keep images and static content on plain REST/CDN URLs so they stay cacheable.
- Internal fan-out (feed, ranking, notifications) over gRPC behind a BFF.
2Communication
-
2.1"Design the update mechanism for a food-delivery tracking screen."
- Split by frequency: order status changes rarely (poll), rider location changes constantly (stream).
- Use SSE for location because it's one-way and reconnects itself; save WebSockets for the chat with the rider.
- State the fallback and the reconnect/backoff policy β that's the part candidates skip.
-
2.2"What's wrong with
setInterval(fetchData, 1000)?"- Responses slower than the interval stack up; use a
setTimeoutchain that waits for the response. - It keeps polling in a hidden tab β gate on
visibilityStateand back off. - No jitter means synchronised clients hammer the server in waves.
- Responses slower than the interval stack up; use a
-
2.3"Why not just poll every second instead?"
- Short polling burns requests when nothing changed; long polling only answers when there's news.
- The cost moves from bandwidth to held server connections and requires a non-blocking server.
- Past roughly one update per second, reconnect churn beats the savings β switch to WebSocket or SSE.
-
2.4"Your chat works locally and breaks behind the company proxy. Why?"
- Some proxies strip the
Upgradeheader or kill idle connections;wss://(TLS) survives far more of them. - Add heartbeats so a silently dead connection is detected, and always ship an SSE or long-poll fallback.
- Behind a load balancer, a reconnect can land on a different server β you need a shared pub/sub layer, not in-memory state.
- Some proxies strip the
-
2.5"Score ticker for ten million viewers β SSE or WebSocket?"
- SSE: the client never sends anything, so duplex is wasted capacity and wasted code.
- Reconnect and replay come free via
Last-Event-ID, which is the hard part of a WebSocket build. - It's plain HTTP, so it rides existing CDN, proxy, and HTTP/2 infrastructure β but confirm HTTP/2 first.
-
2.6"Payment succeeds. How does the user's screen update?"
- Two hops: Stripe β your server by webhook, then your server β the browser by SSE, WebSocket, or a short poll on the order.
- Never wait on the webhook in the checkout request β show an optimistic pending state and reconcile.
- Handle duplicate and out-of-order deliveries with an idempotency key on the event id.
-
2.7"Design real-time updates for a stock trading dashboard."
- Prices: SSE β one-way, high frequency, and free reconnect with replay by
Last-Event-ID. - Order placement and fills: WebSocket, because the client sends and needs sub-second acknowledgement.
- Throttle on the client: coalesce ticks into one render per animation frame, or the UI dies before the network does.
- Prices: SSE β one-way, high frequency, and free reconnect with replay by
3Security
-
3.1"How do you think about security on the frontend?"
- Name the surfaces β injection, third-party code, embedding, transport, and the client's inability to keep secrets.
- Say the frontend can only reduce risk; authorisation is always re-checked server-side.
- Lead with the two highest-leverage moves: contextual output escaping and a strict CSP.
-
3.2"React escapes everything. Are you safe from XSS?"
- No β
dangerouslySetInnerHTML,href={userInput}with ajavascript:URL, andrefDOM writes all bypass it. - Server-rendered JSON embedded in a
<script>tag is a second common hole. - Layer it: escape by context, sanitize rich text with an allowlist, and ship a CSP for the case you missed.
- No β
-
3.3"Your dashboard can be embedded on any site. What's the risk and the fix?"
- Clickjacking: an invisible overlay turns a real user click into a real destructive action.
- Fix with
frame-ancestors, plusSameSite=Laxcookies so framed requests don't carry the session. - If embedding is a product requirement, allowlist specific parents and require confirmation steps for destructive actions.
-
3.4"You ship a CSP and your payment widget stops loading. What now?"
- Read the console violation: it names the directive and the blocked origin.
- Add that specific origin to the specific directive β never widen to
*or add'unsafe-inline'. - Long term, run report-only in staging so violations surface before release, not after.
-
3.5"Where do you store the JWT?"
- Not
localStorageif you can avoid it: any XSS reads it instantly. - Prefer an
HttpOnly; Secure; SameSite=Laxcookie, which XSS cannot read, and handle CSRF separately. - Keep access tokens short-lived with server-side refresh rotation, so a stolen token has a small window.
- Not
-
3.6"Site is HTTPS. Is the data safe?"
- In transit, yes: encrypted, tamper-evident, and the server's identity is verified.
- Not at rest, not in the browser, and not against XSS β TLS protects the pipe, not the endpoints.
- Add HSTS for the first-request gap,
Securecookies, and eliminate mixed content.
-
3.7"
npm auditreports 40 vulnerabilities. What do you do?"- Triage by reachability first: a dev-only build tool's ReDoS is not a production incident.
- Fix anything reaching production or with network/filesystem access; patch the rest on a schedule.
- Then fix the process β audit gate in CI, automated patch PRs, and lockfile discipline.
-
3.8"Where does compliance touch frontend architecture?"
- Third-party scripts become conditionally loaded modules, so your tag manager and CSP
connect-srcmust both be consent-aware. - Analytics must degrade gracefully β the product works fully for users who refuse.
- PII must be scrubbed before it reaches logging and error reporting (see Chapter 7).
- Third-party scripts become conditionally loaded modules, so your tag manager and CSP
-
3.9"You sanitize on input. Why is that not enough?"
- The safe form depends on the destination β the same string needs different treatment in HTML, a URL, and SQL.
- Escaping early corrupts the stored data and double-escapes when rendered elsewhere.
- Correct order: validate shape on input, store raw, escape at each output sink.
-
3.10"Where does SSRF show up in a frontend-facing feature?"
- Anywhere the user supplies a URL your backend then fetches: link previews, imports, webhooks, avatar-by-URL, PDF/screenshot renderers.
- Headless-browser screenshot services are especially exposed β they follow redirects and run JS.
- The fix is resolve-then-validate plus network egress restrictions, not a regex on the string.
-
3.11"How is SSJI different from XSS?"
- XSS executes in one user's browser inside the origin sandbox; SSJI executes on your server with no sandbox at all.
- Impact: session theft versus environment variables, database credentials, and lateral movement.
- Both come from the same root cause β data reaching an interpreter β but SSJI has no recoverable blast radius.
-
3.12"Why restrict features you never call?"
- If XSS or a compromised third-party script lands, those APIs are available to it under your origin's trust.
- Permission prompts show your domain, so abuse damages your reputation directly.
- It's a one-line header covering every route, including ones added after you wrote it.
-
3.13"Does SRI prevent supply-chain attacks?"
- It prevents delivery-time tampering β a compromised CDN or MITM serving different bytes.
- It does not help if the package was already malicious when you hashed it (see 3.7) or if the URL is versionless.
- Pair it with CSP
require-sri-forwhere supported, and prefer self-hosting pinned versions.
-
3.14"You get a CORS error. Is it a frontend bug?"
- No β CORS is granted by the server, so the fix is a response header, not client code.
- Read the exact message: disallowed origin, disallowed header, or missing credentials support each need a different header.
- The clean production answer is often to remove the cross-origin call entirely by proxying the API under the same origin.
-
3.15"Are you safe from CSRF if your API uses JWT in an Authorization header?"
- Structurally yes, because the browser never attaches that header automatically.
- But storing the JWT where JS can read it hands it to any XSS β you traded one risk for another.
- The balanced answer:
HttpOnly+Secure+SameSite=Laxcookies, plus a CSRF token on state-changing routes.
4Testing
-
4.1"What's your testing strategy for a large frontend?"
- Name the shape and the ratio, then justify it by CI time and debugging cost, not by dogma.
- Cover money paths with E2E, everything else lower; add visual and a11y checks as separate gates.
- State the flake policy β quarantine within a day β because that's what keeps a suite trusted.
-
4.2"Where's the line between a unit and an integration test?"
- It's the mocking boundary, not the file count β one component with a mocked child is a unit test.
- I default to mocking only the network (MSW), so the real render, state, and event path stay under test.
- That makes tests survive refactors, which is the property that decides whether a suite lasts.
-
4.3"Your E2E suite is flaky. How do you fix it?"
- Measure first: track per-test failure rate and quarantine anything under 99% within a day.
- Attack the structural causes β shared data, real third parties,
sleep-based waits, animation timing. - Then shrink the suite; most flaky E2E suites are covering things that belong two layers down.
-
4.4"How do you A/B test without hurting performance?"
- Decide at the edge so the variant ships in the HTML β no flicker, no extra round trip, no layout shift.
- Keep the payload as one small config object, not two bundles; lazy-load only genuinely divergent code.
- Add latency and error rate as guardrail metrics, so a winning variant that slows the page still loses.
-
4.5"How do you stop performance regressing over time?"
- Make it a gate, not a goal: budgets fail CI so no regression merges silently.
- Cheap deterministic checks (bundle size) on every PR, full Lighthouse on main, RUM alerting in production.
- Track p75 on real devices β averages hide exactly the users who churn.
-
4.6"Do you practise TDD?"
- For logic-heavy code and for every bug fix, yes β a bug without a failing test first has no proof it's fixed.
- For visual and exploratory UI work I build first and test the settled behaviour, because the interface is still moving.
- The durable benefit isn't coverage, it's that untestable code is usually badly designed code, and TDD surfaces that immediately.
-
4.7"How do you test security in a frontend pipeline?"
- Layer it: secrets at commit, dependencies and SAST on PR, DAST on staging, header assertions as ordinary tests.
- Gate only on reachable high severity, or the team learns to bypass the gate entirely.
- Automation finds known patterns; business-logic flaws β like an IDOR on an order id β still need a human.
-
4.8"How do you test a component that fetches data?"
- MSW intercepts at the network layer, so the real fetch, real serialization, and real error branches all run.
findBy*for the resolved state,queryBy*to assert the loading state is gone β neversleep.- Cover all four states β loading, empty, error, success β since the last three are where production bugs actually live.
5Performance
-
5.1"Which metric would you optimise first, and why?"
- Start with LCP, because it usually shares a root cause with TTFB and render-blocking resources β one fix moves several numbers.
- Then INP, since main-thread work is what makes an app feel broken even after it looks loaded.
- CLS is usually the cheapest fix of the three: dimensions on media and reserved space for late-injected content.
-
5.2"How do you justify a performance sprint to a product manager?"
- Convert the metric into their language: p75 LCP, the conversion delta measured or benchmarked, and the revenue that implies.
- Show the device gap β most stakeholders have never seen the site on a mid-tier Android on 4G.
- Ask for a budget in CI instead of a one-off sprint, so the win doesn't erode by the next quarter.
-
5.3"Lighthouse says 98. Users say it's slow. Who's right?"
- Both β Lighthouse measures one simulated device, field data measures the population.
- Look at p75 and p95 by device class and route; the regression is almost always concentrated somewhere specific.
- Keep lab for gating merges and field for alerting; using either alone leaves a blind spot.
-
5.4"Walk me through debugging a slow page."
- Throttle, reload, open the waterfall, and find what delays the LCP element's start time.
- Chains and render-blocking resources first; only then look at bundle size and main-thread work in the flame chart.
- Verify on a real mid-tier device, then lock the win in with a CI budget (4.5) so it doesn't regress.
-
5.5"The hero image is the LCP element and it's slow. Fix it."
- First ask when it starts, not how long it takes β usually it's discovered late inside CSS or JS.
preloadwithfetchpriority="high", serve AVIF/WebP withsrcset, and set explicit dimensions to protect CLS.- Then check the origin: a slow TTFB delays everything downstream regardless of image size.
-
5.6"SSR or CSR for an e-commerce site?"
- Per route: product and category pages need SEO and fast LCP β SSG/ISR at the edge; cart and account are CSR behind login.
- Price and stock are the genuinely dynamic bits β fetch those client-side or stream them into a static shell.
- Name hydration cost explicitly: SSR that ships a huge bundle can feel slower than CSR despite a better LCP.
-
5.7"Your bundle is 500KB. Where do you start?"
- Open the treemap first β in most apps two or three dependencies own half the weight.
- Route-split, replace the heavyweights, verify tree shaking is actually happening (named ESM imports,
sideEffects). - Lock it in with a
size-limitgate in CI (4.5), or it grows straight back next quarter.
6Database & Caching
-
6.1"Where would you cache the user's feed?"
- Three layers: HTTP cache for the assets, an in-memory client cache for the current session, and IndexedDB for offline availability.
- Normalise entities (6.6) so one updated post updates everywhere rather than in three copies.
- Then state the invalidation rule explicitly β TTL, ETag revalidation, or event-driven purge β because that's the part that actually gets asked about.
-
6.2"Why not keep the whole Redux store in localStorage?"
- It's synchronous, so serialising a large store on every change blocks the main thread and hurts INP.
- 5MB is a hard ceiling with no eviction, and writes throw once you hit it.
- Persist a small deliberate slice (preferences, draft ids) and use IndexedDB for anything substantial.
-
6.3"Session storage or local storage for a checkout flow?"
sessionStorage: the draft is meaningful only for this attempt, and two tabs must not overwrite each other.- It survives an accidental refresh, which is the actual failure users hit.
- Anything that must outlive the tab β a saved cart β belongs on the server, keyed to the user.
-
6.4"Where do you store the session, and why?"
HttpOnly; Secure; SameSite=Laxcookie: XSS can't read it and most CSRF is closed by default.- Short-lived access token with server-side refresh rotation, so a stolen cookie has a small window.
- Keep everything else out of cookies β each byte is uploaded on every request for the life of the session.
-
6.5"How do you make a mail client work offline?"
- IndexedDB for messages with indexes on thread and date, plus an
outboxstore for queued sends. - Service worker (9.1) serves the shell and static assets; the data layer reads IDB first, then revalidates.
- Sync is the real design: a cursor/
updatedAtwatermark, last-write-wins or explicit conflict UI, and replay of the outbox on reconnect.
- IndexedDB for messages with indexes on thread and date, plus an
-
6.6"A WebSocket sends you an updated post. How does the UI update?"
- Normalized store: write the entity once by id, and every list referencing it re-renders consistently.
- Denormalized store: you'd have to locate every copy, and the one you miss becomes an intermittent bug.
- Keep order arrays separate from entities so live inserts and removals don't disturb the data itself.
-
6.7"You deployed but users still see the old version. Why?"
- The HTML was cached with a
max-age, so browsers never asked for the new one and kept referencing old asset URLs. - Correct split:
no-cacheon the HTML document,immutable+ longmax-ageon hashed assets. - Purge the CDN for the document too β the edge can hold a stale copy even after the origin updates.
- The HTML was cached with a
-
6.8"How would you make a news site work offline?"
- Precache the shell, network-first for documents with an offline fallback, cache-first for hashed assets.
- Stale-while-revalidate for the feed so it opens instantly and refreshes behind the user.
- Version the caches, cap the image cache, and keep payments network-only β never serve a stale transaction.
-
6.9"Two components need the same data. How many requests?"
- One β the cache deduplicates by key and both components subscribe to the same entry.
- That's precisely why the key must include every parameter; a missing filter serves the wrong cached data.
- Layer invalidation: TTL as the floor, mutation invalidation for your own writes, and events for other users' writes.
-
6.10"Which state management library would you choose?"
- Reframe first: most of the state is server state, so the real answer is a caching library plus the URL.
- What's left is genuinely small β theme, modals, cart β and
useStateplus one lightweight store usually covers it. - Choose Redux when you need time-travel debugging, middleware, or a large team needing strict conventions β not by default.
7Logging & Monitoring
-
7.1"How do you know your frontend is healthy in production?"
- Metrics first: JS error rate, failed request rate, and p75 Web Vitals, all sliced by release.
- Alert on user-visible symptoms rather than causes β checkout success rate beats CPU usage.
- Then logs and traces for depth, with a request id that connects a browser session to backend spans.
-
7.2"What do you log from the frontend, and what do you never log?"
- Always: error and stack, release id, route, device and connection, breadcrumbs, and feature-flag or experiment tags.
- Never: emails, phone numbers, payment data, auth tokens, or full URLs that may carry tokens in the query string.
- Scrub on the client before transmission, since server-side scrubbing still means the data left the device.
-
7.3"Design alerting for a checkout flow."
- One P1 on the business outcome: checkout completion rate below its normal band for five minutes.
- Supporting P2s on payment API error rate and p75 checkout LCP, so you learn why before the P1 fires.
- Every alert names an owner and links a runbook; anything without an action becomes a dashboard, not a page.
-
7.4"Production error rate just spiked. Walk me through your response."
- Acknowledge, then scope: how many users, which route, which release β and check what deployed in the last hour.
- Mitigate before diagnosing: roll back or kill the flag, so the investigation isn't racing against user impact.
- Then map the stack, reproduce with the right flags, add a failing test, fix, and run a blameless postmortem.
8Accessibility
-
8.1"How do you approach accessibility in a component library?"
- Start from semantic elements and only build custom widgets when the platform genuinely lacks one.
- Bake keyboard interaction and focus management into each component, so consumers get it by default.
- Automate what's automatable (axe in CI), and keep a manual keyboard-and-screen-reader pass for new patterns.
-
8.2"How do you test keyboard accessibility?"
- Put the mouse away and Tab through the whole flow: everything interactive must be reachable, activatable, and visibly focused.
- Check the order matches the visual layout, since CSS can reorder without changing the DOM.
- For each custom widget, verify the expected keys β Escape on dialogs and arrows on composite widgets are the usual gaps.
-
8.3"How do you make a custom dropdown screen-reader friendly?"
- Use
<select>if the design allows; the platform version is correct everywhere for free. - If not:
role="combobox"witharia-expanded,aria-controls,aria-activedescendant, plus the full arrow/Enter/Escape key contract. - Announce results with a polite live region, and verify in VoiceOver and NVDA β the specs agree, the implementations don't always.
- Use
-
8.4"Your SPA is accessible on first load but not after navigation. Why?"
- Client-side routing swaps the DOM without the focus and announcement reset a real navigation performs.
- Fix by moving focus to the new heading, updating
document.title, and announcing via a polite live region. - The same class of bug hits deletions β focus left on a removed node falls back to
<body>and the user loses their place.
-
8.5"Design gives you a palette that fails contrast. What do you do?"
- Bring numbers, not opinions: show the measured ratio and which text sizes fail.
- Propose a derived accessible shade for text and controls, keeping the brand colour for large type and fills.
- Add the check to CI or design tooling so the next palette doesn't repeat it.
-
8.6"Lighthouse gives us 100. Are we accessible?"
- No β automated tools cover roughly a third of the criteria, mostly static markup issues.
- They can't judge whether alt text is correct, whether tab order makes sense, or whether focus survives an action.
- Pair automation in CI with a manual keyboard and screen-reader pass on each new flow.
-
8.7"You inherit a product with 300 accessibility violations. Where do you start?"
- Triage by blocked tasks first: anything that stops a keyboard or screen-reader user completing a core flow.
- Map violations to components β a handful of design-system fixes usually resolves the majority of instances.
- Then gate it in CI and add it to the definition of done, so the backlog shrinks instead of refilling.
9Offline Support
-
9.1"You deployed a fix but users still see the broken version. Why?"
- The old service worker keeps control until every tab using it closes; a refresh doesn't replace it.
- Either call
skipWaitingandclients.claim, or surface an explicit update prompt β silence is what causes this. - It's also why a kill-switch SW and cache versioning are mandatory before your first production deploy.
-
9.2"When would you build a PWA instead of a native app?"
- When reach and update speed matter more than deep device integration β content, commerce, tools, internal apps.
- When install friction is the main funnel problem: a link that becomes an app beats a store listing.
- Not when you need background location, tight OS integration, or store-based discovery and billing.
-
9.3"The user taps Send twice on a flaky connection. How do you avoid a duplicate message?"
- The client creates the message ID once, before the first attempt, and every retry reuses it as the idempotency key.
- The server records keys it has already applied and returns the stored result for a repeat instead of applying it again.
- The UI renders from the local outbox by that same ID, so the screen shows one message too β clock, then tick.
-
9.4"Two devices edit the same note offline. What happens when both reconnect?"
- Each edit carries the version it was based on, so the second to arrive is visibly stale β a conflict, not a silent overwrite.
- Fields that don't overlap merge automatically; for the same field, choose per field β last write wins for low stakes, the user decides for content that matters.
- For genuinely collaborative text, use a CRDT so concurrent edits always converge and there is nothing to resolve.
-
9.5"Your offline notes app loses users' unsent notes on iPhone. Why, and what do you do?"
- Safari has no Background Sync, so the queue only flushes while the app is open β and if the site isn't installed, its storage can be cleared after 7 days of Safari use without the user interacting with it.
- Flush on open, on
onlineand on visibility change; encourage Add to Home Screen, and callpersist()after the first offline save. - Show unsent items clearly so nothing disappears silently, and keep the outbox small by collapsing edits (9.3).
10Low Level Design
-
10.1"Design a reusable Table component."
- Start with the API out loud:
columnsconfig,data,onSort,renderCellfor escape hatches, slots for empty and error states. - Keep sorting and pagination controlled so the parent can drive them from the URL (6.10).
- Name the accessibility contract β real
<table>semantics,scopeon headers, sortable columns announcingaria-sort.
- Start with the API out loud:
-
10.2"How would you build a home screen that changes without a release?"
- Server returns an ordered list of typed sections; the client maps types to components via a registry.
- Validate the config, ignore unknown types for forward compatibility, and version the schema.
- Keep data fetching per section (each declares its own
source) so one slow API doesn't block the whole screen β stream or lazy-load below the fold.
-
10.3"Spinner or skeleton?"
- Skeleton when the layout is known and the wait exceeds a second β it removes the layout shift and sets expectations.
- Spinner for short or unpredictable waits; nothing at all under ~300ms.
- Best of all is stale-while-revalidate, so returning users see content instantly and it refreshes underneath.
-
10.4"How do you protect routes in an SPA?"
- A guard component wrapping the protected subtree, driven by a three-state auth value so refresh doesn't flash the login page.
- Preserve and validate the return path, and use
replaceso the back button doesn't bounce between login and page. - Say plainly that this is presentation only β the server authorises every request regardless of what the client renders.
-
10.5"Redux or Context?"
- Neither, usually β most of what people put in Redux is server state and belongs in a query cache.
- Context broadcasts to every consumer, so it fits low-frequency values like theme and locale, not a cart.
- For genuine global client state I'd default to a selector-based store and reach for Redux Toolkit when the team needs strict conventions, middleware, or time-travel debugging.
-
10.6"How would you add multi-language support to an existing app?"
- Extract to keys with a source bundle, wire
Intlfor all formatting, and lazy-load one locale at a time. - Fix layout for text expansion and switch to logical CSS properties so RTL is a
dirattribute, not a second stylesheet. - Decide URL strategy early β
/de/pathis best for SEO and shareability, and it makes locale a routing concern rather than hidden state.
- Extract to keys with a source bundle, wire
-
10.7"Build an infinite feed. What breaks first?"
- The DOM: without virtualization, memory and scroll performance degrade after a few hundred items.
- Offsets: with items being inserted at the top, offset pagination duplicates and skips β use cursors.
- Then the details that get skipped: the double-fire guard, the end state, scroll restoration, and a keyboard-accessible load-more.
-
10.8"Build an accordion."
- Ask single or multiple first, because it decides the state shape.
- Buttons inside headings,
aria-expandedandaria-controlswired,hiddenon closed panels, focus staying on the trigger. - If the content is heavy, lazy-render panels on first open and keep them mounted afterwards to preserve scroll and form state.
-
10.9"Build Reddit-style nested comments."
- Normalized flat store, memoised parentβchildren map, recursive component with a depth prop.
- Cap indentation around five levels and link deeper threads to their own view β this is a UX requirement, not a shortcut.
- For very large threads, flatten to a visible-nodes array and virtualize; recursion and virtualization don't compose easily.
-
10.10"Build an image carousel."
- Track with a single
translateX, transform-only animation, neighbour preloading, and pointer-based swipe with a commit threshold. - Autoplay pauses on hover, focus, and hidden tab, stops after interaction, and honours reduced motion.
- Mention CSS
scroll-snapas the simpler path when autoplay isn't required β it gives you momentum and accessibility for free.
- Track with a single
-
10.11"Why did the same item appear on two pages?"
- Offset pagination on a list that receives inserts β every new row at the top shifts the window by one.
- Cursors fix it because position is defined by the row you last saw, not by a count.
- Keep a unique tiebreaker in the sort key, or identical timestamps will still cause skips at boundaries.
-
10.12"Build a pagination component."
- Start with the API:
total,page,pageSize,onChangeβ and state that page lives in the URL, not in the component. - Extract the ellipsis range into a pure function so it's unit-testable, and keep the slot count fixed to avoid layout shift.
- Use
<nav>witharia-current="page"and real links, so keyboard, screen reader, and middle-click all behave correctly.
- Start with the API:
-
10.13"Live updates arrive while the user is scrolled into the feed. What do you do?"
- Buffer inserts behind a "N new posts" banner and keep scroll anchored; only auto-insert when the user is at the top.
- Patch entities by id in a normalized store so unrelated rows don't re-render.
- Handle sequence numbers, reconnect deltas, and dirty local fields β those three are what separate a real implementation from a demo.
-
10.14"Design live chat for a stream with 500k viewers."
- Client side: buffer and flush on a frame, cap the window, virtualize, and pin to bottom only when the user is already there.
- Transport: SSE or WebSocket per viewer, fanned out from a pub/sub layer β and at extreme volume the server samples messages rather than sending all of them.
- Say the quiet part: nobody can read 300 messages a second, so sampling and "chat paused" are features, not degradations.
-
10.15"Build an autocomplete. What are the failure modes?"
- The race: an earlier slow request landing after a later fast one β fix with
AbortControllerand a stale-response check. - The traffic: no debounce and no minimum length means a request per keystroke.
- The accessibility: it's a
comboboxwitharia-activedescendant, so focus stays in the input while arrows move the selection β most implementations get this wrong.
- The race: an earlier slow request landing after a later fast one β fix with
11High Level Design
-
11.1"Design Instagram's frontend."
- Scope out loud first: feed and upload for mobile web, excluding stories, DMs, and reels β then confirm.
- Give a number: 500M DAU, ~30 posts per session, images 200KB after transform.
- Then follow the frame, and reserve the middle 15 minutes for the two deep dives, which is where the grading actually happens.
-
11.2"The feed janks after a minute of scrolling. Why?"
- Unbounded DOM: every scrolled card is still mounted, so memory and layout cost grow linearly β virtualize.
- Images: wrong variant for the device, no
aspect-ratiobox, decoding on the main thread β usesrcset, reserved space, anddecoding="async". - Then verify with a flame chart (5.4) rather than guessing; long tasks name the culprit.
-
11.3"Why not just SSR the whole site?"
- Product and category pages are identical for everyone β rendering them per request wastes capacity that matters on sale days.
- ISR at the edge gives the same SEO and a better LCP, with a client island keeping price and stock accurate.
- Cart and checkout are per-user and must never be cached, so those stay client-rendered with
no-store.
-
11.4"New posts arrive while the user is reading. What do you do?"
- Buffer them and show a count pill; only insert automatically when scroll is at the very top.
- Use cursor pagination so those inserts don't cause duplicates on the next page fetch.
- Patch by id into a normalized store, so a like on one post doesn't re-render the entire list (10.5).
-
11.5"The video keeps stalling on mobile. What do you change?"
- Check the buffer policy first: the player should drop a rung on a draining buffer rather than defending quality.
- Shorten segment length so adaptation reacts faster, and cap the maximum rung on small screens where 4K is invisible anyway.
- Verify with rebuffer ratio in telemetry, not by watching it once on a good connection.
-
11.6"Music stops when the user navigates. Why, and how do you fix it?"
- The
<audio>element is inside a route, so navigation unmounts and recreates it. - Hoist a single player instance above the router and drive it from a global store; routes dispatch play/pause intents only.
- Then add Media Session so hardware and lock-screen controls work, which is expected behaviour for anything audio.
- The
-
11.7"Ten million concurrent viewers. WebSocket or SSE?"
- SSE: the traffic is entirely one-way, and reconnect plus replay come free, which is the expensive part of a WebSocket build.
- Terminate connections at edge PoPs fanning out from pub/sub, so the origin publishes once.
- Then name the degradation ladder: full push β coalesced push β CDN-cached JSON polling, so peak load has a floor.
Review 11.7 HLD β Live Commentary (CricInfo, Cricbuzz) β
-
11.8"The user archives 20 emails offline. What happens?"
- Each action applies to IndexedDB immediately and appends to an ordered outbox; the UI reflects it at once.
- On reconnect the outbox replays in order with idempotency keys, so retries can't double-apply.
- Conflicts resolve by type β label changes merge, deletes win over edits, and conflicting drafts are kept as two versions rather than silently dropped.
-
11.9"Dragging gets slow with 5,000 shapes. What's wrong?"
- You're probably redrawing the entire canvas per pointer event β split into static and active layers so a drag redraws one shape.
- Hit testing is likely linear per mousemove; add a quadtree and cull to the viewport.
- Coalesce pointer events into one
requestAnimationFrametick; browsers deliver far more of them than you can render.
-
11.10"A widget needs to chart 40 million rows. How?"
- It doesn't β the server aggregates to the granularity the chart can actually show, typically a few hundred points.
- Downsample with an algorithm that preserves visual shape (LTTB) rather than naive sampling, which hides spikes.
- Keep the widget independently loaded and cached by its query key so other cards render while it works.
Review 11.10 HLD β Analytics Dashboard (Google Analytics) β
-
11.11"Two users type in the same sentence. How does it not break?"
- Position indices shift under concurrent edits, so raw last-write-wins loses one of them.
- OT transforms incoming operations against already-applied ones; CRDTs give every character a unique id so merges commute.
- I'd pick based on constraints β OT with an authoritative server, CRDT if offline or peer-to-peer editing is required β and I'd apply locally first so typing never waits on the network.
-
11.12"How do you recalculate a sheet with 10 million cells?"
- You don't recalculate the sheet β you recalculate the dependents of the edited cell, found via reverse edges in a DAG and ordered topologically.
- Detect cycles at parse time so a circular reference errors instead of hanging the tab.
- If the dirty set is large, run recalculation in a Web Worker and batch one repaint per frame so typing stays responsive.
-
11.13"Would you use microfrontends here?"
- Only above roughly four teams, or to strangle a legacy app route by route β otherwise a monorepo with clear module boundaries gives the same isolation with none of the runtime risk.
- If yes: shell owns routing, auth, and shared singletons; remotes deploy independently; communication goes through the URL and events, never a shared store.
- The recurring cost is shared-dependency version skew, and I'd plan an upgrade cadence for it upfront.
-
11.14"Two users drag the same card at once. What happens?"
- Both apply optimistically and locally, so both feel instant; the server resolves position by last write and broadcasts the result.
- Each client reconciles against its optimistic copy and animates to the server's answer, so no two boards disagree.
- The card that lost shows a toast explaining the move β silently snapping back is what makes users distrust the tool.