# Design Search Autocomplete (Typeahead): Tries, Redis, Postgres

> How to design search autocomplete at scale: capacity arithmetic, a 100 ms latency budget, tries versus Postgres and Redis, decayed ranking, offline log aggregation, top-K caching and a debounced client.

URL: https://www.matthewswong.com/en/blog/design-search-autocomplete-typeahead/

- Author: Matthews Wong (https://www.matthewswong.com/en/about/)
- Published: 2026-10-10
- Updated: 2026-10-10
- Category: Backend

> **Key takeaway:** Design search autocomplete by precomputing the top ten suggestions for every query prefix offline from aggregated query logs, ranking them by time-decayed frequency, and serving them from Redis or a CDN by exact prefix key. The client debounces keystrokes and cancels stale requests, and the whole round trip targets about 100 milliseconds.

A product picker on a point-of-sale screen is the smallest autocomplete most developers build: type three letters, see matching items. It works on a few thousand rows with a LIKE query, and it keeps working until the list, the traffic or the typing speed grows enough that every keystroke becomes a database query.

This post is a design exercise, not a case study. Every number comes from stated assumptions with the arithmetic shown, or from a cited source, and none is a benchmark. It covers capacity, latency, the data structure, ranking, offline aggregation, caching and the client, ending with a decision checklist. Plain full-text search is covered in the PostgreSQL full-text search post, and the debounce hook basics in the React debouncing guide, so both stay brief here.

## How much traffic does search autocomplete generate?

Far more than the search it serves. Search is one request per submitted query, while typeahead can fire one per keystroke. Start with assumptions you can defend, then derive everything else. The block below assumes 5 million daily active users and shows why debouncing alone cuts request volume by 4.75 times.

Two conclusions follow. The read path must be a cheap key lookup, because 6,944 peak requests per second of ranking work would be absurd, and the search log is a modest 579 writes per second that a batch insert absorbs easily. The 80 percent cache hit figure is an assumption, but it works only because the URL carries nothing user-specific, a property the caching section protects.

## What latency budget should autocomplete hit?

Suggestions that arrive after the user has finished typing are noise, so the budget is tight. Nielsen Norman Group describes 0.1 second as the limit for a response that feels instantaneous, which makes 100 ms a reasonable target. Split it across the stages you control and see how much is left.

The slack is small, and the debounce delay is not inside it, because it elapses before the request leaves the browser. That is the real design tension: every millisecond of server work competes with the debounce you wanted to save requests. It is also the argument for precomputation, since a single key lookup leaves room for both.

## Trie, prefix index or Redis: which data structure should you use?

A trie stores strings by shared prefixes, so finding the node for a prefix costs time proportional to the prefix length, not the number of strings. Store the top ten suggestions on each node and a lookup is a walk plus a copy. The catch is that it lives in one process, so every instance needs the same build and a way to swap it. Compare it with the database-backed options.

| Approach | What it matches | Ranking | Main weakness |
| --- | --- | --- | --- |
| In-memory trie with top-K at each node | Exact prefix, cost grows with prefix length | Precomputed per node | Per-process memory; every instance needs the same build |
| Postgres B-tree with text_pattern_ops | Left-anchored LIKE such as ca% | ORDER BY score over every match | Short prefixes match huge row sets that must be sorted |
| Postgres pg_trgm with a GIN index | Anywhere in the string, plus typos via similarity | ORDER BY similarity, then score | Larger index; patterns with no extractable trigrams scan the whole index |
| Redis sorted set per prefix | Exact prefix key lookup | The score is the rank | An offline job must fill it; memory grows with prefix count |
| Redis ZRANGE BYLEX on one set | Left-anchored lexicographic range | Alphabetical only, not by popularity | Cannot rank, and all scores must be equal |

On one VPS I would begin in Postgres, because it is already running and a few hundred thousand queries fit comfortably. The PostgreSQL docs state that text_pattern_ops indexes support LIKE when the database is not in the C locale, and that pg_trgm indexes support LIKE, ILIKE and similarity searches that need not be left-anchored. Use the B-tree for plain prefixes and pg_trgm when you want typo tolerance.

The scale step is to stop querying and start looking up. Redis documents ZRANGE with BYLEX for lexicographic ranges, but only for members that share one score, which returns alphabetical order. Popularity ranking needs the other shape: one sorted set per prefix whose score is the rank, written by an offline job and read with a single ZREVRANGE.

> Cap prefix length, for example at 8 characters. Beyond that point users are narrowing a list they already see, so reuse the 8-character list and filter it in the app. The key space then stays bounded no matter how long a query someone types.

## How do you rank suggestions by frequency and recency?

Raw counts reward old giants: a query searched 1,000 times last month outranks one that is surging today. Weight each day's count by an exponential decay with a half-life you choose, and sum. The worked example uses a 7-day half-life and shows the order flipping.

The half-life is a product decision, not a constant. A short one makes trending topics surface fast and also lets a one-day spike displace steady favourites, while a long one is stable but slow. Add a minimum count before a query is eligible at all, which also removes one-off typos and rare personal queries.

## How do you build suggestions offline from query logs?

Never rank on the request path. Log submitted searches, aggregate them into daily counts per normalised query, and run a nightly job that scores each query, expands it into prefixes and keeps the top ten per prefix. In Postgres the whole job is one statement using generate_series and row_number.

The output feeds the Redis sets under a new version number, and a single SET flips the version pointer once the build is complete, so readers never see a half-built index. A nightly cycle means suggestions lag by up to a day, which is acceptable for most products. If it is not, add a small online layer that increments scores for fresh queries and merge it later.

> Query logs contain what people typed, including names, phone numbers and things they would not want suggested to a stranger. Normalise, enforce the minimum count shown above, filter with a blocklist before publishing, and set a retention period for the raw log. A suggestion shown to everyone is a publication, not an internal metric.

## How do you cache top-K suggestions per prefix?

Make the endpoint a pure function of the prefix, so the answer is identical for every user. Then the URL itself is the cache key, and the browser, a CDN and Redis can all hold it. The handler below does one Redis read, bounds its input and sets a public Cache-Control header.

Check the memory you are signing up for before building it. The arithmetic gives an upper bound, because real prefixes overlap heavily, and that bound fits a modest Redis instance. Measure a sample key rather than trusting the per-entry estimate.

Treat the five-minute max-age as a freshness decision. Because the nightly job already makes data up to a day old, five minutes of extra staleness costs nothing the user can see, and it is what makes the 80 percent hit assumption plausible.

## How should the client debounce and cancel requests?

Debounce so a burst of keystrokes sends one request, and cancel so a slow response can never overwrite a newer one. AbortController is the standard way to cancel a fetch, and an effect cleanup is the natural place to call it. The hook below also keeps an in-memory map, so deleting a character and retyping it costs no request.

Cancelling only stops the browser waiting; the server may still finish the work, which is cheap here because the answer is one cached lookup. The 100 ms delay is a tunable from the latency budget, not a rule, so choose it against how fast your users actually type.

## Which autocomplete design should you choose? A checklist

Pick the lightest design that survives your numbers, and move up only when a measurement forces you to. Answer these in order.

Under about a million rows and modest traffic: a B-tree with text_pattern_ops, debounce and a minimum of two characters. Stop here if the load test passes.

Users make typos or search mid-string: add pg_trgm with a GIN index, and accept the larger index.

Short prefixes sort too many rows: precompute top ten per prefix into a table or Redis sorted sets.

Traffic is dominated by repeated prefixes: serve a public, URL-keyed response and add CDN caching before adding servers.

Suggestions must react within minutes: add an online score-increment layer on top of the nightly build, and keep the build as the source of truth.

Whichever you choose, write down the assumptions behind the capacity block and revisit them when real traffic arrives. The arithmetic is the part you can check, and a wrong assumption is cheap to correct while it is still on paper.

Autocomplete is a read-heavy lookup disguised as a search problem. Do the expensive ranking offline, key the result by prefix, cache it publicly, and make the client send as few requests as it can. Start with the database you already run, and let measured load, not fashion, move you to tries or Redis.

## Sources and further reading

- PostgreSQL docs: pg_trgm, trigram matching and index support
- PostgreSQL docs: operator classes, including text_pattern_ops
- Redis docs: ZRANGE, including BYLEX lexicographic ranges
- Nielsen Norman Group: response times, the 3 important limits
- MDN: AbortController for cancelling fetch requests
- Wikipedia: trie, the prefix tree data structure

## Source links

- https://www.postgresql.org/docs/current/pgtrgm.html
- https://www.postgresql.org/docs/current/indexes-opclass.html
- https://redis.io/docs/latest/commands/zrange/
- https://www.nngroup.com/articles/response-times-3-important-limits/
- https://developer.mozilla.org/en-US/docs/Web/API/AbortController
- https://en.wikipedia.org/wiki/Trie

## FAQ

### How do you design search autocomplete at scale?

Precompute the top ten suggestions for every query prefix offline from aggregated search logs, then serve them by exact prefix key from Redis or a CDN. This turns each keystroke into a single cached lookup instead of a ranking query. The client debounces input and cancels stale requests, and the target round trip is about 100 milliseconds.

### Should I use a trie or a database for autocomplete?

A trie gives lookups proportional to prefix length but lives in one process, so every instance needs the same build. For small data, a Postgres B-tree with text_pattern_ops is simpler and already running. Move to precomputed Redis sorted sets when short prefixes sort too many rows or traffic outgrows the database.

### How do I rank autocomplete suggestions by popularity and recency?

Weight each day's search count by an exponential decay with a half-life you choose, such as 7 days, and sum the results. A query searched 400 times yesterday then outranks one searched 1,000 times two weeks ago. Add a minimum count so rare or private queries never become eligible.

### How can Postgres pg_trgm help with autocomplete?

The pg_trgm extension adds GIN and GiST indexes that support LIKE, ILIKE and similarity searches, and the match need not be left-anchored. That gives typo tolerance, such as matching cofee to coffee. It costs a larger index and is slower than an exact key lookup, so use it where typos matter.

### How long should I debounce an autocomplete input?

Around 100 milliseconds is a reasonable starting point, but it is a dial, not a rule. A shorter delay feels faster and sends more requests, while a longer one saves requests and delays suggestions. Pair it with AbortController so a slow earlier response can never overwrite a newer one.

---

- HTML version: https://www.matthewswong.com/en/blog/design-search-autocomplete-typeahead/
- Bahasa Indonesia: https://www.matthewswong.com/id/blog/design-search-autocomplete-typeahead/
- Site index for agents: https://www.matthewswong.com/llms.txt
- Sitemap: https://www.matthewswong.com/sitemap.xml
- API description (OpenAPI): https://www.matthewswong.com/openapi.json
