Building Robust Autocomplete Query Management
Data Structure DesignModel answerLast 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
This problem tests your ability to manage complex asynchronous state with multiple interacting concerns: timing, cancellation, ordering, error handling, and data persistence.
Part 1: Debouncing Input
The core pattern is maintaining a single active timer that gets reset on every keystroke:
let debounceTimer = null;
function handleInput(query) {
if (debounceTimer) clearTimeout(debounceTimer);
if (query.trim() === '') {
clearSuggestions();
return;
}
debounceTimer = setTimeout(() => {
fetchSuggestions(query);
}, 300);
}
function cleanup() {
if (debounceTimer) clearTimeout(debounceTimer);
}
Key considerations:
- Empty input must clear suggestions synchronously, not schedule a fetch
- Always clean up the timer on unmount to prevent memory leaks
- For testing, inject
setTimeout/clearTimeoutor use Jest's fake timers rather than hardcoding delays
Part 2: Handling Out-of-Order Responses
Use a monotonically increasing counter to tag each query:
let currentGeneration = 0;
function fetchSuggestions(query) {
const generation = ++currentGeneration;
const controller = new AbortController();
fetch(buildUrl(query), { signal: controller.signal })
.then(response => response.json())
.then(data => {
if (generation === currentGeneration) {
updateSuggestions(data);
}
// Silently ignore stale responses
});
return controller;
}
Alternative approaches:
- Store the exact query string and compare it before updating (works but fails if user types "cat" → "dog" → "cat")
- Use
AbortControllerto cancel old requests entirely (better for bandwidth, but still need generation check since cancellation isn't instant)
State transitions:
- Set
loading = truewhen starting a fetch - Only set
loading = falseif the completing request matches the current generation - Same rule applies to error states
Part 3: Retry Logic with Backoff
Classify errors and retry only transient failures:
function isTransient(error) {
if (error.name === 'AbortError') return false;
if (error.status >= 400 && error.status < 500) return false;
return true; // Network errors, 5xx, timeouts
}
async function fetchWithRetry(query, generation, maxAttempts = 3) {
let attempt = 0;
while (attempt < maxAttempts) {
const controller = new AbortController();
try {
const response = await fetch(buildUrl(query), {
signal: controller.signal
});
return response.json();
} catch (error) {
if (!isTransient(error) || generation !== currentGeneration) {
throw error;
}
attempt++;
if (attempt >= maxAttempts) throw error;
// Exponential backoff: 200ms, 400ms, 800ms with jitter
const delay = 200 * Math.pow(2, attempt - 1);
const jitter = delay * 0.3 * Math.random();
await sleep(delay + jitter, generation);
}
}
}
function sleep(ms, generation) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
if (generation === currentGeneration) resolve();
else reject(new Error('Cancelled'));
}, ms);
// Store timer for cleanup
currentRetryTimer = timer;
});
}
Why jitter matters: Without randomization, all failed requests retry at exactly the same intervals, creating traffic spikes that can overwhelm a recovering server.
Part 4: Caching Strategy
Implement a TTL-based LRU cache:
class QueryCache {
constructor(maxSize = 50, ttlMs = 5 * 60 * 1000) {
this.cache = new Map();
this.maxSize = maxSize;
this.ttlMs = ttlMs;
}
normalize(query) {
return query.trim().toLowerCase();
}
get(query) {
const key = this.normalize(query);
const entry = this.cache.get(key);
if (!entry) return null;
if (Date.now() - entry.timestamp > this.ttlMs) {
this.cache.delete(key);
return null;
}
// Move to end for LRU
this.cache.delete(key);
this.cache.set(key, entry);
// Return a copy to prevent mutation
return { ...entry, results: [...entry.results] };
}
set(query, results) {
const key = this.normalize(query);
if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
// Evict oldest (first) entry
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(key, {
results: [...results],
timestamp: Date.now()
});
}
}
Stale-while-revalidate pattern: When a cached entry exists, immediately show it to the user while fetching fresh data in the background:
const cached = cache.get(query);
if (cached) {
updateSuggestions(cached.results, { stale: true });
}
fetchSuggestions(query); // Updates with fresh data when complete
Complexity Analysis
- Time per query: O(1) for cache lookup, O(n) for network request where n is response size
- Space: O(k × m) where k is cache size and m is average result count per query
- Debounce overhead: Constant per keystroke (just timer management)
Common Mistakes
- Not canceling timers on unmount: Causes "setState on unmounted component" warnings and memory leaks
- Forgetting empty input edge case: Sending a request for "" wastes bandwidth and may cause errors
- Retry on client errors: 400-level responses indicate bad input, not transient failure
- Shared cache mutations: Returning cached arrays directly allows external code to modify cached data
- No generation check: Relying solely on cancellation—responses can still complete if cancellation arrives late
- Missing jitter: Synchronized retries create thundering herd problems under load
Testing Strategy
Use fake timers and mock fetch:
- Advance timers to test debounce without real delays
- Control response order to verify out-of-order handling
- Mock Date.now() to test TTL expiration
- Verify cleanup functions run on unmount