System Design Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What is the right way to start answering a frontend system design question?
Correct answer: By clarifying requirements and constraints
A popular framework is RADIO: Requirements (functional and non-functional), Architecture (components and data flow), Data model (client state), Interface (API), Optimizations (performance, a11y, i18n, security). Without requirements it's easy to design the wrong system.
2. Why is cursor pagination better than offset pagination for a feed?
Correct answer: No duplicates on inserts and fast on deep pages
With
offset, new posts shift the window and the user sees repeats;OFFSET 100000is expensive for the DB. A cursor ("after the record with id X") is stable and efficient on an index. The downside is you can't jump to page 57, so for tables with page numbersoffsetis sometimes more appropriate.3. How would you design an infinite feed with thousands of posts?
Correct answer: Cursor loading via
IntersectionObserverplus list virtualizationA sentinel element near the end of the list triggers loading the next page. Virtualization keeps only visible items in the DOM. Also consider: restoring scroll position when navigating back, images with explicit dimensions, new posts at the top without the feed "jumping".
4. What matters when designing autocomplete?
Correct answer: Debounce, cancelling stale requests, caching, keyboard support
Plus a minimum query length, handling response races, highlighting matches, a "nothing found" state, and the ARIA combobox pattern. For a small fixed dictionary, filtering on the client is fine (sometimes with a trie); for large ones, use server-side search.
5. What is the main trade-off of GraphQL compared to REST?
Correct answer: Precise field selection, but harder caching and protection from heavy queries
GraphQL solves over- and under-fetching and provides a typed schema. But queries go via POST to a single endpoint, so URL-based CDN caching doesn't work out of the box; you need a normalized client cache (Apollo, urql), complexity limits and persisted queries.
6. What is the N+1 problem in GraphQL and how is it solved?
Correct answer: A DB query per item; solved with batching
A list of 100 posts with an
authorfield on each produces 1 + 100 queries. DataLoader collects ids within a single tick and makes oneWHERE id IN (...)query, caching results for the duration of the request.7. When is tRPC a good fit?
Correct answer: When frontend and backend are both TypeScript in one repository
tRPC infers server procedure types directly in the client without code generation or a schema. For public APIs and polyglot clients, REST with OpenAPI, GraphQL or gRPC are better.
8. What caching layers exist between the user and the database?
Correct answer: Memory, HTTP cache, Service Worker, CDN, server cache
Each layer offloads the next and reduces latency: client data cache (TanStack Query), HTTP cache via headers, SW for offline, CDN at the network edge, Redis and render cache on the server. The hard part is consistent invalidation.
9. How should JS and CSS bundles be cached?
Correct answer: A hash in the filename and
Cache-Control: max-age=31536000, immutableThe name
app.3f9a1c.jschanges when the content changes, so the file can be cached "forever". The HTML that references the bundles is cached briefly or with revalidation, so a new release is picked up immediately. Bundlers do the hashing automatically.10. What does
Cache-Control: max-age=60, stale-while-revalidate=600do?Correct answer: Fresh for a minute, then the stale response is served while it updates in the background
The user almost always gets an instant response from cache, while freshness is maintained by background revalidation. The same strategy underlies SWR, TanStack Query and ISR in Next.js.
11. Why is cache invalidation called one of the hardest problems?
Correct answer: Data lives in many caches and they must be updated consistently
The same data sits in the CDN, the server cache, the client cache and on multiple pages. Tags (
revalidateTag, key-based invalidation), short TTLs with SWR and event-driven invalidation after mutations help.12. What is the main drawback of stateless JWTs compared to server-side sessions?
Correct answer: An issued token is hard to revoke
The server verifies the signature without hitting the DB, which is convenient for scaling. But if a user is banned or a token is stolen, it keeps working. Solutions: short-lived access tokens, rotating refresh tokens, a revocation list (which partially brings state back).
13. Where is it safer to store a session token in the browser?
Correct answer: In a cookie with
HttpOnly,SecureandSameSiteAn
HttpOnlycookie is inaccessible to scripts, so XSS can't steal it directly.SameSitereduces CSRF risk,Securemeans HTTPS only. A token inlocalStoragecan be read by any injected script. There's no fully safe storage under XSS - XSS protection is mandatory.14. Why use a pair of access and refresh tokens?
Correct answer: A short-lived access token limits leak damage; refresh renews it
Access lives for minutes and is sent with every request; refresh lives longer, is stored more securely and is used only to obtain new access tokens. Refresh token rotation makes it possible to detect reuse of a stolen token.
15. Which OAuth flow is recommended for SPAs and mobile apps?
Correct answer: Authorization Code with PKCE
A public client can't keep a secret. PKCE binds the authorization request and the code exchange with a one-time verifier/challenge pair, protecting against code interception. Implicit and Password Grant are considered deprecated and insecure.
16. How does OpenID Connect differ from OAuth 2.0?
Correct answer: OIDC adds authentication to OAuth: an ID token with user data
OAuth 2.0 is a protocol for delegating access to resources ("let this app read my calendar"); it doesn't say who the user is. OIDC, built on top of it, standardizes sign-in: ID token (JWT), userinfo, discovery. "Sign in with Google" is OIDC.
17. How do you protect against CSRF with cookie-based authentication?
Correct answer:
SameSitecookies plus a CSRF token or anOrigincheckThe browser attaches cookies to requests from other sites.
SameSite=Lax/Strictblocks most such scenarios, and a token orOrigincheck covers the rest. GET must not change data, otherwise the protection breaks.18. What should you use for real-time notifications that only flow from the server?
Correct answer: Server-Sent Events over a simple HTTP stream
SSE is simpler than WebSocket: it runs over HTTP, reconnects on its own and sends
Last-Event-IDto catch up on missed events. WebSocket is needed when the client also sends data frequently. Polling every 100 ms creates a huge load.19. What should be handled when a WebSocket reconnects?
Correct answer: Backoff, resubscribing and fetching what was missed
Instant retries from thousands of clients will finish off a recovering server. After reconnecting, the client resubscribes to channels and requests events since the last received id. The UI shows the connection status.
20. How do you safely retry a payment request after a network error?
Correct answer: Send an idempotency key with every attempt
On a timeout you don't know whether the request got through. The key (
Idempotency-Key) is generated by the client per operation; when the server sees a retry, it returns the stored result. This is how Stripe and many payment APIs work.21. Why add random jitter to exponential retry backoff?
Correct answer: So clients don't retry at the same moment
If a service goes down and comes back, all clients with identical backoff hit it simultaneously (thundering herd). The random component spreads retries over time. This is covered in detail in an AWS Architecture Blog article.
22. How should user file uploads to cloud storage be organized?
Correct answer: Get a signed URL and upload directly to storage
A presigned URL lets the browser upload the file directly to S3/GCS without loading the API server or exposing keys. The backend checks permissions and issues a time-limited URL, then confirms the upload. Base64 increases size by a third.
23. How do you reliably upload multi-gigabyte files?
Correct answer: Split into chunks with resume after a disconnect
A drop at 95% of one big request loses everything. Chunks (S3 multipart upload, the tus protocol) let you resume from the break point, upload parts in parallel and show accurate progress.
24. How do you handle conflicts when two users edit the same record?
Correct answer: A version or ETag: the server rejects a stale update
The client sends
If-Match: <etag>or aversionfield; if the record has already changed, the server returns 409/412 and the UI offers to refresh or merge changes. "Last write wins" silently loses someone else's work.25. How would you build offline mode for a notes app?
Correct answer: Service Worker for the shell, IndexedDB for data and a sync queue for changes
Offline-first: the shell comes from the SW cache, data is read and written locally, changes accumulate in a queue and are sent when the network returns (Background Sync or on the
onlineevent). Conflict resolution needs to be thought through.26. What makes an app a PWA?
Correct answer: A manifest and a Service Worker: install, offline, push
A Progressive Web App is a regular HTTPS site with a web app manifest and a Service Worker. It can be installed on the home screen, works offline and receives notifications. Capabilities depend on the platform.
27. Which rendering strategy makes sense for a landing page, a catalog and a user dashboard?
Correct answer: Landing - SSG, catalog - ISR, dashboard - dynamic
The strategy follows the page's data: identical for everyone and rarely changing - static; shared data with regular updates - cache with revalidation; personal data - render per request (or PPR: a static shell plus streaming).
28. What's wrong with fully hydrating a large content page?
Correct answer: The browser executes JS even for static text
Until the JS runs, the page is visible but unresponsive - INP and TBT suffer. Solutions: Server Components (static parts aren't hydrated), islands, lazy client components,
content-visibility.29. How do you track performance for real users?
Correct answer: RUM: collect Web Vitals in production and analyze by percentiles
The
web-vitalslibrary (oruseReportWebVitalsin Next.js) sends LCP, INP, CLS viasendBeacon. Look at the 75th percentile by device type and page, and correlate regressions with releases. Lab tests are useful but don't replace field data.30. How do you speed up navigation to the page the user is likely to open next?
Correct answer: Prefetch code and data based on user intent
Prefetching based on user intent makes navigation nearly instant without wasting bandwidth on everything. Next.js
<Link>,queryClient.prefetchQueryononMouseEnter,<link rel="prefetch">, the Speculation Rules API.31. Why are third-party scripts (analytics, chats, ads) dangerous for performance?
Correct answer: They compete for the main thread and network and can block rendering
Third-party code can be heavy and is outside your control. Load it asynchronously and deferred (
next/scriptwith thelazyOnloadstrategy), use facades (a preview instead of the widget), move it to workers (Partytown), set a budget.32. How does a canary release differ from blue-green?
Correct answer: Canary - to a portion of users, blue-green - to everyone at once
Blue-green keeps two environments and switches traffic instantly, allowing fast rollback. Canary sends 1–5% of traffic to the new version and widens the share while watching metrics. They're often combined with feature flags.
33. How do you gradually enable a new feature for 10% of users?
Correct answer: A flag with rollout by user id hash
A hash of the user id gives stable group membership across sessions and devices.
Math.random()would toggle the feature on every load. Flags are evaluated on the server or at the edge to avoid UI flicker.34. What are the pros and cons of a monorepo for several frontend apps?
Correct answer: Shared code and atomic changes, but you need build and caching tooling
A change to the UI kit and all apps can be done in one PR, and code reuse is easier. The cost is scaling CI: you need tools with a dependency graph and caching (Turborepo, Nx), plus ownership and boundary rules.
35. What is the foundation of a scalable design system?
Correct answer: Tokens, documented components, versioning
Tokens (colors, spacing, typography) are a single source of truth for design and code. Components are documented and tested in Storybook and published as a package with SemVer. Accessibility out of the box and a clear evolution process matter.
36. How should the UI behave when one dashboard widget fails?
Correct answer: Isolate the failure and show a fallback only for that widget
Graceful degradation: the rest of the dashboard works, the broken widget has a message and a "Retry" button, and the error goes to monitoring. Error boundaries are placed around independent parts.
37. Why pass a request id / trace id from the frontend through to the backend?
Correct answer: To link a browser error to backend logs and traces
Distributed tracing (OpenTelemetry, the
traceparentheader) shows a request's path through the API gateway, services and DB. A user sends a screenshot with the error id - and you immediately find the full context.38. How does the token bucket rate limiting algorithm work?
Correct answer: The bucket refills with tokens at a constant rate; each request spends one
Bucket capacity sets the allowed burst, the refill rate sets the average limit. When tokens run out, the server responds with 429. Alternatives: fixed/sliding window, leaky bucket.
39. How do you show other participants' cursors in a collaborative editor without flooding the network?
Correct answer: Throttle sends and interpolate on the client
Presence data is ephemeral: it isn't stored in the document, it's sent at most 10–20 times per second and smoothed with animation. The document edits themselves are synced separately - via OT or CRDT.
40. The unread message counter differs between tabs. How do you fix it?
Correct answer: Sync tabs via
BroadcastChannelEach tab is a separate app with its own state.
BroadcastChannelpasses changes between them; you can also keep a single server connection in a SharedWorker and broadcast events to tabs.41. How do you load translations in a multilingual SPA without bloating the bundle?
Correct answer: Dynamically load only the current language's dictionary (and per section)
Dictionaries for all languages easily take hundreds of kilobytes. Dynamic import by locale and namespace saves bandwidth. With Server Components, dictionaries don't end up in the client bundle at all.
42. Which HTTP security headers should a web app configure?
Correct answer: CSP, HSTS,
frame-ancestors,nosniffCSP restricts script sources, HSTS enforces HTTPS,
frame-ancestorsprevents embedding the site in an attacker's frames,nosniffprevents MIME type sniffing.ACAO: *on private APIs is, on the contrary, dangerous.43. How do you send analytics events efficiently?
Correct answer: Queue them, send in batches and flush when the page is hidden
Batching reduces the number of requests and the load on the main thread. On
visibilitychangetohidden, the remainder is sent viasendBeacon. User consent (cookie consent) must be respected.44. Why can returning
totalCountin every list response be expensive?Correct answer: An exact
COUNT(*)with filters loads the databaseAn infinite feed doesn't need an exact number -
hasNextPageis enough. If the number matters, use an approximate estimate, cache the count, or compute it separately and less often.45. How does an API Gateway differ from a BFF?
Correct answer: A gateway is shared; a BFF serves one client
A gateway handles cross-cutting concerns for all clients. A BFF aggregates and adapts data to the needs of a specific interface (web, mobile app). In real systems they often coexist.
46. How do you update the client cache after a mutation so the user sees the changes?
Correct answer: Invalidate queries or update the cache
Key-based invalidation (
invalidateQueries, RTK Query tags) refetches fresh data; if the server returned the updated object, it's written into the cache directly without an extra request. On the Next.js server the equivalent isupdateTag/revalidatePath.47. What is the back/forward cache and how do you avoid breaking it?
Correct answer: A page snapshot for instant "back";
unloadandno-storeget in the waybfcache stores a snapshot of the page with its JS state, so the "Back" button opens it instantly.
unloadhandlers,Cache-Control: no-storeand open connections can disqualify a page from this optimization. Usepagehideandvisibilitychangeinstead ofunload.48. How do you handle an access token expiring while the user is working?
Correct answer: Intercept 401, refresh the token once and retry pending requests
Several parallel requests may get 401 at the same time - the refresh must run once (a shared promise), while the other requests wait for it and are retried. If the refresh fails, log out while preserving drafts.
49. Why is search for large catalogs done on the server rather than by filtering on the client?
Correct answer: Millions of records can't be loaded into the browser
Server-side search engines (Elasticsearch, Meilisearch, PostgreSQL full-text search) provide relevance, typo tolerance and facets. Client-side filtering is appropriate for hundreds to thousands of already loaded records.
50. How do you manage focus when opening a modal in an SPA?
Correct answer: Move focus inside, trap it and restore it after closing
Without focus management, keyboard and screen reader users get lost. The native
<dialog>withshowModal()does most of the work. At the system level, this is built into the design system's base components.51. How do
Cache-Control: no-cacheandno-storediffer?Correct answer:
no-cacherevalidates;no-storeforbids storingno-cachewith an ETag still saves bandwidth through304. Useno-storefor sensitive data like banking pages.52. What does
Cache-Control: privatemean for a CDN?Correct answer: Only the user's browser may cache the response
Use
privatefor personalized responses so one user's data isn't served to another from a shared cache.53. When does the browser send a CORS preflight request, and how can you avoid it?
Correct answer: For "non-simple" requests; a same-origin API avoids it
The extra
OPTIONSround trip adds latency.Access-Control-Max-Agelets browsers cache the preflight result.54. What do
SameSite=LaxandSameSite=Strictcookies change?Correct answer: They restrict cookies on cross-site requests
Lax(the default in modern browsers) blocks most CSRF while keeping links from other sites logged in.NonerequiresSecure.55. What is IDOR, and how is it prevented?
GET /api/invoices/1043 // user changes the id to 1044Correct answer: A missing object-level access check on the server
Unguessable ids reduce enumeration but don't replace authorization checks on every object.
56. How does
PATCHdiffer fromPUT?Correct answer:
PATCHchanges only part of a resourcePUTis idempotent by definition;PATCHmay not be (e.g. "increment by 1"), which matters for retries.57. Why use a standard error format like RFC 9457 Problem Details?
{ "type": "/errors/out-of-stock", "title": "Out of stock", "status": 409, "detail": "Only 2 left" }Correct answer: Clients can handle all errors uniformly
Consistent shapes let the frontend map
typeto user messages and field errors without per-endpoint code.58. How should a client react to
429 Too Many Requestswith aRetry-Afterheader?Correct answer: Wait at least the indicated time before retrying
Respecting
Retry-After(and backoff) avoids making the overload worse. The UI can show a short "try again" message.59. What does
<link rel="preconnect">give you?Correct answer: It opens the connection to an origin early
Use it for a few critical origins (CDN, API). Too many preconnects waste resources.
60. What does
103 Early Hintsallow?Correct answer: Sending
Linkhints before the final responseIt uses the server's "think time" while generating HTML. HTTP/2 server push, by contrast, was removed by browsers.
61. Which service worker caching strategy fits which resource?
Correct answer: Cache-first for static, network-first for data
Choosing per resource type balances speed, freshness and offline support.
62. What does Background Sync help with in an offline-capable app?
Correct answer: Replaying queued requests once back online
Browser support varies, so apps also keep their own queue (e.g. in IndexedDB) and retry on the
onlineevent.63. When should heavy computation move to a Web Worker?
Correct answer: When it would block the main thread
Workers run in parallel but can't touch the DOM; data is passed via messages (or transferable objects).
64. How should a global app handle dates and times?
Correct answer: Store UTC; convert to local time for display
Formatted strings are ambiguous across locales.
Intl.DateTimeFormathandles display per user.65. How does synthetic monitoring differ from real user monitoring (RUM)?
Correct answer: Synthetic uses scripted checks; RUM uses real users
Synthetic tests catch outages and regressions even with no traffic; RUM shows the real distribution of devices and networks.
66. How do SLI, SLO and SLA differ?
Correct answer: Indicator, target for it, contract with consequences
SLOs are usually stricter than SLAs, so teams react before contractual penalties apply.
67. A page needs data from 6 microservices. What reduces chattiness for the client?
Correct answer: An aggregation layer, like a BFF or GraphQL
Server-side calls are faster within the data center and the client's latency cost is paid once.
68. Why should a webhook endpoint respond quickly and process the event asynchronously?
Correct answer: Providers time out and retry slow endpoints
Store the event, return
2xx, then process it in a worker - idempotently, because retries still happen.69. How do liveness and readiness probes differ?
Correct answer: Liveness: restart it? Readiness: send it traffic?
During startup or a dependency outage, an instance can be alive but not ready; restarting it wouldn't help.
70. What do GraphQL persisted queries give you?
Correct answer: Clients send a query id instead of the full text
An allowlist also blocks arbitrary expensive queries from attackers.
71. How do you announce asynchronous updates (e.g. "3 new messages") to screen reader users?
Correct answer: Render the message in an
aria-liveregionThe live region must exist in the DOM before the update. Don't overuse
assertive, it interrupts users.72. Why can sticky sessions on a load balancer cause problems?
Correct answer: Uneven load, and lost sessions when a server dies
Stateless app servers (state in Redis/database/token) can be added, removed and restarted freely.
73. How should secrets (API keys, DB passwords) be managed in a deployment?
Correct answer: Inject them at runtime from a secrets manager
Leaked secrets in Git history persist after deletion; secret scanning in CI catches mistakes early.
74. Why can an unbounded
GET /api/items(no limit) become an incident?Correct answer: Responses grow huge as the data grows
Server-side limits protect against both accidental growth and abuse.
75. What is a key frontend concern when designing a large multi-step form (wizard)?
Correct answer: Persisting progress and validating per step
Users leave and come back; drafts in storage or on the server prevent frustration on long forms.