wasAsked.

Design a search autocomplete API that is fast, accessible, rate-limited, and safe from injection.

Paytm · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Spring Boot, Authentication & Security

Community answers

Posted by wasAsked editorial collection

Design for speed first, then add protections. Search backend - Use an index built for prefix matching: Elasticsearch or OpenSearch with edge n-gram analyzers or completion suggesters, or PostgreSQL with a text_pattern_ops index for prefix LIKE queries (and the pg_trgm extension for fuzzy matching) when data is small. - Return the top 5–10 suggestions with only the fields needed (ID and label), ranked by popularity or relevance. - Cache popular prefixes in Redis or Caffeine with a short TTL. Spring Boot endpoint @GetMapping("/api/suggestions") public List<Suggestion> suggest(@RequestParam @Size(min = 2, max = 50) String q) { ... } - Validate length and characters; normalise case and whitespace. - Apply timeouts on the search client and fail fast with an empty list rather than hanging. Injection safety - Use parameterised queries (Spring Data derived queries, named parameters, or the Criteria API). Never concatenate input into SQL, JPQL or Elasticsearch query strings. - For LIKE, escape % and _ characters in user input. - For Elasticsearch, use structured queries (match_phrase_prefix, completion) via the Java client builders instead of query_string with raw user input, which allows special syntax. Rate limiting - Token bucket per user or IP using Bucket4j (with Redis for multiple instances) or at the API gateway (Spring Cloud Gateway's RequestRateLimiter). Allow short bursts for typing; return 429 with Retry-After when exceeded. Frontend behaviour - Debounce input (about 250 ms), require a minimum length, and cancel in-flight requests when the user types again (AbortController). - Cache recent results client-side. Accessibility - Implement the WAI-ARIA combobox pattern: input with role="combobox", aria-expanded, aria-controls and aria-autocomplete="list"; the suggestion list with role="listbox" and options with role="option"; aria-activedescendant for keyboard focus. - Full keyboard support (arrow keys, Enter, Escape), visible focus, and a polite live region announcing "5 suggestions available". Privacy and authorization - Only suggest data the user is allowed to see (tenant filtering), and do not leak other users' personal information through suggestions. Measure p95 latency and keep it well under 100 ms end to end.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics