DEV Community

Cover image for Meilisearch Under the Hood: What Actually Happens Between search() and a 10ms Result
Syed Anzar
Syed Anzar

Posted on

Meilisearch Under the Hood: What Actually Happens Between search() and a 10ms Result

Meilisearch: The Open-Source Algolia Alternative (What Actually Happens Between search() and a 10ms Result)

Most search features start the same way. You write a query like SELECT * FROM products WHERE name ILIKE '%phon%' against PostgreSQL or MySQL.

At ten thousand rows, it feels instant. At one million rows, your database cpu spikes to 100%, sequential disk scans thrash your buffer pool, and users wait two seconds per keystroke. Worse, if a user mistypes "phome", your database returns zero results.

The standard industry answer is either to pay thousands of dollars a month for a hosted Algolia cluster, or deploy a heavy Elasticsearch node that requires 4GB of JVM heap just to stay alive without throwing out-of-memory errors.

Meilisearch took a radically different path. Written in Rust and powered by an internal engine called Milli, it runs inside a single binary, fits comfortably on a $5 Linux virtual server, and delivers typo-tolerant prefix search in under 10 milliseconds.

How does it pull this off without a JVM, without massive background caches, and without calculating edit distances against millions of strings on every keystroke?

Here is what actually happens under the hood when your frontend calls POST /indexes/products/search.


1. The Storage Engine: Zero-Copy LMDB via Memory Mapping

Traditional search engines keep custom application-level buffer pools in memory. Lucene and Elasticsearch manage segments on disk, load terms into the JVM heap, and rely on garbage collection to cycle memory.

Meilisearch skips user-space buffer management entirely. Underneath its Milli search engine, Meilisearch uses LMDB (Lightning Memory-Mapped Database) through the Rust heed crate.

+---------------------------------------------------------------+
|                      MEILISEARCH ENGINE                       |
+---------------------------------------------------------------+
| HTTP REST Layer (Actix-web / Tokio Async Runtime)             |
+---------------------------------------------------------------+
                               |
                               v
+---------------------------------------------------------------+
| Milli Search Core (Rust)                                      |
| - Levenshtein Automata (DFA Intersection over FST)            |
| - Roaring Bitmaps (SIMD-accelerated Set Intersections)        |
| - 6-Stage Bucket Sort (Words -> Typo -> Proximity...)         |
+---------------------------------------------------------------+
                               |
                               v
+---------------------------------------------------------------+
| LMDB via `heed` Crate                                         |
| - Memory-Mapped I/O (mmap) straight into OS Page Cache        |
| - Single-Writer, Multi-Reader MVCC (B+ Trees)                 |
| - Zero User-Space Buffer Copies                               |
+---------------------------------------------------------------+
Enter fullscreen mode Exit fullscreen mode

LMDB is an embedded B+ tree key-value store that relies directly on the operating system's virtual memory subsystem via mmap().

When Meilisearch opens an index, it does not read gigabytes of index files into heap allocations. Instead, it asks the Linux kernel to map the index file (data.mdb) directly into the process's virtual address space.

When a search query needs a word record or a posting list, the CPU reads the mapped virtual address directly. If the page is already in the Linux page cache (RAM), the CPU accesses the bytes instantly with zero user-space memory copies. If the page is not in RAM, the CPU triggers a minor page fault, and the kernel loads the 4KB memory page directly from NVMe storage into the page cache.

Because Meilisearch does not run a garbage collector, it produces zero GC pauses. Search queries run concurrently across worker threads using read-only MVCC transactions (RoTxn). Readers never block other readers, and readers never block indexing writers.


2. Typo Tolerance: Why Naive Levenshtein Destroys Latency

If you search for smartphon, you want documents containing smartphone to match with 1 typo.

The naive way to implement typo tolerance is computing the Levenshtein or Damerau-Levenshtein edit distance between the input string and every word in the dictionary:

$$\text{Time Complexity} = O(V \cdot L_1 \cdot L_2)$$

