1. Production Pain Points and Architecture Trade-offs
The most common failure mode of Elasticsearch in small teams is not insufficient performance but operational cost disproportionate to actual load: a 3-node cluster starts at 6-8 GB heap, JVM tuning, shard rebalancing, and certificate rotation, while the real corpus is often only a few hundred thousand to a few million documents. SQLite FTS5 on a single box handles this comfortably: roughly 300-600 MB on disk for 1M documents of ~1 KB each, query P99 in the 5-30 ms range (trigram prefix/substring queries are slower than token queries), and resident memory under 64 MB.
Three architectural decisions matter:
- Dual index, not a single index. The
unicode61tokenizer splits on whitespace and punctuation and is extremely fast for Latin text, but a whole Chinese sentence becomes one token, so searching for数据库will not match分布式数据库. Thetrigramtokenizer slides a 3-character window over the text, natively supporting CJK substrings and arbitrary substring queries, at the cost of an index roughly 3-5x the source size and a hard minimum of 3 characters per query. This blueprint therefore maintains bothdocs_unianddocs_tri, routing queries based on whether the input contains CJK or is shorter than 3 characters. - External content over contentless. Using
content='docs'keeps only the inverted index in FTS5 while the body lives in thedocstable, saving roughly 40% of space, andsnippet()/bm25()still work. The cost: deletes and updates must explicitly write the'delete'command through triggers, otherwise the index drifts from the source of truth — the single most common production incident with this design. - WAL plus BEGIN IMMEDIATE. Writers take the write lock immediately with
BEGIN IMMEDIATE, avoidingSQLITE_BUSYfrom deferred-transaction lock upgrades; WAL lets readers proceed without blocking writers, andbusy_timeout=5000covers the typical single-writer/multi-reader search service.
2. Step-by-Step Deployment and Permission Hardening
Step 1: Verify SQLite version and compile options. The trigram tokenizer requires SQLite >= 3.34.0 and FTS5 compiled in. Run python3 -c "import sqlite3;print(sqlite3.sqlite_version)". If below 3.34, upgrade the system libsqlite3 or use an official Python build. Verify trigram support with python3 -c "import sqlite3;c=sqlite3.connect(':memory:');c.execute(\"CREATE VIRTUAL TABLE t USING fts5(x, tokenize='trigram')\")" — no exception means it is available.
Step 2: Create a dedicated system user and directories. Never run the indexer as root:
sudo useradd --system --home /var/lib/fts --shell /usr/sbin/nologin fts
sudo install -d -o fts -g fts -m 0750 /var/lib/fts /var/log/fts
sudo install -m 0755 fts_indexer.py /usr/local/bin/fts_indexer.pySet the database file to 0640 owned by fts:fts. If the search service is separate from the indexer, add the search process to the fts group. Note that SQLite WAL readers need write access to the directory to create -shm/-wal files; alternatively open a read-only connection with PRAGMA query_only=1 and accept the WAL read-only constraints.
Step 3: Systemd unit (optional, for scheduled incremental sync).
[Unit]
Description=FTS5 incremental indexer
After=network.target
[Service]
Type=oneshot
User=fts
Group=fts
Environment=FTS_DB=/var/lib/fts/fts.db FTS_LOG_LEVEL=INFO
ExecStart=/usr/bin/python3 /usr/local/bin/fts_indexer.py upsert --source cms --ext-id %i --body-file /dev/stdin
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=/var/lib/fts
PrivateTmp=trueStep 4: Initial build and bulk import. Use the upsert subcommand per document, or wrap a JSONL reader in a loop. Run optimize every 5000 documents to merge b-tree segments; it briefly holds the write lock, so schedule it off-peak.
Step 5: Backups. Never cp a live database file. Use sqlite3 /var/lib/fts/fts.db ".backup '/var/lib/fts/backup-$(date +%F).db'", which produces a consistent snapshot under WAL.
3. Parameter Tuning and Load Verification
Balancing index size against query latency. Trigram indexes are large; if the corpus is mostly English, keep only docs_uni; if mostly Chinese, keep both. Measure with:
sqlite3 /var/lib/fts/fts.db "SELECT name, SUM(pgsize)/1024/1024 AS mb FROM dbstat GROUP BY name ORDER BY mb DESC LIMIT 10;"Load testing queries. Use hyperfine or a simple loop to measure P50/P99:
for i in $(seq 1 200); do
/usr/bin/time -f "%e" python3 /usr/local/bin/fts_indexer.py --db /var/lib/fts/fts.db search "分布式数据库" --limit 10 >/dev/null
done 2>&1 | sort -n | awk '{a[NR]=$1} END{print "P50="a[int(NR*0.5)]" P99="a[int(NR*0.99)]"}'Key PRAGMA tuning. synchronous=NORMAL under WAL already guarantees crash consistency (at most the last transaction is lost) and is 3-5x faster than FULL. cache_size=-64000 (64 MB page cache) pays off for read-heavy workloads. mmap_size=268435456 (256 MB) reduces read syscalls but must be weighed against RSS. For bulk writes, raising wal_autocheckpoint from the default 1000 pages to 4000 reduces checkpoint jitter.
Query construction pitfalls. Under unicode61 you must quote user input (the code does " ".join(f'"{w}"' ...)), otherwise AND/OR/NEAR are parsed as FTS5 syntax and raise OperationalError. Under trigram, pass the raw string, but reject queries shorter than 3 characters — FTS5 trigram returns nothing for shorter MATCH terms.
4. Troubleshooting and Safe Rollback
Issue 1: database is locked. Usually a long transaction or a missing busy_timeout. Diagnose with sqlite3 fts.db "PRAGMA wal_checkpoint;" to see if it blocks, and fuser -v /var/lib/fts/fts.db* to find the holder. Fix by ensuring every connection sets busy_timeout, routing all writes through BEGIN IMMEDIATE, and never doing network IO inside a transaction.
Issue 2: Results diverge from the source (ghost rows). Almost always caused by bypassing triggers with a direct UPDATE docs or DELETE FROM docs; external content tables do not observe those automatically. Fix by routing all writes through upsert(). If drift has already occurred, rebuild with INSERT INTO docs_uni(docs_uni) VALUES('rebuild') and the same for docs_tri — a full scan, tens of seconds for a million rows.
Issue 3: Chinese queries return nothing. Check whether the query was misrouted to docs_uni. Confirm with EXPLAIN QUERY PLAN, or directly run SELECT * FROM docs_tri WHERE docs_tri MATCH '数据库' to verify the trigram index exists.
Issue 4: Disk usage spikes. An unreclaimed WAL file usually means a long-running read transaction is blocking checkpoint. PRAGMA wal_checkpoint(TRUNCATE) forces truncation but blocks writers. The durable fix is to monitor -wal size and alert above 256 MB.
Safe rollback. Take a .backup snapshot before every schema change or bulk import. To roll back: stop the service, mv fts.db fts.db.broken, cp backup-YYYY-MM-DD.db fts.db, restart. Because the FTS5 indexes can be fully rebuilt from the docs table, the worst case only requires preserving docs data to restore all search capability — a major operational advantage over Elasticsearch snapshot recovery.