Skip to content

Frontend System Design

As a full-stack JS dev, you may get a frontend system design round instead of (or as well as) backend HLD. The question looks like “Design an autocomplete component” or “Design the Instagram feed UI”. It’s about component architecture, state, data fetching, performance and accessibility — not databases.

R ── Requirements what features, which devices, offline? a11y? i18n?
A ── Architecture components and how they talk (diagram), where state lives
D ── Data model client state shape, server data, caching/normalisation
I ── Interface (API) component props/events + server API contracts
O ── Optimizations performance, network, a11y, UX polish, edge cases

Time split (45 min): R 5 / A 10 / D 5 / I 10 / O 15. Optimizations is where you score points — have a checklist ready.

Optimizations checklist (reuse in every answer)

Section titled “Optimizations checklist (reuse in every answer)”
Area Things to mention
Network debounce/throttle, caching, request cancellation (AbortController), prefetch, pagination, compression, HTTP caching, CDN
Rendering virtualization for long lists, memoization, avoiding layout thrash, requestAnimationFrame, CSS transforms over top/left
Loading code splitting, lazy loading (loading="lazy", IntersectionObserver), skeletons, srcset/responsive images, WebP/AVIF
State single source of truth, server cache (React Query/SWR) vs UI state (Zustand), optimistic updates
Accessibility keyboard nav, ARIA roles, focus management, screen reader announcements, prefers-reduced-motion, contrast
Resilience error states, retries, offline, race conditions, empty states
Metrics Core Web Vitals: LCP, INP, CLS

R — Show suggestions as the user types; keyboard navigation; click/enter to select; highlight match; works for a large dataset (server-side search); mobile friendly.

A

<Autocomplete>
├── <Input> onChange → debounced query
├── <SuggestionList> role="listbox"
│ └── <SuggestionItem> role="option", highlighted match
└── controller/hook: useAutocomplete(fetcher)
├── cache: Map<query, results>
└── AbortController for in-flight request

D

type State = {
query: string;
results: Suggestion[];
status: "idle" | "loading" | "error" | "success";
activeIndex: number; // keyboard highlight
open: boolean;
};
const cache = new Map<string, Suggestion[]>(); // LRU-capped, with TTL

I

<Autocomplete
fetchSuggestions={(q, signal) => Promise<Suggestion[]>}
onSelect={(item) => void}
minChars={2}
debounceMs={250}
renderItem={(item, query) => ReactNode}
/>
// GET /api/search/suggest?q=pyth&limit=8

O — talking points

  • Debounce input (~200–300 ms) to avoid a request per keystroke.
  • Race conditions: typing “ja” then “jav” — “ja” response may arrive last and overwrite. Fix: abort the previous request with AbortController, or ignore responses whose query ≠ current query.
  • Cache results per query (client LRU); prefix results can be filtered locally for short lists.
  • Accessibility: role="combobox", aria-expanded, aria-activedescendant, aria-controls; arrow keys/Enter/Escape; announce result counts.
  • Highlight the matched substring safely (no dangerouslySetInnerHTML with user input).
  • Show loading, empty (“No results”) and error states; close on blur/Escape.

R — Load posts in pages as the user scrolls; images; like/comment; new posts indicator; should stay smooth with thousands of items. (Ties to AniSnap.)

A

<Feed>
├── <NewPostsPill> "5 new posts ↑" (polling / realtime count)
├── <VirtualList> renders only visible rows (+ overscan)
│ └── <PostCard> image (lazy), actions (optimistic like)
└── <Sentinel/> IntersectionObserver → fetchNextPage()
Data layer: useInfiniteQuery(['feed'], ({ pageParam }) => getFeed(pageParam))

D

type Page = { items: Post[]; nextCursor: string | null };
// Normalised store helps when the same post appears in multiple places:
type Store = { postsById: Record<string, Post>; feedIds: string[] };

I

GET /api/feed?cursor=<createdAt_id>&limit=20 → { items, nextCursor }
POST /api/posts/:id/like (optimistic on client, rollback on error)