Where $V$ is your vocabulary size (e.g., 250,000 unique words) and $L$ is word length. Calculating dynamic programming matrices 250,000 times per keystroke takes several hundred milliseconds. For search-as-you-type at 60 frames per second, naive distance calculation is impossible.

The Levenshtein Automaton Breakthrough

Milli solves this using Levenshtein Automata, an algorithmic method formalised by Klaus Schulz and Stoyan Mihov.

Instead of comparing the query word to every word in the dictionary, Meilisearch converts the user query into a Deterministic Finite Automaton (DFA).

A Levenshtein automaton for a search word $W$ and maximum edit distance $k$ is a state machine that accepts any string within edit distance $k$ of $W$.

Query: "cat" (max edit distance k = 1)

State transitions track insertions, deletions, and substitutions:
       'c'           'a'           't'
(0,0) ------> (1,0) ------> (2,0) ------> ((3,0)) [Exact match, 0 typos]
  |             |             |
  | edit        | edit        | edit
  v             v             v
(0,1) ------> (1,1) ------> (2,1) ------> ((3,1)) [Match with 1 typo]
Enter fullscreen mode Exit fullscreen mode

At the same time, the entire vocabulary of the index is stored as a Finite State Transducer (FST), which is essentially a compressed prefix tree (trie) where common prefixes and suffixes are shared.

To find all matching words with typo tolerance, Milli performs an automaton intersection: it traverses the vocabulary FST and the query Levenshtein DFA simultaneously.

If a path in the vocabulary FST enters an error state in the DFA (meaning the edit distance already exceeds $k=1$ or $k=2$), the engine rejects that entire branch immediately.

Instead of evaluating hundreds of thousands of words, whole subtrees containing 50,000 words are discarded in single-digit nanoseconds. The engine finds all valid typo candidates in under 0.2 milliseconds.

Default Typo Thresholds

By default, Meilisearch enforces strict typo rules based on word byte length:

  • 0 to 4 characters: 0 typos allowed (prevents noisy matches on short words like "cat" or "sql")
  • 5 to 8 characters: 1 typo allowed
  • 9 or more characters: 2 typos allowed

3. Posting Lists: Roaring Bitmaps and SIMD Set Intersections

Once the engine identifies the valid words for a query, it needs to find the documents containing those words and apply filters (such as in_stock = true AND price < 500).

In search engine terminology, the list of document IDs associated with a term is called a posting list.

Every document in Meilisearch receives an internal 32-bit unsigned integer ID (docid). Rather than storing docids as raw integer arrays or linked lists, Meilisearch stores them using Roaring Bitmaps (via the roaring Rust crate).

How Roaring Bitmaps Work

A standard 32-bit uncompressed bitmap for 10 million documents would consume 1.25 MB per term, regardless of whether a term matches 5 documents or 5 million documents.

Roaring Bitmaps solve this by partitioning 32-bit integers into chunks based on the top 16 bits. The lower 16 bits are stored in one of three container types depending on data density:

32-bit Document ID:
[ Higher 16 bits: Chunk Index ]  |  [ Lower 16 bits: Container Data ]

Container Types:
1. Array Container (< 4,096 IDs):
   Stores sorted 16-bit integers directly. Memory: 2 bytes per ID.

2. Bitset Container (>= 4,096 IDs):
   Converts to a 65,536-bit (8 KB) bitset. Memory: exactly 8,192 bytes.

3. Run Container (Contiguous sequences, e.g., docids 1000..5000):
   Stores pairs of [start, length]. Extremely compact for sequential inserts.
Enter fullscreen mode Exit fullscreen mode

When two bitset containers need to intersect (word_docids("phone") AND word_docids("apple")), the CPU executes bitwise AND instructions across 64-bit words, accelerated by AVX-512 or AVX2 SIMD vector registers.

Millions of candidate documents are filtered down in microseconds, staying entirely within L1 and L2 CPU caches.


