Build a Type-Ahead Catalog Lookup with Cancellation and Caching
Data Structure DesignModel answerLast updated
Build an accessible type-ahead lookup that delays requests, discards outdated responses, remembers past queries, supports keyboard control, and copes with errors.
Task
Build a type-ahead lookup box for an online store catalog. As the shopper types, the component asks a backend for matching items and shows at most 10 of them in a dropdown. It has to stay responsive and correct even when network latency varies from request to request.
You may use React (a component or a custom hook), or plain TypeScript/JavaScript.
Interface
interface Suggestion {
id: string;
title: string;
category: string;
}
interface SearchBoxProps {
fetchSuggestions: (query: string, signal: AbortSignal) => Promise<Suggestion[]>;
onSelect: (item: Suggestion) => void;
debounceDelayMs?: number; // default 300
maxResults?: number; // default 10
}
Required behavior
- Delayed requests. Only call the backend once the user has paused typing for
debounceDelayMs(300 ms by default). Every new keystroke restarts the wait. - Outdated responses. A slow response for an old query must never overwrite the results of a newer query. Cancel the old request, ignore its result, or both.
- In-memory cache. Keep results of recent queries so that repeating a query (for example after backspacing) is served instantly with no network call.
- Keyboard control.
ArrowDown/ArrowUpmove the highlighted suggestion,Enterpicks the highlighted one, andEscapecloses the dropdown. - Accessibility. Follow the WAI-ARIA combobox pattern:
role="combobox",aria-autocomplete="list",aria-expanded, andaria-activedescendantpointing to the highlighted option's DOM id. - Visible states. Show distinct loading, empty-result, and error states.
Example flow
- The user types
s, thenshoeswithin 200 ms. The first timer is discarded; 300 ms after the last keystroke one request goes out with anAbortSignal, and a loading indicator is shown until it returns. - The user presses
ArrowDown. The first suggestion (index 0) is highlighted andaria-activedescendantreferences its id. - The user presses
Enter.onSelect(item)fires, the dropdown closes, and the input shows the chosen title.
Edge cases to handle
- Empty or whitespace-only input clears the suggestions and sends no request.
- Typing
apple, backspacing toapp, then typingappleagain must show theappleresults immediately from the cache, with no new call. - A network failure must not erase or alter what the user has typed.
What to deliver
Explain your design, then provide code. Discuss complexity and the trade-offs you made (for example, how you handle cache size and selection side effects).
Hints
Hint 1
Treat the query text as the single source of truth. Each change should invalidate the previous timer and the previous in-flight request, then decide: blank, cached, or schedule a new fetch.
Hint 2
In React, a useEffect that creates one timer and one AbortController per run, and tears both down in its cleanup, gives you debouncing, cancellation, and unmount safety with one mechanism. Still check whether the controller was aborted after awaiting, in case the backend ignores the signal.
Hint 3
Selecting an item changes the input text, which would normally trigger another fetch. Think about how to suppress exactly that one fetch without swallowing the user's next keystroke. Also consider normalizing cache keys and only caching successful responses.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Model the component as a small state machine driven by one value: the query string. Every change to it does three things in order:
- Invalidate whatever the previous query left behind: a pending timer and an in-flight request.
- Short-circuit if the normalized query is blank (reset everything) or already cached (render immediately, no timer).
- Schedule a fetch after
debounceDelayMs, carrying anAbortSignalthat the next change will trigger.
In React, useEffect maps onto this directly. Each effect run owns one timer and one AbortController; its cleanup (run on the next query change or on unmount) calls clearTimeout and controller.abort(). One mechanism covers debouncing, cancellation, and not updating state after unmount.
DOM focus never leaves the <input>. The highlighted option is just an index in state, exposed to assistive tech through aria-activedescendant.
Why it is correct
- Debounce: a keystroke inside the window runs the previous cleanup, which clears the timer. A request exists only if the input was stable for the full delay.
- Races: two layers of defense. Aborting cancels the network call; and after
await, the code checkscontroller.signal.abortedbefore touching state. This still protects you if the backend ignores the signal. Only the latest effect run has an un-aborted controller, so only the latest query can write results. - Cache: keys are normalized with
trim().toLowerCase(). The sequenceapple->app->applehits the cache on the way back, synchronously. Cache only successful responses so a transient failure is never pinned. - Errors: a failure changes only
status; theinputstate is never modified.AbortErroris swallowed, not shown. - Selection: setting the input to the chosen title would trigger a fetch. A one-shot
skipRefsuppresses that, and is set only when the text actually changes (otherwise it would eat the next real keystroke).
Complexity
- Per keystroke: O(1) for timer and controller management.
- Cache get/set: O(1) using a
Map's insertion order as an LRU (delete and re-insert to refresh recency; evict the first key when over capacity). - Render: O(k), k <=
maxResults. - Space: O(C * k) for capacity C.
Implementation (React + TypeScript)
import { useEffect, useId, useRef, useState, KeyboardEvent } from "react";
type Status = "idle" | "loading" | "success" | "error";
class LRUCache<V> {
private map = new Map<string, V>();
constructor(private capacity = 50) {}
get(key: string): V | undefined {
const v = this.map.get(key);
if (v !== undefined) { this.map.delete(key); this.map.set(key, v); }
return v;
}
set(key: string, v: V): void {
this.map.delete(key);
this.map.set(key, v);
if (this.map.size > this.capacity) {
this.map.delete(this.map.keys().next().value as string);
}
}
}
export function SearchBox({
fetchSuggestions, onSelect, debounceDelayMs = 300, maxResults = 10,
}: SearchBoxProps) {
const [input, setInput] = useState("");
const [items, setItems] = useState<Suggestion[]>([]);
const [status, setStatus] = useState<Status>("idle");
const [open, setOpen] = useState(false);
const [active, setActive] = useState(-1);
const cacheRef = useRef(new LRUCache<Suggestion[]>(50));
const fetchRef = useRef(fetchSuggestions);
fetchRef.current = fetchSuggestions; // latest fn without re-running the effect
const skipRef = useRef(false);
const listId = useId();
const optionId = (i: number) => `${listId}-opt-${i}`;
useEffect(() => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = () => { clearTimeout(timer); controller.abort(); };
setActive(-1);
if (skipRef.current) { skipRef.current = false; return cleanup; }
const q = input.trim().toLowerCase();
if (!q) { setItems([]); setStatus("idle"); setOpen(false); return cleanup; }
const cached = cacheRef.current.get(q);
if (cached) { setItems(cached); setStatus("success"); return cleanup; }
timer = setTimeout(async () => {
setStatus("loading");
try {
const res = (await fetchRef.current(q, controller.signal)).slice(0, maxResults);
if (controller.signal.aborted) return; // stale response
cacheRef.current.set(q, res);
setItems(res);
setStatus("success");
} catch {
if (controller.signal.aborted) return; // abort or stale failure
setItems([]);
setStatus("error"); // input text untouched
}
}, debounceDelayMs);
return cleanup;
}, [input, debounceDelayMs, maxResults]);
const select = (item: Suggestion) => {
if (item.title !== input) skipRef.current = true;
setInput(item.title);
setOpen(false);
setActive(-1);
onSelect(item);
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
const n = items.length;
switch (e.key) {
case "ArrowDown":
e.preventDefault();
if (!open) { setOpen(n > 0); return; }
if (n) setActive(i => (i + 1) % n);
break;
case "ArrowUp":
e.preventDefault();
if (open && n) setActive(i => (i <= 0 ? n - 1 : i - 1));
break;
case "Enter":
if (open && active >= 0 && active < n) {
e.preventDefault();
select(items[active]);
}
break;
case "Escape":
setOpen(false);
setActive(-1);
break;
}
};
// Render: <input role="combobox" aria-autocomplete="list"
// aria-expanded={open && input.trim() !== ""} aria-controls={listId}
// aria-activedescendant={active >= 0 ? optionId(active) : undefined} .../>
// plus <ul role="listbox" id={listId}> with <li role="option" id={optionId(i)}
// aria-selected={i === active} onMouseDown={e => e.preventDefault()}
// onClick={() => select(item)}>, and a polite live region for status text.
}
Edge cases
- Whitespace-only input: clears results, closes the list, no request.
- Stale or failed old responses: dropped through the
abortedcheck, never shown as errors. - Zero results: show a "No results" message; announce it in a polite
aria-liveregion so screen-reader users get feedback too. - Mouse selection: call
preventDefaultonmousedownfor options, otherwise the input'sblurcloses the list beforeclickregisters. - Unstable
fetchSuggestionsprop: keep the latest function in a ref so an inline arrow function does not retrigger the effect each render. - Unmount mid-request: cleanup aborts it, so no state update happens afterward.
Trade-offs and common mistakes
- Only debouncing, no staleness guard: a slow response for
shocan land aftershoesand overwrite it. Debounce reduces traffic; it does not order responses. - Relying only on
abort(): if the fetcher ignores the signal, the promise can still resolve. Always check the signal before writing state. - Caching errors: one blip would then stick for that query. Cache successes only.
- Unbounded cache: grows forever in a long session; use an LRU (or TTL if results go stale, e.g. prices or stock).
- Un-normalized keys:
Apple,apple, andAPPLEwould produce three requests. - Forgetting the selection side effect: filling the input with the chosen title re-triggers a search and reopens the list.
- Moving DOM focus into the list: breaks typing. Keep focus on the input and use
aria-activedescendant.
A possible extension is prefix-aware caching (reuse the app results to filter locally for appl when the backend is known to be prefix-based), at the cost of correctness risk if ranking differs server-side.