How-To Guide

How to Implement Search Autocomplete

Serve prefix suggestions in milliseconds with an indexed prefix structure, client debouncing and a ranking that favours useful results.

On this page

  1. Introduction
  2. What Autocomplete Needs
  3. Prefix Matching with an Index
  4. Debouncing and Cancelling on the Client
  5. Ranking Suggestions
  6. Handling Typos and Fuzziness
  7. Caching and Rate Limiting
  8. Conclusion

Introduction

Autocomplete feels instant when it works and broken when it lags, because the user types faster than a slow request can return. A suggestion list must appear within a few hundred milliseconds of the last keystroke, which rules out a full-text search on every keystroke and demands a structure built for prefix lookup. This article covers the index that makes prefix matching fast, the client behaviour that avoids a request per keystroke, how to rank suggestions so the useful ones come first, and how to handle typos and cache the results.

What Autocomplete Needs

Autocomplete answers one question quickly: given what the user has typed so far, what are the most likely completions. That is a prefix query, not a relevance query, and it operates on a small result set. The requirements are latency, because the query runs on every keystroke; freshness, because new items should appear; and ranking, because the top few suggestions are the ones the user will pick.

A full-text search engine on every keystroke is the wrong tool: it is built for relevance over many terms and is too slow per keystroke at scale. A dedicated prefix index, or a search index configured for completion, is what keeps the response within the budget.

Prefix Matching with an Index

A trie or a prefix index maps a prefix to the completions under it. In a relational database, a B-tree index on the text column supports a prefix range scan with a LIKE pattern, as long as the index uses the right operator class and the collation is suitable; a case-insensitive index requires a functional index or the citext type. The query returns rows whose text starts with the prefix, ordered by the index, and a limit keeps it small.

-- Case-insensitive prefix index for completions.
CREATE EXTENSION IF NOT EXISTS citext;
CREATE INDEX idx_products_name_prefix ON products (name citext_pattern_ops);

-- Prefix query: uses the index for a range scan on the prefix.
SELECT name, popularity
FROM products
WHERE name ILIKE $1 || '%'          -- $1 is the escaped prefix
ORDER BY popularity DESC, name
LIMIT 8;

-- Escape wildcards in the user input before using it as a prefix,
-- or a typed % matches everything.
--   prefix = prefix.replace(/[%_\\]/g, '\\$&')

Debouncing and Cancelling on the Client

The client should not fire a request on every keystroke. Debounce so a request is sent only after the typing pauses, and cancel the in-flight request when the user types again, so a slow earlier response cannot arrive after a faster later one and show stale suggestions. Debounce and cancellation together are what make the list feel responsive without hammering the server.

function createAutocomplete(input, onSuggestions) {
  let timer, controller, lastQuery = '';
  input.addEventListener('input', () => {
    clearTimeout(timer);
    controller?.abort();                       // cancel the previous request
    const q = input.value.trim();
    if (q.length < 2) { onSuggestions([]); return; }
    timer = setTimeout(async () => {
      controller = new AbortController();
      try {
        const res = await fetch('/suggest?q=' + encodeURIComponent(q), {
          signal: controller.signal,
        });
        const data = await res.json();
        if (q === lastQuery) return;           // ignore a stale response
        lastQuery = q;
        onSuggestions(data.items);
      } catch (err) {
        if (err.name !== 'AbortError') onSuggestions([]);
      }
    }, 120);                                   // debounce delay
  });
}

Ranking Suggestions

The top suggestions determine whether the feature helps. Rank by a blend of match quality and usefulness: an exact prefix match outranks a match later in the string; a popular item outranks a rare one; and a category or recent item may be boosted when the context supports it. Keep the ranking signal cheap to compute, because it runs on every keystroke.

Precompute the popularity score so the query does not have to aggregate on the fly, and store it in a column the prefix index can order by within the limited set. A query that sorts by a computed popularity at request time is slower than one that reads a stored score. Blend the signals into a single score updated on a schedule so the query stays simple.

Handling Typos and Fuzziness

Users mistype. A prefix index handles correct prefixes but not a misspelled one, so a fuzzy layer helps: an edit-distance match, a phonetic key, or a trigram index that finds strings sharing character sequences. Fuzzy matching is more expensive, so apply it only when the exact prefix returns too few results, or run it on a smaller candidate set.

Trigram indexes are a common middle ground: they match on shared three-character sequences and support a similarity threshold. They are slower than a pure prefix index but handle misspellings and mid-word matches. Use fuzzy matching as a fallback rather than the primary path, so the common case stays fast.

Caching and Rate Limiting

Autocomplete traffic is high and repetitive, so cache the results. A short-lived cache keyed by the prefix serves the popular prefixes from memory and shields the database from the request-per-keystroke pattern, even after debouncing. Keep the TTL short, since suggestions should reflect recent data, and invalidate on a large content change.

Rate limit the endpoint, because it is easy to abuse and expensive to serve at volume. A per-client limit protects the database from a script that iterates over prefixes. Combine the cache and the limit so the common case is served cheaply and the abusive case is refused, which keeps the feature available to real users.

Conclusion

Autocomplete is a prefix query that must return within a few hundred milliseconds. Index the text for a case-insensitive prefix range scan, debounce and cancel on the client so a slow response cannot overwrite a newer one, rank by a stored score blending match quality and popularity, and fall back to a fuzzy match only when the exact prefix finds too little. Cache the popular prefixes and rate limit the endpoint. Then suggestions appear as the user types and never show a result from an abandoned keystroke.

Sources: PostgreSQL: pattern matching and indexes, PostgreSQL: pg_trgm, MDN: AbortController.

FAQ

Why not use a full-text search engine for autocomplete?
Full-text search is built for relevance over many terms and is slower per query. Autocomplete needs a small result for a prefix within milliseconds on every keystroke, which a prefix index or a completion-tuned index serves far more cheaply.
Why cancel the in-flight request on the client?
Because a slow earlier response can arrive after a faster later one and overwrite the newer suggestions with stale ones. Debouncing reduces the request count and cancelling plus ignoring stale responses keeps the list consistent with what the user typed.

Related Examples