4. Ranking: The 6-Criteria Bucket Sort

Most search engines (like Lucene, Solr, and Elasticsearch) use probabilistic scoring algorithms like BM25 or TF-IDF.

BM25 calculates a floating-point score based on term frequency, inverse document frequency, and field length. The engine then sorts all matching documents by their floating-point score. While flexible, calculating and sorting floating-point scores across 500,000 candidates adds significant compute overhead.

Milli uses a different approach: Bucket Sort with Sequential Ranking Rules.

Instead of assigning a single composite number to each document, Milli evaluates candidates through a pipeline of sequential ranking rules:

All Matching Candidate Documents
               |
               v
    +--------------------+
    |      1. Words      |  -> Groups by number of matched query terms
    +--------------------+
               |
               v
    +--------------------+
    |      2. Typo       |  -> Ties broken by number of typos (0 vs 1 vs 2)
    +--------------------+
               |
               v
    +--------------------+
    |    3. Proximity    |  -> Ties broken by distance between query words
    +--------------------+
               |
               v
    +--------------------+
    |    4. Attribute    |  -> Ties broken by field weight (title > body)
    +--------------------+
               |
               v
    +--------------------+
    |      5. Sort       |  -> Ties broken by user sort (e.g. price:asc)
    +--------------------+
               |
               v
    +--------------------+
    |    6. Exactness    |  -> Ties broken by exact match vs prefix
    +--------------------+
               |
               v
    Top K Results (e.g. limit: 20)
Enter fullscreen mode Exit fullscreen mode

How the Buckets Refine Candidates

  1. Words: Documents containing all search terms land in the top bucket. Documents missing one word land in the next bucket.
  2. Typo: Within the top bucket, documents matching with 0 typos outrank documents matching with 1 typo.
  3. Proximity: Milli checks the word_pair_proximity_docids database. If your query is "wireless headphones", documents where those two words sit directly next to each other (distance = 1) outrank documents where "wireless" is in the title and "headphones" appears forty words later in the description.
  4. Attribute: Matches found in high-priority fields (defined in searchableAttributes, like title) outrank matches in lower-priority fields (description or sku).
  5. Sort: Any custom sort parameter specified in the request (e.g., price:asc).
  6. Exactness: Documents where the query word matches the entire token outrank documents where the query matched only as a prefix.

Early Short-Circuiting

Because the bucket sort works sequentially, it short-circuits. If your query asks for limit=20 and the first rule (Words) places 15 documents in Bucket 1 and 100 documents in Bucket 2, the remaining rules only need to refine Bucket 1 and the top slice of Bucket 2.

The engine never wastes CPU cycles ordering thousands of lower-ranked documents that will never appear on page one.


5. Search-As-You-Type: The Prefix Inverted Index

When a user types "iph", they have not finished their word. They expect results for "iphone" immediately.

In many databases, implementing prefix search requires either expensive LIKE 'iph%' index range scans or generating every possible n-gram during indexing (which inflates index size by 5x to 10x).

Meilisearch treats the final token of every search query as a prefix by default.

To keep this fast, Milli maintains two distinct inverted index tables in LMDB:

  • word_docids: Maps complete words to their document IDs.
  • word_prefix_docids: Maps word prefixes to the union of document IDs whose tokens start with that prefix.

When you type "iph", the engine looks up word_prefix_docids("iph") directly. The lookup returns the pre-computed Roaring Bitmap of all matching documents in a single B+ tree seek.


6. The End-to-End Query Lifecycle

When an HTTP search request arrives, here is the exact sequence of events:

Client Request: POST /indexes/products/search {"q": "cordles drill"}
                                |
1. HTTP Ingestion               v
   Actix-web worker receives JSON payload. Decodes query string.
                                |
2. Tokenization & Parsing       v
   Tokenizer splits input: ["cordles", "drill"]. 
   Identifies "cordles" as full word, "drill" as potential prefix.
                                |
3. Transaction Initialization   v
   Opens read-only LMDB transaction (heed::RoTxn). Zero locks acquired.
                                |
