Architecture
MygramDB runs as a sidecar process alongside MySQL (8.4/9.7/26.x) or MariaDB (10.11+/11.x/12.x). It reads the upstream server's binlog (binary log) to build and maintain an in-memory full-text index, then serves search queries over TCP and HTTP. The server flavor is detected with a capability probe, so the same binary and config work with either.
The important boundary is ownership: MySQL/MariaDB remains the durable source of truth for writes and normal SQL. MygramDB keeps a derived search index that can be rebuilt from an initial snapshot plus binlog replay.
What is a sidecar?
A sidecar is a process added next to an existing system to take on one specific job, without replacing it. Here MySQL keeps handling writes and ordinary SQL, while MygramDB handles full-text search.
System Overview
Index vs document store
The index finds candidate documents fast. The document store (DocumentStore) holds what is needed to return and narrow those candidates: primary keys, filter values, and normalized text. They are separate on purpose: one is optimized for lookup, the other for retrieval.
Components:
- BinlogReader -- Connects to MySQL as a replica and receives the GTID-based binlog stream. The bytes are decoded into row-level events (INSERT, UPDATE, DELETE) by libmybinlog, a separate library.
- Index -- In-memory n-gram index. Maps n-gram strings to posting lists (sorted document ID sets).
- DocumentStore -- Maps internal DocIDs to MySQL primary keys and stores filter-column values and normalized text. DocIDs follow indexing order. When more than 65,536 documents are out of primary-key order, the server logs
primary_key_order_exceptions_highonce;SYNCof the table reassigns the IDs in primary-key order. It stores each filter-column name once; each document keeps its values in a small vector keyed by column ID, avoiding a copy of every name in every document. - SearchHandler -- Parses queries, executes the search pipeline, manages the query cache, and reads candidate text in bounded chunks for text-heavy stages.
- Dump -- A periodic write of the index state and GTID position to a dump file, so a restart does not need a full rebuild.
Data Flow
MygramDB operates in three phases:
Phase 1: Initial Snapshot
The listeners open before any table has data. Each table is then loaded by its own SYNC, with its own consistent snapshot, either run by an operator or, when replication.auto_initial_snapshot: true is configured, by a background loader that works through the uninitialized tables one at a time in configuration order. Reads of a table without data return 6029 until its load completes. The default is auto_initial_snapshot: false, so you choose when the initial MySQL read happens.
The following sequence shows the MySQL path:
On MySQL, the pre-snapshot GTID prevents a gap. Commits between that capture and the transaction start may be replayed; row application is idempotent. MariaDB instead uses the snapshot's exact binlog file and position, converted to a GTID with BINLOG_GTID_POS. See snapshot and binlog handoff for the source-specific behavior.
Phase 2: Live Replication
After the initial snapshot, MygramDB switches to binlog streaming.
The BinlogReader thread reads events into a bounded queue. A worker thread dequeues events and applies them to the index and document store. The queue absorbs short bursts while the two stages run independently; sustained writes faster than MygramDB can apply them can still build replication lag.
On connection loss, MygramDB retries the configured endpoint and resumes from the last applied or processed GTID position. Events after that position may be replayed and applied idempotently.
Phase 3: Query Processing
Search queries arrive via TCP (port 11016, default) or HTTP (port 8080, disabled by default) and are processed through the search pipeline.
Thread Model
MygramDB uses an event-driven Reactor I/O model for TCP connections. The reactor uses epoll (Linux) or kqueue (macOS) to multiplex connections on an event-loop thread and dispatches work to a bounded worker pool. The number of connections a deployment can handle depends on its workload and operating-system limits.
What is a Reactor I/O model?
A Reactor I/O model watches many connections from a small number of threads and hands work to a worker only when there is something to process. Because it does not create a thread per connection, idle connections cost almost nothing.
Concurrency model:
- The Reactor thread handles all TCP I/O (accept, read, write) via epoll/kqueue. No thread-per-connection overhead — thousands of idle connections consume no threads.
- Parsed requests are dispatched to the Worker Thread Pool for query execution.
- The Index and DocumentStore synchronize their own state. Searches take short shared accesses to obtain the data they need; binlog application coordinates its updates before publishing the new state.
- Candidate text is materialized in bounded chunks. The DocumentStore lock is released before BM25 scoring, term-frequency counting, and text post-filters, so those expensive stages do not keep the store locked.
- Cache invalidation uses reverse indexes for n-gram, filter, and text-sensitive dependencies. Its periodic LRU maintenance resumes from a bounded slice instead of sweeping every cache entry under one exclusive lock.
- Per-connection backpressure (
api.tcp.max_write_queue_bytes, default 16 MiB) force-closes slow clients whose write queue exceeds the cap, preventing memory exhaustion. - Atomic counters are used for statistics (query count, cache hits) to avoid lock contention on the hot path.
What is backpressure?
Backpressure stops the server's pending-send buffer from growing without bound when a client reads slowly. Closing connections that pass the cap keeps one slow client from consuming the whole process's memory.
All threads are joined on shutdown. No threads are detached.
Persistence
MygramDB persists its state as periodic dump files, not a write-ahead log (WAL).
What is a WAL?
A write-ahead log records every change sequentially as it happens. MygramDB treats MySQL as the source of truth, so instead of its own WAL it recovers from a periodic dump plus catch-up from the MySQL binlog.
How it works:
- A background scheduler periodically serializes the full index, document store, and current GTID position to disk.
- With
dump.load_on_startup: true, MygramDB triesdump.dir/default_filenameat startup. A successful restore resumes binlog replication from the saved GTID; this mode requiresreplication.start_from: snapshot. - Events between that GTID and the current MySQL position are replayed automatically. If the dump fails validation, the listeners open without data and each table is loaded in the background by a
SYNC.
If the dump restores but startup cannot catch up to the current MySQL position, MygramDB keeps serving the restored index with replication stopped. Readiness reports not_ready until replication recovers. See Snapshot and Dump Recovery for recovery steps.
Dump writes use atomic file operations (write to temp file, then rename) to prevent corruption if the process is interrupted during a dump.
When startup does not attempt a dump restore, enable replication.auto_initial_snapshot to build the initial index automatically, or run SYNC <table> (or SYNC <database>.<table> in multi-database configurations). A failed startup dump restore loads each uninitialized table in the background after the listeners open, even if auto_initial_snapshot is false.
Not a substitute for MySQL backups
MygramDB dump files exist to restore the search index quickly. Backups and point-in-time recovery for the source data remain MySQL's responsibility.
Memory Layout
Sizing reference. The figures below come from the published v1.14.0 benchmark run: 1.1M Wikipedia articles (1M English, 100K Japanese, avg. 666 chars) with verify_text: all, in a 32 GiB container. See Benchmarks for the full run.
| Component | Memory |
|---|---|
| Index (n-gram map + posting lists) | ~191 MB |
| DocumentStore + Text Store | ~1.78 GB |
| Total RSS | ~2.15 GB |
The server keeps normalized text even with verify_text: off, because highlighting is a query-level feature. verify_text controls post-filtering, not text storage. The FAQ explains how to use this benchmark for capacity planning.
Each configured filter column gets an ID once per table; a document stores its values in a small vector keyed by those IDs instead of repeating column names in a per-document map.
Stored text and document data dominate the benchmark above. Memory use depends on the data. OPTIMIZE chooses delta encoding or Roaring bitmaps based on posting-list density; inserts also convert delta lists that grow beyond 4,096 entries. Monitoring does not lock every table for every scrape: per-table values are aggregated into a bounded snapshot served by INFO, /metrics, and Prometheus. See How It Works for details on the adaptive compression.
For search pipeline details, see How It Works. For performance numbers, see Benchmarks.