QuickNote delivers 1.8ms median full-text search latency across 10,000 local developer notes on Windows 10 & Windows 11 (x64) while staying inside a ~15-25 MB RAM footprint and <12 MB binary (~11.45 MB). The engine pairs SQLite Write-Ahead Logging (PRAGMA journal_mode=WAL) with an FTS5 virtual table configured with the unicode61 tokenizer, 2- and 3-character prefix indexes (prefix='2 3'), and field-weighted bm25() ranking. Crucially, QuickNote enforces a strict cryptographic isolation boundary: AES-256-GCM encrypted vault entries (card, account, and api secrets) are never written to the FTS5 body index—only non-sensitive titles and tags are indexed—preventing plaintext secret leakage into inverted index B-trees or WAL frames.

(Originally published at anan.lat/blog/sqlite-fts5-sub-2ms-full-text-search-rust-tauri.)

1. Why Keystroke-Rate Search Demands Sub-2ms Query Latency

When you summon QuickNote globally with Ctrl+Shift+Q (under 50ms end-to-end) to grab a Docker command, SQL migration snippet, or staging credential, you expect results to refine smoothly on every single keystroke at 60Hz (16.6ms frame budget).

Once you subtract Tauri IPC serialization, DOM reconciliation in WebView2, and compositor painting, your storage engine has less than 4ms to parse the query, scan the corpus, rank candidates, and return excerpts. Naive SQL LIKE '%query%' scans every row sequentially, breaking down around 2,000 notes and stalling for tens of milliseconds at 10,000 notes. Conversely, cloud search backends violate QuickNote's 100% offline-first guarantee and introduce 80ms–300ms network latency.

SQLite's built-in FTS5 (Full-Text Search 5) extension compiled statically via rusqlite gives us a battle-tested inverted index in the exact same single-file database as our notes—zero background daemon, zero Lucene JVM heap, and 1.8ms median query latency on 10,000 notes.

2. Tuning SQLite for Concurrent Reads & Type-Ahead Speed

Out-of-the-box SQLite uses rollback journal mode, which serializes readers behind writers. In an interactive scratchpad where autosave debounces writes every few hundred milliseconds while the user is searching or switching notes, lock contention causes noticeable UI micro-stutters. QuickNote applies four deterministic connection pragmas at startup:

  • PRAGMA journal_mode = WAL; — Enables Write-Ahead Logging so search readers proceed concurrently without blocking autosave commits, dramatically reducing fsync stalls on Windows NTFS.
  • PRAGMA synchronous = NORMAL; — Safe under WAL mode against application crashes while avoiding redundant per-transaction disk barriers.
  • PRAGMA temp_store = MEMORY; — Keeps transient FTS5 merge and BM25 sort scratch structures in RAM instead of creating temporary files in %TEMP%.
  • PRAGMA cache_size = -8192; — Allocates a bounded 8 MiB page cache per connection—enough to keep hot FTS5 B-tree interior nodes resident while respecting our ~15-25 MB total RAM ceiling.

On the FTS5 virtual table itself, three configuration choices do the heavy lifting for developer text:

  1. unicode61 remove_diacritics 2 tokenchars '_-': Normalizes Unicode text and diacritics while treating underscores and hyphens as token characters so developer identifiers like zeroize_on_drop or aes-256-gcm stay intact instead of fragmenting into noisy sub-tokens.
  2. prefix='2 3': Pre-builds dedicated 2-character and 3-character prefix B-trees. When a user types ru or tok, FTS5 performs an O(log N) prefix tree lookup instead of scanning every term beginning with that letter.
  3. bm25(notes_fts, 10.0, 5.0, 1.0): Weights title matches 10× higher and tag matches 5× higher than body matches. Note an essential SQLite FTS5 detail: bm25() returns negative floating-point scores where more negative values indicate higher relevance, so queries must sort ORDER BY score ASC.

3. Critical Security Boundary: Isolating Encrypted Vault Secrets Out of FTS5

Security Invariant — Zero Secrets in Inverted Indices

An inverted full-text index is fundamentally a plaintext dictionary of every word in the indexed column. If you decrypt a credential vault in memory and feed its secret payload into SQLite FTS5 to make passwords or API keys searchable, you have silently defeated AES-256-GCM encryption at rest: every token lands unencrypted inside SQLite's notes_fts_data B-tree pages, WAL frames, and vacuum freelists.

QuickNote protects sensitive vault categories—card (payment cards), account (logins), and api (API tokens & private keys)—using Argon2id key derivation, AES-256-GCM authenticated encryption (NIST SP 800-38D), and Rust zeroize memory scrubbing.