4. Candidate Extraction         v
   - Levenshtein DFA intersects FST dictionary: accepts "cordless" (1 typo).
   - Prefix FST lookup: accepts "drill", "drilling", "drills".
   - Retrieves posting lists as RoaringBitmaps from LMDB.
                                |
5. Filter Evaluation            v
   Applies any filter clause via bitwise SIMD AND/OR against candidate bitsets.
                                |
6. Bucket Sort Execution        v
   Evaluates Words -> Typo -> Proximity -> Attribute -> Sort -> Exactness.
   Short-circuits once requested page limit (e.g. 20 hits) is satisfied.
                                |
7. Document Hydration           v
   Fetches the 20 winning docids from LMDB's documents database.
   Applies highlighting and crop snippets if requested.
                                |
8. Response Dispatch            v
   Serializes response to JSON. Streams back over HTTP.
   Total Wall-Clock Elapsed Time: 2.8ms to 6.4ms.
Enter fullscreen mode Exit fullscreen mode

7. Production Gotchas and Tuning

While Meilisearch is simple to deploy, running it in high-throughput production environments comes with several technical details you must know:

1. The LMDB Sparse File Characteristic

If you inspect Meilisearch's data folder on Linux:

ls -lh /var/lib/meilisearch/data.msif
# Output might show: 100G

du -sh /var/lib/meilisearch/data.msif
# Output shows: 2.4G
Enter fullscreen mode Exit fullscreen mode

Do not panic. LMDB creates a sparse file that reserves virtual address space (map_size), typically defaulting to 100GB or more on 64-bit systems.

The ls utility reports the maximum virtual address ceiling, whereas du reports actual disk blocks allocated on physical storage. Ensure your monitoring alerts check du (or statvfs), not raw file size headers.

2. Indexing Memory Spikes

Reading from an index uses minimal memory because pages live in the OS cache. Indexing, however, is resource-intensive.

When you batch-insert 500,000 JSON documents, Milli creates intermediate sorting chunks using grenad (an external merge-sort library). If you do not limit indexing memory on a modest virtual machine, the Linux kernel OOM killer will terminate the process.

Always configure the memory limit in your environment or systemd unit:

# Bound indexing memory to 2GB on a 4GB RAM server
MEILI_MAX_INDEXING_MEMORY=2GiB
MEILI_MAX_INDEXING_THREADS=2
Enter fullscreen mode Exit fullscreen mode

3. Attribute Ranking Order Matters

In Meilisearch, the order of searchableAttributes directly controls the Attribute ranking rule:

{
  "searchableAttributes": [
    "title",
    "brand",
    "categories",
    "description"
  ]
}
Enter fullscreen mode Exit fullscreen mode

If a customer searches for "Sony", a product with "Sony" in the title will always rank above a product with "Sony" buried in the description. Placing long text fields before identity fields is the most frequent cause of relevance degradation.


Key Takeaways

  • Memory-mapped I/O: Meilisearch delegates cache management to the Linux kernel via LMDB and mmap(), eliminating JVM heap overhead, user-space buffer copies, and garbage collection pauses.
  • Automaton intersection: Typo tolerance does not scan dictionary words. It turns the search query into a Levenshtein DFA and traverses an FST dictionary, pruning non-matching branches in nanoseconds.
  • Roaring Bitmaps: Candidate document IDs and filter intersections operate as compressed 32-bit chunked bitsets processed via SIMD vector instructions inside CPU cache.
  • Bucket sort vs BM25: Relevance is computed using successive bucket sorting across six criteria (words, typos, word proximity, attribute importance, custom sort, exactness), short-circuiting once page limits are met.
  • Self-hosting viability: By combining Rust with memory-mapped data structures, Meilisearch provides a sub-10ms, typo-tolerant search experience on a standard $5 Linux VPS, replacing expensive third-party SaaS search subscriptions without operational complexity.

Top comments (0)