Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
78

Frontend System Design · Lesson 78 of 86 · 4 min

Integrating Backend Search Services

This isn't just about fetching data. It's about designing the contract, managing complex state, and articulating the trade-offs of a real-time UI feature.

When you're asked to design a typeahead search, the interviewer is testing your ability to think through the entire frontend system. They want to see how you handle user input, network requests, state management, and potential race conditions. A shallow answer that just mentions fetch and useState is a red flag.

Define the API Contract First

Before writing a line of client code, define the API. This forces clarity on what the frontend controls and what the backend provides. A well-defined contract is the foundation of a decoupled, maintainable system.

Your query parameters are the frontend's control panel. A robust search endpoint needs more than just a query string. You will need:

  • q: The user's search term.
  • page or offset: For pagination.
  • pageSize or limit: To control the number of results per page.
  • sortBy & sortOrder: For user-controlled sorting.
  • filters: A structured way to send faceted search criteria, often as a stringified JSON object or repeated query parameters (category=electronics&category=clothing).

The response payload should give the UI everything it needs to render the current view and the controls for other views. Don't make the client calculate metadata.

  • results: An array of search result items.
  • totalCount: The total number of matching documents, essential for calculating pagination.
  • totalPages: Math.ceil(totalCount / pageSize), calculated on the server.

In an interview, start here. When asked to design a search UI, begin by saying, "First, let's define the API contract." Sketch out the request and response shapes. This immediately shows you're thinking about system boundaries, not just a single component. It also lets you control the assumptions for the rest of the problem.

Manage All Search Parameters as a Single State Object

Avoid scattering search state across multiple useState hooks. A single state object, representing all possible API parameters, is easier to manage, update, and synchronize.

const [searchParams, setSearchParams] = useState({
  q: '',
  page: 1,
  sortBy: 'relevance',
  filters: {
    category: 'electronics'
  }
});

When a user types, changes a filter, or clicks a pagination button, you update this single object. This triggers a useEffect hook that re-runs the search. This pattern centralizes the logic for fetching data.

The trap: Forgetting the URL. If your search state lives only in component memory, the URL doesn't change. This breaks sharing, bookmarking, and the browser's back button. The URL is a form of state. Use the URLSearchParams API and your router's history management to keep the component state and the URL in sync. A change in the URL should update your state object, and an update to your state object should be reflected in the URL.

Orchestrate the Request-Response Flow

The core of the frontend logic is a useEffect hook that observes the searchParams object. This effect is responsible for the entire lifecycle of a single search request.

Here's the sequence:

  1. A user action (typing, clicking a filter) updates the searchParams state.
  2. The useEffect hook is triggered by this state change.
  3. Inside the effect, you start a debounced timer. If the effect re-runs before the timer fires, the old timer is cleared.
  4. When the timer fires, set a loading state to true.
  5. Make the API call, passing the searchParams.
  6. On success, update the results state and set loading to false.
  7. On failure, update an error state and set loading to false.

This flow is the minimum viable implementation for a good user experience. It provides visual feedback for loading and error states and protects your backend from being overwhelmed.

Prevent Race Conditions with AbortController

The trap: A fast user types "A", then "B". The request for "B" might return before the request for "A". If you just update state as responses arrive, the UI will show results for "B", then flicker and incorrectly show results for "A". This is a classic race condition.

The solution is to cancel the previous request whenever a new one is initiated. The AbortController API is designed for this. Create a new controller for each request inside your useEffect, and call its abort() method in the effect's cleanup function.

This demonstrates a deep understanding of asynchronous browser behavior and is a huge plus in an interview.

useEffect(() => {
  // Create a controller for this specific request
  const controller = new AbortController();

  const fetchData = async () => {
    if (!searchParams.q) return;
    try {
      // Pass the signal to your fetch call
      const data = await api.search(searchParams, { signal: controller.signal });
      setResults(data);
    } catch (error) {
      // Aborted requests throw an error; ignore it.
      if (error.name === 'AbortError') {
        console.log('Fetch aborted');
      } else {
        setError(error);
      }
    }
  };

  // Debounce the actual fetch
  const timerId = setTimeout(fetchData, 300);

  // The cleanup function runs when the effect re-triggers or the component unmounts
  return () => {
    clearTimeout(timerId);
    controller.abort(); // Abort the in-flight request
  };
}, [searchParams]); // Re-run effect when params change

This small block of code is more valuable to discuss than a hundred lines of UI boilerplate. It correctly handles debouncing, cancellation, and error states.

Try it

Take an existing project with a simple search input. Refactor it to manage all search parameters (query, page, filters) in a single state object. Then, use the URLSearchParams API to ensure that every change to this state object is reflected in the page URL, and vice-versa.

Next: We'll look at frontend-specific rendering challenges in the next lesson, "Choosing a Chart Library: D3, Chart.js, Recharts".

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Search Performance: Debouncing and Web Workers

Next

Choosing a Chart Library: D3, Chart.js, Recharts