O — talking points

  • Cursor pagination, not offset (no duplicates when new posts arrive).
  • IntersectionObserver sentinel instead of scroll listeners; trigger a bit before the end (rootMargin: "800px").
  • Virtualization (react-window / TanStack Virtual) once lists get long — DOM size stays constant. Handle variable heights (measure).
  • Images: loading="lazy", srcset, fixed aspect-ratio boxes to prevent CLS, blur placeholder.
  • Scroll restoration when navigating back to the feed (keep the query cache + saved offset).
  • Optimistic likes with rollback; debounce rapid toggles.
  • Don’t insert new posts at the top while user is reading (content jump) — show the pill.

R — Show images one at a time; next/prev buttons; swipe on mobile; dots; optional autoplay; loop; responsive.

A

<Carousel images autoplay interval loop>
├── <Track> (flex row, translateX(-index * 100%))
│ └── <Slide><img/></Slide> × N
├── <PrevButton/> <NextButton/>
└── <Dots/> (role="tablist")
hook: useCarousel({ count, loop, autoplay }) → { index, next, prev, goTo }

D — { index: number, isPaused: boolean, dragOffsetPx: number }

I

<Carousel images={{ src, alt, srcSet }[]} initialIndex={0} autoplay={5000} loop onChange={(i) => {}} />

O — talking points

  • Animate with CSS transform (GPU-composited), not left — smooth 60fps.
  • Lazy load non-adjacent slides; preload next/previous only.
  • Touch: pointer events, threshold to decide swipe vs tap, follow the finger during drag.
  • Autoplay: pause on hover/focus and when tab hidden (visibilitychange); respect prefers-reduced-motion.
  • A11y: buttons with labels, aria-roledescription="carousel", live region announcing “Slide 3 of 7”, arrow keys, every image has alt.
  • Fixed aspect ratio container → no layout shift.

4. Drag-and-Drop Learning Module (your Calcimate work)

Section titled “4. Drag-and-Drop Learning Module (your Calcimate work)”

R — A math exercise where the learner drags items (numbers, shapes, fraction pieces) into drop zones; instant feedback (animation + sound); submit answer; progress saved; works on touch devices; accessible alternative to dragging.

A

<ExercisePlayer exercise>
├── <DndProvider backend={isTouch ? TouchBackend : HTML5Backend}>
│ ├── <ItemTray> └── <DraggableItem/> (useDrag)
│ └── <Board> └── <DropZone/> (useDrop, canDrop rules)
├── <FeedbackLayer> GSAP animations (correct/incorrect)
├── audio service Howler sprites (preloaded)
└── <SubmitBar> → POST attempt → update quest progress
State: useReducer / Zustand store for the exercise (placements, attempts)

D

type Exercise = {
id: string;
items: { id: string; label: string; value: number }[];
zones: { id: string; accepts?: string[]; capacity: number }[];
solution: Record<string, string[]>; // zoneId -> itemIds (or validated server-side)
};
type ExerciseState = {
placements: Record<string, string | null>; // itemId -> zoneId
status: "playing" | "checking" | "correct" | "incorrect";
attempts: number;
startedAt: number;
};

I

<ExercisePlayer exercise={...} onComplete={(result) => void} />
POST /api/quests/:questId/steps/:stepId/attempts { placements, clientAttemptId, durationMs }
→ { correct, xpAwarded, nextStepId }

O — talking points

  • Data-driven exercises: the same engine renders many exercises from JSON config (authors add content without code changes). This is a great architecture point.
  • Validate on the server (or at least award XP server-side) — client-side checking is easy to cheat; clientAttemptId for idempotency so double-submit doesn’t double XP.
  • Touch support: HTML5 drag-and-drop doesn’t work on mobile → TouchBackend (or pointer-based DnD library); larger hit areas; prevent page scroll while dragging.
  • Accessibility: drag-and-drop is hard for keyboard/screen-reader users → offer “select item, then select zone” with keyboard, aria-live feedback (“Placed 3/4 in zone A”). Mention this unprompted — it stands out.
  • Animations: GSAP on transform/opacity; kill tweens on unmount; respect prefers-reduced-motion.
  • Audio: Howler sprite (one file, many sounds) preloaded; browsers block autoplay until a user gesture — unlock audio on first interaction; mute toggle persisted.
  • Performance: lazy-load GSAP/Howler/DnD only on exercise routes (code splitting); low-end Android is the target device.
  • Resilience: save progress locally (localStorage) if offline and sync later; resume half-finished exercises.

