Skip to content

Lesson 6 of 14 · 19m

Tries and Longest-Prefix Matching

Your kernel's route table (`net/ipv4/fib_trie.c`) is a trie doing longest-prefix match — the rule that let a forged /24 hijack YouTube in 2008.

Every packet leaving your machine is resolved by a trie. The Linux IPv4 forwarding table lives in net/ipv4/fib_trie.c — a level-compressed Patricia trie — and the lookup it performs isn't "is there a route," it's "what's the longest matching prefix." Send to 10.1.2.5 with routes 10.0.0.0/8 and 10.1.2.0/24 installed, and the /24 wins. Most specific always wins. ip route get 10.1.2.5 shows you which entry matched.

The wrong model is "a dict keyed by network." A hash map answers exact keys; longest-prefix match asks a question a dict can't express. The trie walks the address bit by bit, and the deepest node that matches is the answer — which is also why a per-octet trie is wrong for this job: prefixes aren't octet-aligned, so the FIB is a bitwise radix tree. "Patricia" and "level-compressed" mean single-child paths are collapsed into one node — without compression a /32 walk would burn 32 nodes of pointers.

The incident that proves the rule

On February 24, 2008, Pakistan Telecom tried to blackhole YouTube inside Pakistan by advertising 208.65.153.0/24 — a service whose legitimate announcement was /22. Its upstream, PCCW, leaked the advertisement worldwide, and because longest-prefix match prefers the more specific route, the forged /24 beat the real /22 everywhere it reached. YouTube was unreachable globally for about two hours. BGP didn't malfunction; the data structure's rule — specificity wins — was weaponized. RPKI and route filtering exist precisely because routers will faithfully follow a lying /24.

Where else the same shape appears

  • Autocomplete / type-ahead — walk the prefix once, enumerate the subtree. "Find every word starting with fir" is one descent, not a 100k-word startswith scan per keystroke. Elasticsearch's completion suggester uses the trie's compacted cousin — a finite-state transducer in Lucene — because a raw per-char trie is a memory hog on large dictionaries.
  • DNS and ACLs — suffix and wildcard matching are the longest-prefix idea walked right-to-left.
  • Firewall prefix sets — ipset/nftables sets and ipaddress.collapse_addresses() merge adjacent networks before they hit a ruleset.

A minimal trie

class Trie:
    def __init__(self):
        self.root = {}
    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node['$'] = True            # terminal marker
    def starts_with(self, prefix):
        node = self.root
        for ch in prefix:
            if ch not in node:
                return []
            node = node[ch]
        return self._collect(node, prefix)
    def _collect(self, node, path):
        out = [path] if '$' in node else []
        for ch, child in node.items():
            if ch != '$':
                out += self._collect(child, path + ch)
        return out

Dict-of-dicts is O(total chars) to build and O(prefix length) to query — the startswith scan is O(dictionary size) per keystroke. The honest cost: each node is a dict, so per-node overhead is heavy; radix compression or an FST is what production uses.

What to actually do

Words on a static dictionary: sorted array plus bisect on the prefix range is genuinely competitive and trivially cheap. Words that update constantly — or anything prefix-shaped at kernel scale: routes, ACLs, ASN tables — radix trie, via pytricia or py-radix rather than a hand-rolled bitwise tree. And keep the routers' rule in your pocket: the most specific match wins, which is exactly why an unexpectedly specific route deserves suspicion.

Field notes

  • A raw char trie spends a dict per character — radix/Patricia compression collapses single-child chains; fib_trie.c is level-compressed for exactly this reason.
  • IPv6 lookup walks 128 bits uncompressed — compression and multibit strides are what keep route lookup at line rate.
  • ip route get <addr> prints the winning route — the fastest way to see longest-prefix match pick a /24 over a /8.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.