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
50

Frontend System Design · Lesson 50 of 86 · 4 min

Batching, Throttling and Debouncing API Calls

These are your core tools for managing network requests. In an interview, knowing which to use and why is non-negotiable.

Debounce vs. Throttle: The classic trade-off

Both techniques control how often a function executes, but they solve different problems. Mixing them up is a common red flag.

Debounce groups a burst of events into a single one. The function only runs after a specific period of inactivity. Think of an elevator door: it only closes after everyone has stopped trying to get in.

Use debounce when you only care about the final state. The classic use case is a typeahead search input. You don't want to fire an API request for every keystroke ("a", "ap", "app", "appl"); you want to fire one request for "apple" after the user has paused typing.

Throttle ensures a function runs at a maximum frequency. It guarantees execution at regular intervals, no matter how many times the event is fired. Think of a game loop running at 60 frames per second; it doesn't matter how fast the hardware is, the screen won't update more than 60 times a second.

Use throttle for continuous events where you need periodic updates. Examples include tracking scroll position for an infinite scroll feature, handling window resize events, or reporting mouse movement. You want updates while the action is happening, just not thousands of them.

In an interview, it's this simple:

  • If the problem involves reacting to a user's pause (e.g., "search input"), your answer is debounce.
  • If the problem involves handling a continuous stream of events (e.g., "scrolling", "resizing"), your answer is throttle.

Batching: Reducing network chatter

Batching is different. It's not about rate-limiting a single action; it's about bundling multiple distinct actions into a single network request.

Instead of sending ten small analytics events in ten separate API calls, you queue them up and send them all at once. This reduces HTTP overhead (fewer TCP handshakes, fewer headers) and can ease server load.

The trade-off is latency for the individual events. The first event you queue has to wait for either the batch to fill up or a timeout to expire. This is fine for non-critical data like analytics, but unacceptable for an action where the user is waiting for a response, like submitting a form.

The trap: What happens if the user closes the tab before the batch is sent? You lose the data. A robust implementation listens for the pagehide or visibilitychange events to flush the queue before the page unloads. For this, navigator.sendBeacon() is the right tool, as it's designed for this exact "fire-and-forget" scenario and won't be cancelled by page navigation.

How to implement debounce from scratch

You will almost certainly be asked to write a debounce function in a coding interview. You need to be able to do it from memory. The core is a closure that holds a reference to a timer.

function debounce<T extends (...args: any[]) => void>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: ReturnType<typeof setTimeout> | null = null;

  return function(this: ThisParameterType<T>, ...args: Parameters<T>) {
    // Preserve the `this` context from the call site.
    const context = this;

    // If the debounced function is called again, clear the previous timer.
    if (timeoutId) {
      clearTimeout(timeoutId);
    }

    // Set a new timer. The function will execute after `delay` ms of inactivity.
    timeoutId = setTimeout(() => {
      func.apply(context, args);
    }, delay);
  };
}

Key points to explain during the interview:

  1. Closure: The returned function has access to the timeoutId variable from its parent scope. This is how the timer state persists between calls.
  2. clearTimeout: This is the heart of the debounce. Every new call cancels the previously scheduled execution.
  3. apply(context, args): This ensures the original function is called with the correct this context and all of its arguments. A naive func(...args) would lose the context.

The follow-up question: "How do you prevent memory leaks in a React component using this?"

In a class component, you'd clear any pending timer in componentWillUnmount. In a functional component, you return a cleanup function from useEffect. This is critical. If the component unmounts before the timer fires, you need to cancel it to prevent it from trying to update a non-existent component.

Choosing the right delay

An interviewer might ask, "What's a good delay for a search input?" There is no single right answer. It's a trade-off between responsiveness and efficiency.

  • Too short (e.g., 50ms): You'll still make many unnecessary API calls for fast typists. The UI might feel busy and flicker.
  • Too long (e.g., 1000ms): The application feels sluggish. The user stops typing and waits a full second for results to appear.

A reasonable starting point is 200-400ms. This range is short enough that it feels responsive to most users but long enough to batch keystrokes from an average typist. The important thing is to articulate the trade-off, not to state a magic number.

This diagram shows the logic for a debounced function. Each time the event fires, the timer is reset. The function only executes when the timer is allowed to complete.

Try it

Implement a throttle function from scratch. It's a different logic: instead of a timer you reset, you'll likely use a timestamp or a boolean flag to track whether you're in a "cooldown" period. Use it to log window.scrollY to the console, but no more than once every 200ms.

Next: Handling API Errors in the Frontend.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

REST and GraphQL for Frontend Engineers

Next

Handling API Errors in the Frontend