5. Video Player with Quality Switching (your Vigil work)

Section titled “5. Video Player with Quality Switching (your Vigil work)”

R — Play HLS streams; auto quality (adaptive) + manual quality menu; play/pause, seek, volume, fullscreen, captions; show buffering; works on mobile; keyboard shortcuts.

A

<VideoPlayer src=".../master.m3u8">
├── <video ref> native element
├── engine: hls.js (Chrome/Firefox via MSE) | native HLS (Safari/iOS)
├── <Controls>
│ ├── PlayPause, SeekBar (buffered ranges), Volume, Time
│ ├── QualityMenu ← hls.levels, hls.currentLevel
│ ├── CaptionsToggle, Speed, Fullscreen
└── <Overlay> spinner on "waiting", error UI
hook: usePlayer(videoRef) → { state, actions } (subscribes to media events)

D

type PlayerState = {
playing: boolean; currentTime: number; duration: number;
buffered: [number, number][]; volume: number; muted: boolean;
levels: { index: number; height: number; bitrate: number }[];
currentLevel: number; // -1 = auto
isBuffering: boolean; error: string | null;
};

I

<VideoPlayer src={hlsUrl} poster={thumbUrl} autoPlay={false} startAt={0}
onProgress={(t) => void} onQualityChange={(level) => void} />

O — talking points

  • How adaptive streaming works: master playlist lists renditions (240p…1080p); the player measures bandwidth/buffer and picks a level per segment. Manual selection sets hls.currentLevel; “Auto” sets -1.
  • Use hls.nextLevel (switch at the next segment) for smoother changes vs currentLevel (flush buffer, immediate).
  • Startup time: poster image, start at a low rendition then ramp up, preload="metadata", CDN for segments.
  • Update the seek bar via timeupdate/requestAnimationFrame — don’t re-render the whole tree each frame; keep the progress bar in a small component.
  • Mobile: iOS Safari plays HLS natively (hls.js not needed); playsInline; autoplay requires muted.
  • A11y: keyboard shortcuts (space, arrows, f, m, c), labelled buttons, captions (WebVTT), focus-visible controls.
  • Analytics: track rebuffer events, startup time, chosen quality — this is how you’d know if your renditions are right.
  • Only stream approved videos (ties back to Vigil’s moderation status), use signed URLs for private content.

Q: What does RADIO stand for?

Requirements, Architecture, Data model, Interface (API), Optimizations.

Q: Debounce vs throttle?

Debounce: run once after the user stops for N ms (search input). Throttle: run at most once per N ms while events keep firing (scroll, resize, drag position).

Q: How do you prevent stale typeahead results from overwriting newer ones?

Abort the previous request with AbortController, or tag each request with the query/sequence number and ignore any response that doesn’t match the latest one.

Q: What is list virtualization and when do you need it?

Rendering only the items visible in the viewport (plus a buffer), recycling as you scroll, so DOM size stays small. Needed when lists reach hundreds/thousands of complex items and scrolling gets janky.

Q: How do you avoid layout shift (CLS) with images?

Reserve space: set width/height attributes or a CSS aspect-ratio box, use placeholders/skeletons, and don’t inject content above what the user is reading.

Q: Why is drag-and-drop an accessibility problem and how do you fix it?

It relies on a pointer. Provide a keyboard alternative (select item with Enter/Space, move focus to a zone, press Enter to drop), announce changes via aria-live, and make targets large enough for touch.

Q: Optimistic updates — what and the risk?

Update the UI immediately assuming the server will succeed (like button), then reconcile. Risk: server fails → must roll back and show an error; also handle rapid repeated toggles (debounce or send latest state).

Q: Server state vs client state?

Server state (feed, user profile) is owned by the backend — cache it with React Query/SWR (dedupe, refetch, pagination). Client state (modal open, selected tab, exercise placements) lives in React state/Zustand. Mixing them leads to stale duplicated data.