Design a search autocomplete API that is fast, rate-limited, accessible, and safe from query injection.
Paytm · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, ASP.NET Core, Authentication & Security
Community answers
Posted by wasAsked editorial collection
Debounce input, cancel the previous request, require a sensible minimum length, and return a small ranked result set. The server must still validate and bound every query.
Example:
using var request = new HttpRequestMessage(HttpMethod.Get,
$"api/search?q={Uri.EscapeDataString(query)}");
var results = await http.SendAsync(request, ct);
On the server, use a normalized searchable column or a search engine rather than leading-wildcard scans at scale. Filter tenant data by authenticated RestaurantId and OutletId, index the search pattern, and return only display fields. Protect against stale UI responses by cancellation or sequence numbers; add rate limiting, keyboard accessibility, empty/loading/error states, and telemetry for latency and zero-result queries.
Backbencher Developer · · 0 likes
Autocomplete must answer in well under 100 ms, so it needs a purpose-built design.
Data and querying
- Use a prefix-friendly index: a search engine (Elasticsearch/OpenSearch with edge n-grams or completion suggesters, Azure AI Search suggesters) or, for small data, a database index on a normalized column with LIKE 'term%'.
- Avoid LIKE '%term%' on large tables because it cannot use a normal index.
- Return only a handful of fields and the top 5–10 suggestions, ranked by popularity.
Safety from injection
- Always use parameterized queries (EF Core LINQ or SqlParameter); never concatenate user input into SQL or search DSL strings.
- Escape LIKE wildcards (% and _) in user input.
- Validate length (for example 2–100 characters) and normalise whitespace and case.
Performance
- Cache popular prefixes in memory or Redis for a short time.
- Add a request timeout and CancellationToken so abandoned requests stop work.
- On the client, debounce input by about 200–300 ms, require a minimum length, and cancel in-flight requests with AbortController when the user keeps typing.
Rate limiting
- Use a token-bucket limiter per user or IP that allows bursts while typing but blocks scraping, and return 429 with Retry-After.
Accessibility (often forgotten in interviews)
- Follow the WAI-ARIA combobox pattern: an input with role="combobox", aria-expanded and aria-controls, a listbox of options, and aria-activedescendant for the highlighted item.
- Support keyboard navigation (arrow keys, Enter, Escape) and announce result counts with a polite live region.
- Do not move focus away from the input while the user types.
Also protect privacy: do not suggest other users' private data, and filter suggestions by the caller's permissions or tenant.