Skip to main content
← CONCEPTS / ALGORITHMS & DATA STRUCTURES
An end-to-end domain learning journey

Aho-Corasick Automaton &
Multi-Pattern Matching.

The Aho-Corasick Automaton fuses a prefix Trie with KMP-style BFS failure links and dictionary output links, scanning N-byte payloads against K patterns in O(N + M + Z) amortized time.
Start the journey7 sections· Last modified Nov 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep storage layouts predictable as data grows, by pre-computing fallback suffix transitions once during compilation, per-request matching time becomes completely independent of dictionary size K.

TL;DR30-second simplified summary
▾

By combining a prefix Trie with BFS-computed failure links and output links, Aho-Corasick generalizes KMP from 1 pattern to K patterns. Build time is O(M * |Sigma|) (or O(M) with hash/array maps) and search time is O(N + Z), where Z is the number of matches.

Full walkthrough · 7 stages
01
Stage 1 · Foundationfoundation

The Multi-Pattern Bottleneck: Why O(K * N) Collapses.

Why this matters: Quantify why running single-pattern algorithms (KMP, Boyer-Moore, or individual regexes) K times saturates CPU on high-throughput inspection pipelines.

Single-pattern algorithms like Knuth-Morris-Pratt (KMP) scan an N-character payload in O(N) time. However, security and moderation systems rarely search for one keyword—they evaluate K = 10,000+ signatures concurrently. Looping KMP or compiled regular expressions over each pattern forces K full memory passes over the payload, inflating CPU cache misses and driving work to O(K * N) = 10^8 operations per 10 KB request.

def scan_naive(text: str, patterns: list[str]) -> list[tuple[int, str]]:
    if not text or not patterns:
        return []
    hits: list[tuple[int, str]] = []
    for pat in patterns:  # K passes over N characters -> O(K * N)
        if not pat:
            continue
        idx = text.find(pat)
        while idx != -1:
            hits.append((idx, pat))
            idx = text.find(pat, idx + 1)
    return hits
Naive Baseline

Sequential K-Pass Payload Scanning

10 KB Payload (N)sourcePattern Loop(K=10,000)process10^8 Ops / Requestwarning< 500 req/s CeilingsinkO(K * N) comparisons

1.Memory Bandwidth: Re-scanning N bytes K times evicts hot dictionary state from L1/L2 cache.

2.Throughput Collapse: Adding new threat signatures linearly degrades request throughput.

Caption: Sequential per-pattern scanning multiplies payload length N by dictionary size K, saturating CPU cores.

02
Stage 2 · Foundationfoundation

Prefix Trie Compilation: Merging K Patterns into O(M) States.

Why this matters: Build the goto-function Trie so shared pattern prefixes are represented once in memory.

The first phase of Aho-Corasick inserts all K patterns (with total character length M) into a standard Trie. Shared prefixes such as 'he' and 'hers' share the exact same root->h->e path, bounding total Trie nodes to at most M + 1.

class ACNode:
    __slots__ = ("next", "fail", "outputs")
    def __init__(self) -> None:
        self.next: dict[str, ACNode] = {}
        self.fail: ACNode | None = None
        self.outputs: list[str] = []
Phase 1: Goto Graph

Prefix Trie Construction for {he, she, his, hers}

Root (0)sourceState 1 ('h')processState 2 ('he') *storeState 4 ('sh')process'e'

1.Prefix Sharing: Total states <= M + 1 regardless of how many patterns share prefixes.

2.Mismatch Problem: A bare Trie cannot jump from 'sh' to 'h' without restarting at Root.

Caption: Inserting all patterns into a prefix Trie merges common prefixes into O(M) states.

Engineering Decision Framework
Problem
How to implement Aho-Corasick Automaton & Multi-Pattern Matching without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep storage layouts predictable as data grows, by pre-computing fallback suffix transitions once during compilation, per-request matching time becomes completely independent of dictionary size K.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Aho-Corasick Automaton & Multi-Pattern Matching experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
Stage 3 · Intermediateintermediate

BFS Failure Links: Generalizing KMP's Prefix Function.

Why this matters: Compute fail(v) via breadth-first search so mismatches jump to the longest valid suffix state without rewinding the text pointer.

If we match 'sh' and the next character is 'i' (no 'i' child from 'sh'), we must not rewind the input tape; 'h' is already matched as a suffix of 'sh'! A BFS starting from depth-1 children (whose fail link is always root) computes fail(v) for each child v = u.next[ch] by walking f = u.fail until f has a transition on ch or f reaches None (defaulting to root). Because BFS processes nodes in strictly increasing depth order, every shallower fail target is already finalized.

from collections import deque
Phase 2: Failure Links

BFS Suffix Fallback Resolution

Depth-1 NodessourceBFS QueueprocessWalk u.fail ChainprocessSet v.fail & MergestoreFor each edge (u, ch, v)

1.Level-Order Invariant: depth(u.fail) < depth(u) guarantees u.fail is finalized before u is popped.

2.Zero Rewind: Input index i never decrements during search.

Caption: Breadth-first traversal computes failure links in O(M) time by reusing shallower suffix links.

04
Stage 4 · Intermediateintermediate

