KatInterview

Building Robust Autocomplete Query Management

Data Structure DesignModel answer
MediumModel answerData Structure Designasynccachingstate-management

Last updated

Design and implement the query-handling layer for an autocomplete component with debouncing, retry logic, response ordering, and result caching.

You're building the query coordination layer for an autocomplete search box. The UI component is already built—your job is to implement the logic that manages when queries are sent, how responses are handled, and how results are stored.

Your implementation must handle:

Requirements

1. Query Debouncing

Don't send a request immediately when the user types. Wait until they pause typing for a short period (e.g., 300ms). If the input becomes empty, clear the suggestions without making any network call.

2. Response Ordering

Network responses can arrive in any order. A slow query for "ca" might return after a fast query for "cat". Ensure that stale results never overwrite fresh ones—only the most recent query's results should be displayed.

3. Failure Recovery

When a request fails, distinguish between errors worth retrying (network timeouts, 5xx server errors) and those that aren't (4xx client errors). For transient failures, retry with exponential backoff, but limit the number of attempts. If the user types a new query, abandon any in-progress retry sequence.

4. Result Caching

Store successful results keyed by normalized query text (case-insensitive, trimmed). Define policies for:

  • Maximum cache size
  • How long results stay fresh
  • Whether to show cached results immediately while fetching updated data in the background

What to Address

Your solution should cover:

  • Cleanup of timers and pending operations when queries change or the component unmounts
  • Preventing race conditions where an old response overwrites a newer one
  • Retry backoff strategy with randomization to avoid thundering herd problems
  • Cache key normalization and eviction policy when capacity is reached
  • How cached data interacts with loading states
  • Testing approach for time-dependent behavior

Hints

Hint 1

Track a generation counter or request ID that increments with each new query to identify which response is most recent

Hint 2

Use AbortController to cancel in-flight requests when a new query starts, and clearTimeout to cancel pending debounce and retry timers

Hint 3

For caching, normalize query strings (trim and lowercase) as keys, store timestamps with each entry, and use an LRU eviction policy when the cache fills up