To preserve that guarantee alongside sub-2ms search, QuickNote enforces a strict architectural split:

  • Plaintext developer notes (is_encrypted = 0): Full title, tags, and body are indexed in notes_fts for instant full-text and snippet retrieval.
  • Encrypted vault entries (is_encrypted = 1, categories card / account / api): The primary notes table stores only the opaque AES-256-GCM ciphertext blob in ciphertext_blob (with body = ''). Database triggers write only non-sensitive title and tags (e.g., "Stripe Prod Webhook", #billing #api) into notes_fts, passing an empty string for the FTS body column.
  • Why we avoid naive content='notes' external-content tables here: External-content FTS5 tables read directly back from the base table during rebuild or snippet() operations. Keeping ciphertext_blob in a separate column untouched by FTS5 and populating a dedicated notes_fts table via conditional triggers guarantees that neither raw secrets nor base64 ciphertext garbage can ever pollute the search index.

The result is both fast and auditable: you can press Ctrl+Shift+Q, type stripe prod, locate the vault entry in 1.8ms via its non-sensitive title/tags, and decrypt the secret on demand only after Master PIN verification.

4. Real SQLite Schema & Vault-Safe Trigger Pipeline

Here is the core schema and synchronization trigger set enforcing both FTS5 speed and vault isolation directly at the SQLite layer:

PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA temp_store = MEMORY; PRAGMA cache_size = -8192; CREATE TABLE IF NOT EXISTS notes ( id INTEGER PRIMARY KEY AUTOINCREMENT, category TEXT NOT NULL DEFAULT 'note', -- 'note' | 'card' | 'account' | 'api' is_encrypted INTEGER NOT NULL DEFAULT 0 CHECK (is_encrypted IN (0, 1)), title TEXT NOT NULL DEFAULT '', tags TEXT NOT NULL DEFAULT '', body TEXT NOT NULL DEFAULT '', -- ALWAYS '' when is_encrypted = 1 ciphertext_blob BLOB, -- AES-256-GCM (nonce || ciphertext || tag) updated_at INTEGER NOT NULL ); -- Standalone FTS5 table keyed by rowid = notes.id CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5( title, tags, body, tokenize = "unicode61 remove_diacritics 2 tokenchars '_-'", prefix = '2 3' ); -- Enforce vault isolation on INSERT: encrypted secrets NEVER enter FTS5 body CREATE TRIGGER IF NOT EXISTS notes_ai AFTER INSERT ON notes BEGIN INSERT INTO notes_fts(rowid, title, tags, body) VALUES ( NEW.id, NEW.title, NEW.tags, CASE WHEN NEW.is_encrypted = 1 OR NEW.category IN ('card', 'account', 'api') THEN '' ELSE NEW.body END ); END; -- Enforce vault isolation on UPDATE (including if a plaintext note is promoted to encrypted) CREATE TRIGGER IF NOT EXISTS notes_au AFTER UPDATE ON notes BEGIN DELETE FROM notes_fts WHERE rowid = OLD.id; INSERT INTO notes_fts(rowid, title, tags, body) VALUES ( NEW.id, NEW.title, NEW.tags, CASE WHEN NEW.is_encrypted = 1 OR NEW.category IN ('card', 'account', 'api') THEN '' ELSE NEW.body END ); END; CREATE TRIGGER IF NOT EXISTS notes_ad AFTER DELETE ON notes BEGIN DELETE FROM notes_fts WHERE rowid = OLD.id; END; 

5. Production Rust (rusqlite) Query & Sanitizer

Passing raw user keystrokes directly into an FTS5 MATCH clause will throw syntax errors whenever a developer searches for symbols like C++, std::vec, or unmatched quotes. QuickNote tokenizes user input safely in Rust, quotes each term defensively, appends a prefix wildcard (*) to activate the prefix='2 3' B-trees, and returns BM25-ranked hits:

use rusqlite::{params, Connection, Result}; #[derive(Debug, Clone, serde::Serialize)] pub struct SearchHit { pub id: i64, pub category: String, pub is_encrypted: bool, pub title: String, pub tags: String, pub snippet: String, pub bm25_score: f64, } /// Converts raw user input into a safe FTS5 prefix-AND query. /// Example: `aes-256 tok` -> `"aes-256"* AND "tok"*` pub fn build_safe_fts5_query(raw: &str) -> Option<String> { let terms: Vec<String> = raw .split_whitespace() .filter_map(|token| { let cleaned: String = token .chars() .filter(|c| c.is_alphanumeric() || *c == '_' || *c == '-') .collect(); if cleaned.is_empty() { None } else { // Quote token to prevent FTS5 operator injection (OR/NOT/NEAR) Some(format!("\"{}\"*", cleaned)) } }) .collect(); if terms.is_empty() { None } else { Some(terms.join(" AND ")) } } pub fn search_notes(conn: &Connection, raw_query: &str, limit: i64) -> Result<Vec<SearchHit>> { let Some(fts_query) = build_safe_fts5_query(raw_query) else { return Ok(Vec::new()); }; let mut stmt = conn.prepare_cached( r#" SELECT n.id, n.category, n.is_encrypted, n.title, n.tags, CASE WHEN n.is_encrypted = 1 THEN '[Encrypted Vault Entry]' ELSE snippet(notes_fts, 2, '<mark>', '</mark>', '...', 18) END AS preview, bm25(notes_fts, 10.0, 5.0, 1.0) AS rank_score FROM notes_fts JOIN notes n ON n.id = notes_fts.rowid WHERE notes_fts MATCH ?1 ORDER BY rank_score ASC, n.updated_at DESC LIMIT ?2 "#, )?; let rows = stmt.query_map(params![fts_query, limit], |row| { Ok(SearchHit { id: row.get(0)?, category: row.get(1)?, is_encrypted: row.get::<_, i64>(2)? == 1, title: row.get(3)?, tags: row.get(4)?, snippet: row.get(5)?, bm25_score: row.get(6)?, }) })?; rows.collect() } 

Notice conn.prepare_cached(...): reusing the compiled SQLite VDBE bytecode across consecutive keystrokes eliminates repeated SQL parser and query-planner overhead, shaving another ~0.2ms–0.4ms off every interactive search.

6. Step-by-Step Implementation Checklist

  1. Initialize WAL & memory pragmas once on connection open: Enable journal_mode=WAL, synchronous=NORMAL, temp_store=MEMORY, and a bounded page cache.
  2. Separate ciphertext storage from indexed plaintext: Store AES-256-GCM blobs in a dedicated ciphertext_blob column and force body = '' for encrypted vault rows.
  3. Create the FTS5 virtual table with developer-friendly tokenization: Configure unicode61 remove_diacritics 2 tokenchars '_-' and prefix='2 3'.
  4. Attach defensive triggers for insert, update, and delete: Ensure that converting an existing plaintext note into an encrypted vault item immediately purges its old body tokens from notes_fts.
  5. Sanitize user input & cache the prepared statement in Rust: Quote individual tokens to prevent FTS5 syntax errors, append * for prefix lookup, and rank via weighted bm25() ascending.
  6. Run periodic passive WAL checkpoints & FTS5 optimize: Schedule PRAGMA wal_checkpoint(PASSIVE) and INSERT INTO notes_fts(notes_fts) VALUES('optimize') during idle periods so the WAL file and inverted index segments stay compact.

7. Benchmark Comparison: 10,000 Developer Notes on Windows 11 (x64)

To verify real-world interactive performance, we benchmarked a synthetic corpus of 10,000 developer notes (averaging ~1.2 KB of mixed Markdown, Rust/SQL snippets, and tags per note; ~12 MB raw corpus) on Windows 11 x64 with an NVMe SSD, measuring median (p50) latency across 200 two-term prefix queries:

Search Architecture Median Latency (10k Notes) Relevance Ranking Offline / Air-Gap Encrypted Vault Safety
Naive SQL LIKE '%q%' ~38.0ms – 65.0ms None (boolean substring only) Yes Safe if body is blanked
SQLite FTS5 + WAL (QuickNote) 1.8ms (p50) Weighted BM25 (10 / 5 / 1) 100% Native Strict trigger isolation (title/tags only)
Cloud Search (SaaS / Hosted API) 90.0ms – 320.0ms+ BM25 / Vector No (fails offline) Requires uploading plaintext to server

"Fast local search is an indexing problem, but safe local search is a boundary problem. SQLite FTS5 plus WAL gets you to 1.8ms across 10,000 notes; keeping AES-256-GCM vault secrets strictly outside the inverted index ensures speed never silently compromises encryption at rest."

Try It in QuickNote v0.2.3

This architecture powers QuickNote, a native Windows 10 & 11 (x64) developer scratchpad and encrypted credential vault built in Rust 1.80+ and Tauri 2.0 (~15–25 MB RAM footprint, ~11.45 MB binary, sub-50ms Ctrl+Shift+Q summon). It is free for up to 50 local notes (with an optional $29 one-time Lifetime Pro upgrade for up to 3 personal Windows devices), and SHA256-verified installer and portable builds are published on GitHub Releases.

Read the original engineering post on the QuickNote blog: Sub-2ms Local Search Across 10,000 Notes.

Authoritative References