Dictionary Output Links: Catching Embedded Sub-Matches.

Why this matters: Ensure patterns that end strictly inside another pattern (like 'he' inside 'she' or 'ushers') are never missed.

Consider the text 'ushers' with patterns {'he', 'she', 'hers'}. When the automaton reaches state 'she', it must report both 'she' AND its proper suffix 'he'. There are two equivalent ways to achieve this: (1) pre-merge v.outputs.extend(v.fail.outputs) during BFS (simple and O(1) lookup if output lists are small), or (2) store a compressed dictionary-suffix pointer dict_link(v) pointing to the nearest ancestor along the fail chain that has non-empty outputs, keeping build space strictly O(M) even when many patterns nest.

def search(root: ACNode, text: str) -> list[tuple[int, str]]:
    if not text:
        return []
    cur = root
    hits: list[tuple[int, str]] = []
    for i, ch in enumerate(text):
        while cur is not root and ch not in cur.next:
            cur = cur.fail  # type: ignore[assignment]
        cur = cur.next.get(ch, root)
        for pat in cur.outputs:
            hits.append((i - len(pat) + 1, pat))
    return hits
Output Resolution

Propagating Suffix Matches Along Failure Chains

State 'she'sourcefail('she') -> 'he'processMerged OutputsstoreStoreInherit suffix match

1.Pre-Merge vs Dict Link: Pre-merging is faster at scan time; dict_link avoids O(M * K) worst-case output list copies.

2.Output-Sensitive Z: Emitting hits takes O(Z) total time where Z is the actual number of matches found.

Caption: Output links guarantee that every embedded suffix pattern is reported in the same pass.

05
Stage 5 · Intermediateintermediate

Amortized O(N + M + Z) Proof via Potential Method.

Why this matters: Prove formally why the while-loop following failure links cannot degrade runtime to O(N * M).

At first glance, the inner while cur is not root and ch not in cur.next: cur = cur.fail loop looks like it could run many times on a single character.

Define the potential function Phi(cur) = depth(cur) in the Trie. Initially Phi = 0 and Phi >= 0 always. In each outer loop iteration (one per input character, N total), cur = cur.next.get(ch, root) increases depth by at most +1.

Complexity Proof

Potential Function Phi = depth(cur) <= 2N Transitions

Advance Character isourceFollow fail(cur)processSum(fail hops) <= NstoreStorePhi >= 0 invariant

1.Independent of K: Whether K = 10 or K = 100,000 patterns, character transitions stay <= 2N.

2.Worst-Case Per-Char: A single character can take O(L_max) fail steps, but only after L_max prior +1 advances.

Caption: The potential function Phi = depth(cur) proves total state transitions are strictly bounded by 2N.

06
Stage 6 · Advancedadvanced

DFA Completion & Double-Array Tries for Cache-Line Speed.

Why this matters: Eliminate the inner while-loop entirely and compress pointer-chasing hash maps into flat integer arrays for 50k+ req/s WAF nodes.

In latency-critical C++, Rust, or Java WAFs, following dict hash maps and inner while loops causes CPU branch mispredictions and pointer-chasing cache misses.

During BFS, we can pre-compute the complete deterministic transition table go[u][c] for every byte c in 0..255: if c is a Trie child, go[u][c] = child; otherwise go[u][c] = go[fail[u]][c].

Hardware Sympathy

Complete DFA Transition Table vs Pointer-Chasing Trie

Byte Stream(0..255)sourcestate = go[state][b]processDouble-Array /SparsestoreStoreCompress sparse rows

1.Memory vs Speed: Full 256-byte table uses 1 KB/state (e.g., 100 MB for 100k states) for zero-branch O(1) transitions.

2.Double-Array Trie: Packs sparse byte transitions into contiguous int32 base/check arrays.

Caption: Pre-computing complete DFA transitions removes the inner failure loop for predictable p99 latency.

07
Stage 7 · Advancedadvanced

Zero-Downtime Hot-Reloading & Production Failure Modes.

Why this matters: Safely update threat signatures in live traffic without mutating the active automaton or triggering OOM.

Production WAFs update rulesets every few minutes. Mutating a live Trie in place causes torn reads and segfaults/NPEs across worker threads. Instead, compile new signatures in a background builder thread with bounded memory limits, verify automaton size, and atomically swap an immutable reference (AtomicReference / ArcSwap).

// Java: Lock-free immutable automaton hot-swap
private final AtomicReference<AhoCorasickDFA> activeDfa = new AtomicReference<>();
Production Operations

Immutable Blue-Green Automaton Swap

Signature FeedsourceBackground CompilerprocessAtomic Pointer SwapstoreOld DFA ReclaimedsinkPublish atomically

1.Zero Lock Contention: Request threads read an immutable DFA reference with zero mutexes.

2.Memory Guardrail: Cap total Trie states M before compilation to prevent OOM during rule pushes.

Caption: Compiling shadow automata off the request path and swapping pointers atomically prevents read-write races.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

In an Aho-Corasick Automaton, why must failure links be computed in Breadth-First Search (BFS) order rather than Depth-First Search (DFS) order?

Recommended Learning Flow