Keep Autocomplete Fast as Your Dataset Grows
In this article
Autocomplete can slow down dramatically as your dataset grows, turning a snappy search into a laggy nightmare. This guide shows you practical, incremental strategies—from indexing and debouncing to server-side search—that keep suggestions instant even with millions of entries. You'll learn what to do before your data gets big, and how to fix it if it's already slow.
What You'll Need
- Access to your codebase (frontend and/or backend)
- Basic understanding of your current autocomplete implementation
- Optional: a profiling tool (browser dev tools, server logs)
Step-by-Step
- Measure the current bottleneck. Use your browser's network tab to see if the delay is on the client (rendering) or server (query time). If it's server-side, check database query logs for slow queries. If it's client-side, use the performance profiler to see if filtering or DOM updates are the issue.
- Add an index on the search column. If you're using a SQL database, create an index on the column you're searching. For example:
CREATE INDEX idx_name ON users (name);This turns a full table scan into a fast index lookup. - Limit the result set. Modify your query to return only the top N matches (e.g., 10 or 20). This reduces network payload and rendering time. In SQL:
SELECT name FROM users WHERE name LIKE 'query%' LIMIT 10; - Debounce the input. Add a debounce of 150–300ms so you don't fire a request on every keystroke. This cuts the number of queries dramatically. Example in JavaScript:
let timer; input.addEventListener('input', () => { clearTimeout(timer); timer = setTimeout(fetchSuggestions, 200); }); - Cache results. Store recent queries and their results in memory (or localStorage) to avoid repeated requests. Use a simple object keyed by the query string.
- Move to server-side search. If you're still filtering a large array on the client, move the search to the server. Send the query via an API endpoint that uses the database index and returns only a few results.
- Consider a dedicated search engine. For very large datasets (millions of rows), tools like Elasticsearch or Algolia are built for fast prefix search. They use inverted indexes and can return results in milliseconds.
- Use a trie or prefix tree (if client-side). If you must keep data on the client, build a trie structure that allows O(1) prefix lookups. This is more efficient than filtering an array with
startsWith. - Virtualize the suggestion list. If you're rendering many suggestions, use a virtual scrolling library (like react-window) to render only visible items. This keeps the DOM light.
- Optimize the database query. Use
LIKE 'prefix%'instead ofLIKE '%substring%'to leverage indexes. Avoid leading wildcards if possible. - Add a minimum character threshold. Only start searching after the user types 2–3 characters. This avoids returning too many results for a single letter.
- Profile and re-test. After each change, measure the response time again. Adjust limits and debounce as needed.
Common Mistakes
- Using
LIKE '%query%'with a leading wildcard. This prevents index usage and forces a full scan. - No debounce. Sending a request on every keystroke floods the server and causes lag.
- Returning too many results. Sending 1000 suggestions when the user only sees 10 wastes bandwidth and rendering time.
- Client-side filtering of a huge array. Filtering a 100k-item array on every keystroke will freeze the UI.
- Ignoring caching. Repeatedly fetching the same query is wasteful.
Tips
- Use a
prefixsearch (e.g.,LIKE 'term%') for autocomplete, not a contains search. - Consider using a database's built-in full-text search if it supports prefix matching.
- For high-traffic apps, add a CDN cache in front of your API.
- If using Elasticsearch, use the
prefixquery or edge n-grams for fast suggestions. - Keep the suggestion list short—5 to 10 items is usually enough.
Troubleshooting
Autocomplete is still slow after indexing. Check if the index is actually being used by running EXPLAIN on your query. If not, you may need a different index type (e.g., a covering index).
Debounce doesn't seem to help. Ensure you're not accidentally resetting the timer on every render. Use a ref or a closure to store the timer.
Server returns results fast, but UI still lags. The bottleneck is likely rendering. Use virtualization and reduce the number of DOM nodes.
Cache is growing too large. Implement a simple LRU (least recently used) eviction to keep only the most recent queries.
Search engine is overkill? If your dataset is under ~100k rows, a simple database index is often enough. Adding Elasticsearch adds operational complexity.
Frequently Asked Questions
Q: What is the best database index for autocomplete?
A: A B-tree index on the search column works for prefix searches. For case-insensitive search, use a functional index like LOWER(name).
Q: How many results should I return?
A: Typically 5–10. More than 20 is rarely useful and slows down rendering.
Q: Should I use a trie or a database?
A: For client-side datasets under ~10k items, a trie is fast. For larger datasets, use a database or search engine.
Q: Is debounce always necessary?
A: Yes, unless you're using a local dataset and the search is instant. Debounce reduces server load and improves perceived speed.
Q: How do I handle diacritics or accents?
A: Normalize the text before storing and searching (e.g., strip accents). This requires a normalized column or a search engine that supports it.
Q: What if my data changes frequently?
A: Use a cache with a short TTL, or invalidate the cache on data updates. For search engines, use near-real-time indexing.