Tries and Radix Trees - Complete Deep Dive
Prerequisites: Database Indexing, Search Indexing Used in: Search Autocomplete, Trending Topics, Zomato
What is a Trie?
A trie is a tree where the edges carry characters, not the nodes, so the path you walk from the root spells out a string. Walk c, then a, then t and you are standing at the node for the prefix cat. Every string stored in the trie shares its nodes with every other string that starts the same way, which is exactly why it answers “what comes after this prefix?” without searching anything.
Real-world analogy: Think of a library where the shelves are labelled one letter at a time. The ground floor has 26 corridors, one per first letter. Walk into corridor c and you find 26 more corridors, one per second letter. To find every book starting with cat, you do not read a single spine — you take three turns and you are physically standing in the only place those books can be. The number of turns depends on how long your prefix is, and not at all on how many books the library owns. Adding a million books adds no turns.
Why Not Just Use LIKE or an Index
The obvious first answer is a table of terms and a B-tree index. It gets you further than people expect, and then stops dead.
CREATE TABLE terms (term TEXT PRIMARY KEY, popularity BIGINT);
CREATE INDEX idx_terms ON terms (term text_pattern_ops);
-- Query A: trailing wildcard only
SELECT term FROM terms WHERE term LIKE 'pre%';
Query A does use the index. The planner rewrites LIKE 'pre%' into the range term >= 'pre' AND term < 'prf', and a B-tree is a sorted structure, so a range is a seek plus a sequential walk of the leaves. Prefix matching on a B-tree is real. Two things break it.
💡 In Postgres this only works if the index operator class supports it. Under a non-C collation you need text_pattern_ops as shown above, or the planner quietly ignores the index and scans the table.
Ranking is not free. Autocomplete does not want the matches, it wants the ten best matches. The index is sorted by term, not by popularity, so the engine must read every row in the range, sort by popularity, and discard the rest.
-- Query B: what autocomplete actually needs
SELECT term FROM terms WHERE term LIKE 'a%' ORDER BY popularity DESC LIMIT 10;
For pre that might be 4,000 rows. For a it is a large fraction of the whole corpus — hundreds of thousands of rows read and sorted to return ten, on every keystroke, for every user. A composite index on (term, popularity) does not rescue you either: the leading column is a range, so the index cannot deliver the second column in sorted order. You can add a covering index per prefix length, which is just a worse trie built out of disk pages.
Leading wildcards cannot use the index at all.
-- Query C: no usable left anchor
SELECT term FROM terms WHERE term LIKE '%pre%';
A B-tree is ordered by the string’s beginning. %pre% gives the planner no starting point, so there is no range to seek to and the only correct plan is to read every row and test it. Ten million terms, full scan, every keystroke. This is not a tuning problem — it is the wrong data structure for the question, and the fix is a different index (an n-gram index or a real search engine), never a better query.
Lookup Cost and Why It Ignores Corpus Size
Walking a trie costs O(p) pointer hops, where p is the length of the prefix the user typed. Not O(log n). Not O(n). There is no n in the expression at all.
The reason is that the trie never compares your prefix against stored data. At each node it uses the next character as a direct lookup — “which child is t?” — and moves. The structure below you got bigger when the corpus grew, but you do not touch it. Searching cat is three hops whether the trie holds a thousand terms or a billion.
| Structure | Find all terms with prefix p |
Get top 10 of those | Depends on corpus size |
|---|---|---|---|
| B-tree on term | Seek plus walk the range | Read whole range and sort | Yes, via range width |
| Hash index on term | Impossible, hashing destroys order | n/a | n/a |
| Trie | p pointer hops |
Read a precomputed array | No |
Typed prefixes are short — almost all autocomplete traffic is 1 to 12 characters — so p is effectively a small constant, which is the whole reason a trie is the default answer for autocomplete. Note what the diagram below shows: car, card and cat share the nodes for c and ca, so a shared prefix is stored once. A node is also not automatically a term — ca is a waypoint, not a word — so nodes carry an is-a-term flag.
flowchart LR
ROOT(("root"))
C["c"]
CA["ca"]
CAR["car - is a term"]
CARD["card - is a term"]
CAT["cat - is a term"]
ROOT -->|"c"| C
C -->|"a"| CA
CA -->|"r"| CAR
CAR -->|"d"| CARD
CA -->|"t"| CAT
Storing Top-K Completions at Each Node
Reaching the node for a in three microseconds is useless if you then have to find the best completions beneath it. The subtree under a may hold a million terms. A depth-first walk to collect and rank them is O(size of subtree), which is the cost we were trying to avoid, and it is worst exactly where traffic is heaviest — short, popular prefixes.
The fix is to precompute the answer and store it on the node. Each node keeps a small array of the top K completions in its own subtree, already sorted by score.
{
"node": "ca",
"top_k": [
{ "term": "cars", "score": 982301 },
{ "term": "cat videos", "score": 771004 },
{ "term": "card balance", "score": 640112 }
]
}
A query becomes: walk p hops, read the array, return it. No subtree traversal, no sorting at request time, and the response time is flat across every prefix in the corpus. The cost is memory. Ten entries of roughly 40 bytes each is ~400 bytes per node, and the trie has millions of nodes. Three standard trims: only store the array above a depth cutoff (prefixes of 1-8 characters, since deeper nodes have small subtrees that are cheap to walk live), only store it where the subtree is larger than K, and store 4-byte term IDs plus a side table rather than repeating "card balance" at every ancestor.
Building the arrays is one bottom-up pass. A node’s top-K is the K-way merge of its children’s top-K lists plus its own term, so the whole trie is computed in a single post-order traversal — linear in node count, and parallel across the root’s children.
The Memory Problem and Radix Compression
A naive trie is memory-hostile for a reason that is easy to miss: it allocates a node per character, and most of those nodes do nothing.
Store the term javascript tutorial. After javas there is probably only one way to continue, so you have a chain of fourteen nodes each with exactly one child, each carrying a header, an is-a-term flag, and a child structure, to represent fourteen characters that could have been one string. And the per-node overhead is worse than it sounds. A node with a fixed array of 26 child pointers at 8 bytes each is 208 bytes of pointers, mostly null, before any payload. Over an alphabet that includes digits, spaces and Unicode, that array is far larger. Common alternatives, roughly in order of how much work they are:
| Child representation | Memory per node | Lookup | Notes |
|---|---|---|---|
| Fixed pointer array | Alphabet size times 8 bytes | One array index | Fastest, wildly wasteful |
| Sorted array of pairs | Children times 12 bytes | Binary search | Good default, cache friendly |
| Hash map | Children times ~32 bytes | One hash | Overhead per entry is high |
| Bitmap plus packed array | Alphabet bits plus children | Popcount then index | What production tries use |
A radix tree (also called a compressed trie, and in its binary form a Patricia trie) fixes the structural waste directly: any chain of single-child nodes collapses into one node holding the whole substring on its edge.
Plain trie Radix tree
j - a - v - a - s - c ... "javas" ─┬─ "cript"
└─ "core"
The node count drops from “sum of all term lengths” to roughly “two times the number of terms”, because a node only needs to exist where strings actually diverge. For a real autocomplete corpus that is commonly a 5-10x reduction. The trade is that each hop now compares a string rather than a character, so you do a short memcmp instead of one array index — more work per hop, far fewer hops, and much better cache behaviour because the characters you are comparing are contiguous in memory.
This is not an academic structure. Redis implements a radix tree (rax) and uses it for stream entry IDs and key tracking; Linux’s page cache index and many routing tables are radix trees. If you say “trie” in a design discussion and mean something that ships, you almost certainly mean a radix tree.
Serving Shape - Build Offline, Ship a Snapshot
The instinct is to keep one shared trie and mutate it as new terms arrive. Do not. A mutable shared trie forces a lock discipline on a structure being read tens of thousands of times a second, and the writes are the least urgent thing in the system — nobody needs their search to appear in autocomplete within a second.
The production shape is an immutable trie built offline and swapped atomically.
flowchart LR
LOG[("Query log<br/>raw searches")]
AGG["Offline aggregator<br/>counts per term"]
BUILD["Trie builder<br/>top k per node"]
SNAP[("Snapshot blob<br/>in object storage")]
LB["Load balancer"]
RA["Replica A<br/>trie in RAM"]
RB["Replica B<br/>trie in RAM"]
LOG --> AGG
AGG --> BUILD
BUILD --> SNAP
SNAP --> RA
SNAP --> RB
LB --> RA
LB --> RB
- A batch or streaming job aggregates the query log into
term -> score. - A builder constructs the whole radix trie, computes top-K at every node, and serialises it into one flat binary blob — ideally one where offsets are relative so it can be memory-mapped without parsing.
- The blob goes to object storage with a version number.
- Each serving replica downloads the new blob, builds it in spare memory, then flips a single pointer from the old trie to the new one.
That pointer flip is the whole trick. Readers in flight keep using the old trie and finish normally; new requests get the new one; the old allocation is freed when the last reader is done. No locks on the read path, no partially-updated structure anyone can observe, and replicas are stateless and identical — any one can serve any request, and a new replica is just a process that downloaded a blob. Rollback is shipping the previous version number. Mutating in place gets you none of that: you need read-write locks or a lock-free structure, a half-applied update is visible, replicas drift apart so results differ by which host you hit, and a bad update has no undo.
Sharding a Trie by Prefix
Most of the time you do not shard. A radix trie over a few million terms with top-K arrays is commonly tens to a couple of hundred megabytes, which fits in RAM on every replica, and full replication is strictly better than sharding — one network hop, no scatter-gather, no fan-out tail latency.
When the corpus genuinely does not fit (every product title in a marketplace, every address in a country), shard by prefix, because the prefix is the routing key and the query already contains it.
- Shard on the first 1-2 characters.
a*to one shard,b*to another. Simple, and badly skewed: in English,sandcdwarfx,qandz. - Shard on a prefix-range table built from real traffic. Measure term counts and query volume per prefix, then assign contiguous prefix ranges to shards so each shard holds a similar load —
aa-ap,aq-bm, and so on. This is the same move as range-partitioning a database with explicit split points, and it needs the same periodic rebalancing. See database sharding and hot partitions. - Keep a short-prefix tier replicated everywhere. Prefixes of 1-2 characters are the hottest traffic and the smallest data — the answers are just top-K arrays. Serve those from local memory on every replica and only route 3-plus-character prefixes to a shard.
Never hash the full term to pick a shard. Hashing destroys the ordering that makes a prefix useful, so a prefix query would have to ask every shard.
Keeping Counts Fresh From a Stream
The trie’s structure changes slowly. Its scores change constantly, and scores are what the user sees.
The standard pipeline: every search event goes onto a log (Kafka or Kinesis), a stream processor maintains windowed counts per term, and those counts feed the builder.
- Windowing. A lifetime counter makes autocomplete a museum. Use a decayed score — a sliding 24-hour or 7-day window, or exponential decay applied on each rebuild — so last week’s spike fades. Exact counts for millions of terms fit comfortably in a stream processor’s state store; if you need distinct users per term rather than raw volume, that is a cardinality sketch, not a counter.
- Rebuild cadence. A full rebuild every 10-60 minutes is normal and good enough for almost everything, because it is a batch job over a few million rows.
- A fast path for genuinely new terms. Breaking news coins terms the snapshot has never seen, and an hour is too slow. Keep a small second trie built from the last few minutes of the stream, per replica, and merge its top-K with the main trie’s at query time. Two array merges cost nothing, and a tiny trie rebuilds every 30 seconds. This is the real-time tier in Trending Topics.
One guard rail worth saying out loud: autocomplete is a publishing surface. Anything promoted from raw query logs will eventually promote something you do not want on the page, so the pipeline needs a denylist and a minimum-frequency floor before a term is eligible.
Alternatives - Inverted Index, FST, Sorted Sets
A trie is not the only way, and for several common requirements it is the wrong way.
Inverted index with edge n-grams. At index time, expand each term into its prefixes as tokens — car becomes c, ca, car — and index them in Elasticsearch or OpenSearch. A query for ca is then an ordinary exact-term lookup, so the engine’s existing scoring, filtering and faceting all apply. You get “completions in restaurants near me that are open now” for free, which a standalone trie cannot do. The cost is index size, since every term is stored once per prefix length. See search indexing.
Finite state transducer. An FST is a trie that also shares suffixes, collapsing into a directed acyclic graph where each accepted path emits an output value such as a weight. Lucene’s suggesters use this, and the memory win is large because every term ending in ing or tion shares one tail. It is immutable by construction, so you rebuild rather than update — which the snapshot-and-swap model above already does.
Redis sorted set per prefix. Materialise the answer: one sorted set per prefix, members are completions, scores are popularity, and a query is a single ZREVRANGE prefix:ca 0 9. No tree, one round trip, and you already run Redis. The cost is write amplification — one 20-character term touches 20 keys — plus memory for storing completions under every prefix.
| Approach | Query cost | Ranking and filters | Updates | Pick it when |
|---|---|---|---|---|
| Radix trie with top-k | Prefix length, in-process | Ranking precomputed, no filters | Rebuild and swap | Pure autocomplete at very high read volume |
| Edge n-gram inverted index | One term lookup plus scoring | Full scoring, filters, facets | Near real time per document | Completions must respect filters or permissions |
| Finite state transducer | Prefix length, in-process | Weights baked in | Rebuild only | Memory is the binding constraint |
| Redis sorted set per prefix | One round trip | Score order only | Write amplification per term | Small curated corpus, want it today |
| B-tree plus LIKE | Range scan plus sort | Sorts at query time | Free, it is your table | Low traffic, admin search boxes |
The honest default for a product team is the inverted index, because real autocomplete is rarely “the globally most popular strings” — it is “the most relevant things this user is allowed to see”. Reach for a trie or an FST when the read volume or the latency budget makes a dedicated in-process structure worth owning.
Typo Tolerance Is Out of Scope
A plain trie matches prefixes exactly. Type recieve and you walk to the node for recie, find the subtree that genuinely starts with those characters, and return whatever is there — which is nothing useful. There is no mechanism in the structure for “close enough”, because every hop is an exact character match.
Making it fuzzy means changing the algorithm, not the data:
- Intersect with a Levenshtein automaton. Build a small automaton accepting every string within edit distance
kof the input and intersect it with the trie or FST, pruning any branch whose minimum possible distance exceeds the budget. This is what Lucene’s fuzzy query does. It is correct, and the frontier explodes — distance 2 over a large alphabet makes fuzzy prefix search one to two orders of magnitude more expensive than exact. - Precompute deletions. Index each term together with its single-character deletions and look the query’s deletions up in a hash map. Very fast, memory-heavy, capped at small distances.
- Generate candidates, then rescore. Fetch plausible terms with character n-grams, then rank them with a real distance function. The standard move when you already run a search engine.
The design-interview answer is to separate the concerns: the trie serves exact-prefix completions, and a spelling-correction service sits beside it, consulted when the trie returns too few results. Do not make one structure do both.
When to Use / When NOT to Use
✅ Use a trie or radix tree when: the query is genuinely prefix-shaped and read volume is high, you need flat latency across short and long prefixes, the corpus fits in memory on one replica, and rankings can be precomputed offline.
❌ Don’t when:
- Results must be filtered by permissions, geography or availability — use an inverted index
- You need infix matching (
%pre%) or typo tolerance as a first-class requirement - The data is per-user, so there is no shared snapshot to build
- Traffic is low enough that
LIKE 'pre%'is simply fine, which is more often than engineers admit
Common Interview Questions
Q1: Why is a trie lookup independent of how many terms are stored?
Because the lookup never compares your input against the stored data. Each hop uses the next character of the prefix as a direct lookup for a child pointer, so the work is proportional to the prefix length, not the corpus. Adding terms makes the subtrees below you larger, but a prefix walk does not visit them. This is the key difference from a B-tree, where the depth and the width of the matching range both grow with the data.
Q2: A B-tree index supports LIKE 'pre%'. Why build a trie at all?
Prefix matching is not the hard part — prefix ranking is. The B-tree is sorted by term, so to return the ten most popular matches it has to read every row in the range and sort it, and for a one-character prefix that is a large fraction of the table on every keystroke. A composite index does not help because the leading column is a range. A trie sidesteps it by storing the precomputed top-K on each node, turning the request into a walk plus an array read. Separately,
LIKE '%pre%'cannot use a B-tree at all, since there is no leading anchor to seek to.
Q3: Why ship an immutable snapshot instead of updating the trie in place?
Reads outnumber writes by orders of magnitude and writes are not urgent. An immutable trie needs no locks on the read path, so replicas serve at full speed; the swap is a single atomic pointer flip, so nobody ever observes a half-updated structure; replicas are identical and stateless, so results do not depend on which host you hit; and rollback is redeploying the previous blob. In-place mutation costs you all four of those to make new terms visible a few minutes sooner.
Q4: Your trie is 400GB. What do you do?
First, shrink it. Radix-compress to collapse single-child chains, store term IDs instead of strings in the top-K arrays, cap the depth at which top-K is stored, and consider a finite state transducer to share suffixes as well as prefixes. Those together often move a corpus back into single-host memory. If it still does not fit, range-partition by prefix using split points derived from real traffic — not the first letter, which is heavily skewed — and keep the hot 1-2 character prefixes replicated on every node so most traffic never leaves the box.
Q5: When would you use an inverted index instead?
When completions must respect anything about the request beyond the prefix: permissions, location, stock, open-now, language. A trie’s top-K is precomputed globally, so it cannot answer “most popular dishes at restaurants delivering to me right now” — filtering after the fact gives you an empty or short list. An edge n-gram index in Elasticsearch turns a prefix into an ordinary term lookup that composes with every other filter and with relevance scoring, at the cost of a larger index and a network hop.
Navigation
| ← Optimistic Concurrency | Columnar Analytics → |
| All Concepts | HLD Designs |