Configuration
MygramDB accepts YAML or JSON configuration files. Files are validated against the built-in JSON Schema at startup, so unknown keys, wrong types, missing required fields, and invalid enum values fail fast.
How to read this page
To get running you only need the MySQL connection, tables, replication.server_id, and network.allow_cidrs. Everything else is worth reading once you want to tune search quality, memory use, or operations.
Minimal Example
mysql:
host: "127.0.0.1"
user: "repl_user"
password: "your_password"
database: "mydb"
tables:
- name: "articles"
text_source:
column: "content"
replication:
server_id: 83917
network:
allow_cidrs:
- "127.0.0.1/32"mysql.user, mysql.database, and at least one table are required after environment overrides are applied. The mysql block may be omitted when the values come from MYGRAM_MYSQL_USER and MYGRAM_MYSQL_DATABASE.
Replication is enabled by default. In that case replication.server_id is required: a non-zero value from 1 to 4294967295 that is unique among MySQL replicas and MygramDB instances.
What to do after the minimal config
Writing the config file does not load any data. After starting the server, synchronize each table you want with SYNC articles and confirm completion with SYNC STATUS.
What is server_id?
server_id is the identifier used for a MySQL replication connection. It must not collide with any other MySQL replica or MygramDB instance attached to the same MySQL. With a duplicate, the upstream cannot tell the two apart.
In the reference tables below, keys marked "Mutable with SET" can be changed on a running server; every other key takes effect at the next start.
MySQL / MariaDB Connection
MygramDB works with MySQL 8.4/9.7/26.x and MariaDB 10.11+/11.x/12.x. The same mysql section is used for both; MygramDB uses a capability probe to select the correct GTID format.
mysql:
host: "127.0.0.1"
port: 3306
user: "repl_user"
password: "your_password"
database: "mydb"
use_gtid: true
binlog_format: "ROW"
binlog_row_image: "FULL"
connect_timeout_ms: 3000
read_timeout_ms: 3600000
write_timeout_ms: 3600000
session_timeout_sec: 3600
datetime_timezone: "+09:00"
ssl_enable: true
ssl_ca: "/etc/mygramdb/mysql-ca.pem"
ssl_cert: "/etc/mygramdb/mysql-client-cert.pem"
ssl_key: "/etc/mygramdb/mysql-client-key.pem"
ssl_verify_server_cert: true
ignored_ddl_prefixes: []| Key | Type | Default | Meaning |
|---|---|---|---|
host | string | 127.0.0.1 | Source host |
port | integer | 3306 | Source port, 1–65535 |
user | string | none (required) | Replication account; must be non-empty after environment overrides |
password | string | "" | Account password |
database | string | none (required) | Default database for tables; a non-empty SQL identifier |
use_gtid | boolean | true | Only true is accepted |
binlog_format | string | ROW | Asserts the source's value; only ROW is accepted |
binlog_row_image | string | FULL | Asserts the source's value; only FULL is accepted |
connect_timeout_ms | integer | 3000 | Connect timeout in milliseconds, 100–60000 |
read_timeout_ms | integer | 3600000 | Read timeout in milliseconds, 1000–86400000 |
write_timeout_ms | integer | 3600000 | Write timeout in milliseconds, 1000–86400000 |
session_timeout_sec | integer | 3600 | Session timeout in seconds, 60–86400 |
datetime_timezone | string | +00:00 | Offset (±HH:MM) used to interpret DATETIME and DATE values and temporal required_filters literals |
ssl_enable | boolean | false | Turns TLS on |
ssl_verify_server_cert | boolean | true | Verifies the server certificate; keep true for verified TLS |
ssl_ca | string | "" | CA certificate that signed the server certificate; required when ssl_enable and ssl_verify_server_cert are both true |
ssl_cert, ssl_key | string | "" | Client certificate and key; needed only if the source requires client-certificate authentication |
ignored_ddl_prefixes | string[] | [] | Standalone DDL prefixes to skip; see below |
TLS is disabled by default. The example above enables it, so replace its certificate paths with files on your server. For a source without TLS, set ssl_enable: false and remove the certificate paths.
TIME values are durations in seconds and do not use the datetime_timezone offset. TIMESTAMP values are always handled as UTC.
DATETIME vs TIMESTAMP
MySQL DATETIME carries no timezone. MygramDB uses datetime_timezone to decide which timezone those values are in. TIMESTAMP is already normalized to UTC by MySQL, so this setting does not affect it.
Environment variables override these mysql keys, and they also work when the mysql block is absent. A variable set to an empty string counts as unset.
| Key | Environment variable |
|---|---|
mysql.host | MYGRAM_MYSQL_HOST |
mysql.port | MYGRAM_MYSQL_PORT |
mysql.user | MYGRAM_MYSQL_USER |
mysql.password | MYGRAM_MYSQL_PASSWORD |
mysql.database | MYGRAM_MYSQL_DATABASE |
MYGRAM_MYSQL_PORT must be an integer from 1 through 65535; an invalid value stops startup.
Add an ignored_ddl_prefixes entry only when you have reviewed an otherwise unclassified standalone DDL QUERY_EVENT and know it is safe to skip. Each entry must:
- be non-empty and contain no semicolon;
- begin (case-insensitively) with one of
ALTER,ANALYZE,CHECK,CREATE,DROP,OPTIMIZE,RENAME,REPAIR, orTRUNCATE. DML prefixes are rejected.
The list does not override the safety checks for configured tables and databases. DROP DATABASE or DROP SCHEMA for a configured database still stops replication, even when DROP is listed.
mysql.binlog_format and mysql.binlog_row_image do not change MySQL or MariaDB settings. Set binlog_row_metadata=FULL on the source as well. It is a server setting, not a MygramDB configuration key. See MySQL Replication for the required source and table checks.
Required MySQL Settings
log_bin = ON
binlog_format = ROW
binlog_row_image = FULL
binlog_row_metadata = FULL
binlog_checksum = CRC32These settings belong on the MySQL or MariaDB source. MygramDB validates them at startup and on reconnect and reports error 2008 when one is missing; its YAML mysql block does not configure the source server.
The source must also write uncompressed binlog events: set binlog_transaction_compression=OFF on MySQL or log_bin_compress=OFF on MariaDB. On MySQL, binlog_row_value_options must not include PARTIAL_JSON.
For MySQL, enable GTID:
gtid_mode = ON
enforce_gtid_consistency = ONFor MariaDB, GTID uses MariaDB's native domain-server-sequence format. Set server_id, enable row-based binlogging, and leave binlog_storage_engine unset.
If the source is itself a replica, enable log_replica_updates on MySQL or log_slave_updates on MariaDB so replicated changes are written to its binlog.
Each source connection runs SET SESSION max_execution_time = 0 on MySQL or SET SESSION max_statement_time = 0 on MariaDB, so a server-wide statement time limit does not cut off the initial snapshot. The statement affects only that session and needs no extra grant. When the source refuses it, the connection stays open and MygramDB logs session_statement_limit_not_lifted with the native error number. A limit that is still enforced (MySQL error 3024, MariaDB error 1969) is reported as error 2001 with a hint to exempt the account from the source or proxy limit. Automatic initial loading gives up on that table after this error; correct the limit and run SYNC <table>.
Required Privileges
GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'repl_user'@'%';
FLUSH PRIVILEGES;Narrowing the grant
In production you can scope SELECT to just the searchable databases instead of *.*. The initial SYNC still needs read access to the target tables, and binlog follow-up still needs REPLICATION SLAVE and REPLICATION CLIENT.
Table Configuration
Each table gets an effective identity of <database>.<table>.
MygramDB checks source requirements, primary-key uniqueness, foreign-key actions, and column definitions before replication. See MySQL Replication for the refusal conditions and error codes.
mysql:
database: "app_db"
tables:
- name: "articles" # Effective identity: app_db.articles
primary_key: "id"
text_source:
column: "content"
ngram_size: 2
kanji_ngram_size: 1
cross_boundary_ngrams: true
- database: "archive_db"
name: "articles" # Effective identity: archive_db.articles
primary_key: "id"
text_source:
concat: ["title", "body"]
delimiter: " "| Key | Type | Default | Meaning |
|---|---|---|---|
name | string | none (required) | Source table name |
database | string | value of mysql.database | Source database |
primary_key | string | id | A single-column PRIMARY KEY, or a single-column UNIQUE key declared NOT NULL |
text_source.column | string | none | One text column to index |
text_source.concat | string[] | none | Two or more columns concatenated before indexing |
text_source.delimiter | string | " " (one space) | Separator inserted between concat columns |
required_filters | list | [] | Conditions a row must meet to be indexed; see Filters |
filters | list | [] | Columns available to query-time FILTER; see Filters |
ngram_size, kanji_ngram_size, cross_boundary_ngrams, posting | See N-gram And Posting Lists | ||
synonyms | object | disabled | See Per-table Synonyms |
text_source takes exactly one of column and concat.
In a single-database configuration, bare references such as SEARCH articles hello work. When the configuration spans two or more databases, all TCP, CLI, C/C++, and HTTP references must use <database>.<table>.
What is a table identity?
A table identity is the name MygramDB uses to refer to one searchable table. With a single database, articles is enough; with several, the database has to be included, as in app_db.articles.
Configured column validation
MygramDB checks these rules before replication starts, so the initial loader and the binlog reader represent the same values.
- Names must be non-empty SQL identifiers without NUL bytes. They are not limited to ASCII: spaces,
$, Unicode, and embedded backticks are supported and safely quoted. - Table identity is the
(database, table)pair, and duplicate pairs are rejected. - Configured primary-key, text-source, and filter columns cannot use
FLOAT,JSON,GEOMETRYor its subtypes,VECTOR,ZEROFILL,BINARY,VARBINARY, anyBLOBtype, or a type this build cannot decode from a row image. - Character columns must use an
utf8mb4,utf8/utf8mb3, orasciicollation.
Filters
required_filters decide which rows are indexed. Rows that do not match these conditions are omitted from the index; during replication, rows moving out of the condition are removed and rows moving in are added.
required_filters vs filters
required_filters decide whether a row enters the index at all. filters register columns you can narrow by at query time. To keep soft-deleted rows out of search entirely, use required_filters; to let a search screen filter by status, use filters.
tables:
- name: "articles"
text_source:
column: "content"
required_filters:
- name: "enabled"
type: "int"
op: "="
value: 1
- name: "deleted_at"
type: "datetime"
op: "IS NULL"Each required_filters entry takes these keys:
| Key | Type | Default | Meaning |
|---|---|---|---|
name | string | none (required) | Column name |
type | string | none (required) | One of the filter types in the table below |
op | string | none (required) | =, !=, <, >, <=, >=, IS NULL, IS NOT NULL; a boolean filter accepts only =, !=, IS NULL, IS NOT NULL |
value | string, number, or boolean | none | Comparison value; omitted with IS NULL and IS NOT NULL, required otherwise. An empty string is accepted only for string, varchar, and text |
bitmap_index | boolean | false | Reserved; no effect |
A value that cannot be converted to the declared type, such as value: "abc" for type: "int", is rejected with error 1004. The check runs at configuration load, in mygramdb -t, and in CONFIG VERIFY, without connecting to the source. At startup the server exits with status 78.
filters are search-time filter columns. They do not affect which rows are indexed.
tables:
- name: "articles"
text_source:
column: "content"
filters:
- name: "status"
type: "int"
- name: "category"
type: "string"
- name: "created_at"
type: "datetime"Each filters entry takes these keys:
| Key | Type | Default | Meaning |
|---|---|---|---|
name | string | none (required) | Column name |
type | string | none (required) | One of the filter types in the table below |
dict_compress | boolean | false | Reserved; no effect |
bitmap_index | boolean | false | Reserved; no effect |
bucket | string | "" | minute, hour, or day; reserved, no effect |
A column listed in both required_filters and filters must have the same type in both places.
The configured type must match the column's declaration on the source:
| Filter type | Accepted source declaration |
|---|---|
tinyint | signed tinyint, including tinyint(1) |
tinyint_unsigned | tinyint unsigned |
smallint | signed smallint |
smallint_unsigned | smallint unsigned |
mediumint | signed mediumint |
mediumint_unsigned | mediumint unsigned |
int | signed int or integer |
int_unsigned | int unsigned or integer unsigned |
bigint | signed bigint |
bigint_unsigned | bigint unsigned |
double | double or real |
string, varchar, text | char, varchar, tinytext, text, mediumtext, or longtext |
datetime, date, timestamp, time | the corresponding source type |
boolean | signed tinyint(1) |
float, enum, and set are not accepted filter types. A FLOAT column is also refused as a primary key or text source, because the initial-load result and the binlog row image do not preserve the same value.
Boolean values, in query-time FILTER and in required_filters alike, are true/false or 1/0 in any letter case.
Date and time filters take different value formats in required_filters and in a search-time FILTER:
| Filter type | required_filters value | Search-time FILTER value |
|---|---|---|
datetime, date, timestamp | Epoch seconds, or an ISO date/time in the offset set by mysql.datetime_timezone. Fractional seconds are accepted; a trailing Z, numeric offset, or other suffix is rejected | Epoch seconds |
time | Signed duration seconds, or a MySQL TIME clock such as HH:MM:SS with optional fractional seconds, from -838:59:59 through 838:59:59 | Signed duration seconds |
Reserved filter keys
bitmap_index, dict_compress, and bucket are accepted by the schema and preserved across dumps, but they do not change behavior yet. Setting them has no effect on indexing or query performance.
N-gram And Posting Lists
tables:
- name: "articles"
ngram_size: 2
kanji_ngram_size: 1
cross_boundary_ngrams: true
posting:
block_size: 128
freq_bits: 0
use_roaring: "auto"| Key | Type | Default | Meaning |
|---|---|---|---|
ngram_size | integer | 2 | N-gram length for kana, ASCII/alphanumeric text, and other scripts outside CJK ideographs, 1–10 |
kanji_ngram_size | integer | effective ngram_size | N-gram length for CJK ideographs only, 0–10; 0 means use ngram_size |
cross_boundary_ngrams | boolean | true | Generates n-grams that cross a script boundary, such as 字A |
posting.block_size | integer | 128 | Reserved, 8–1024 |
posting.freq_bits | integer | 0 | Reserved; 0, 4, or 8 |
posting.use_roaring | string | auto | Reserved; auto, always, or never |
Set ngram_size: 1 explicitly only if you need unigram behavior.
What is an N-gram?
An N-gram is a short slice of a string. Because it splits by character rather than by word, it works without a dictionary even in languages that do not separate words with spaces.
Reserved posting keys
The whole posting block — block_size, freq_bits, and use_roaring — is validated and preserved across dumps but not yet enforced. Delta-to-Roaring conversion is driven by memory.roaring_threshold and by OPTIMIZE, not by use_roaring.
BM25 scoring and highlighting use stored normalized text. memory.verify_text controls n-gram candidate verification; it does not disable text storage and does not affect freq_bits.
Per-table Synonyms
Synonym expansion is configured per table, not globally.
Why synonyms are per table
The same word can mean different things in different tables — synonyms useful for a product catalogue may be wrong for an article archive. MygramDB therefore configures them under tables[*].synonyms rather than globally.
tables:
- name: "articles"
text_source:
column: "content"
synonyms:
enable: true
file: "/etc/mygramdb/articles-synonyms.tsv"| Key | Type | Default | Meaning |
|---|---|---|---|
synonyms.enable | boolean | false | Turns synonym expansion on for this table |
synonyms.file | string | "" | TSV file of synonym groups; required when enable is true |
TSV format, one group per line:
car automobile vehicle
fast quick rapid speedy
# comments are ignoredSearch for any term in a group expands to the rest of the group. Terms are normalized with the same text normalization settings as the index.
Identifier and Ingestion Limits
Protocol references use a bare table name only when one database is configured. In a multi-database setup, use <database>.<table>.
- Raw TCP: quote a whitespace-containing reference as one protocol token.
- Native C/C++ SDK: typed methods reject whitespace in names before constructing a command; raw command methods retain the TCP grammar.
- HTTP: percent-encode the table identity in the URL.
The ingestion limits below apply per value or document. Size limits are in bytes unless the row says otherwise:
| Item | Limit |
|---|---|
| Stored primary-key value | 1 MiB |
| Filters per document | 1,000 |
| Filter name | 1 KiB |
| String filter value | 64 KiB |
| Original text and normalized text | 16 MiB each |
The initial SYNC rejects a candidate snapshot that exceeds these limits. During binlog ingestion, an oversized value is an error and MygramDB does not advance the applied GTID past that event.
Replication
replication:
enable: true
auto_initial_snapshot: false
server_id: 83917
start_from: "snapshot"
queue_size: 10000| Key | Type | Default | Meaning |
|---|---|---|---|
enable | boolean | true | Follows the source binlog |
server_id | integer | 0 | Replication client ID, 1–4294967295 when replication is enabled, unique among replicas and MygramDB instances on the source. 0 is accepted only with replication disabled |
auto_initial_snapshot | boolean | false | Loads uninitialized tables in the background at startup |
start_from | string | snapshot | Where replication starts; see the table below |
queue_size | integer | 10000 | Capacity of the binlog reader's event queue, 100–1000000 |
reconnect_backoff_min_ms | integer | 500 | Reserved, 100–60000 |
reconnect_backoff_max_ms | integer | 10000 | Reserved, 1000–600000 |
Leave auto_initial_snapshot off to start the first load explicitly with SYNC <table> for each table you want to load. This avoids accidentally loading large tables on startup. Set it to true only when startup-time loading is intentional. With replication.enable: true, auto_initial_snapshot: true requires start_from: "snapshot", for single-table and multi-table deployments alike. dump.load_on_startup: true has the same requirement so replication resumes from the GTID stored in the restored dump instead of skipping changes. With replication disabled, both combinations are accepted and start_from is neither validated nor used.
start_from accepts:
| Value | Behavior |
|---|---|
snapshot | Resume from the GTID captured by the snapshot/dump |
latest | Start from the source's current GTID, ignoring older changes |
gtid=<position> | Start from a MySQL GTID set (UUID[:tag]:txn[-txn], comma-separated) or MariaDB GTID list (domain-server-seq, comma-separated) |
MySQL GTID transaction numbers must be below 2^63−1; MariaDB uses its separate domain-server-seq grammar. A single MySQL UUID:txn or UUID:tag:txn position means through that transaction. A malformed gtid=... value, including one holding only separators such as gtid=,, is rejected during config validation.
If replay can include TABLE_MAP events written before the source enabled binlog_row_metadata=FULL, run SYNC for every replicated table after changing the source setting.
Startup and Readiness
The TCP listener, and the HTTP listener when enabled, open before the initial load. A table that has no data yet rejects reads with error 6029 (HTTP 503), so check readiness before sending queries: GET /health/ready, or the readiness field of the TCP INFO reply, which carries a readiness_reason line while the server is not ready. mygram-cli --wait-ready INFO blocks until the reply reports ready.
With auto_initial_snapshot: true, or dump.load_on_startup: true when no dump is restored, tables load in the background one at a time in configuration order, each from its own consistent snapshot. A dump restored at startup completes before the listeners open. The server stays not ready until every table has initial data.
The automatic loader retries source failures 2000, 2002, and 2004. The first retry waits 5 seconds and the delay doubles with each consecutive failure, up to 300 seconds. After the fifth retryable failure past the snapshot query, or on a permanent failure, loading of that table stops and the log shows startup_load_abandoned at error level with the table, error code, message, and budget used. The process keeps running; correct the cause and run SYNC <table>. While an automatic attempt is in flight, SYNC, DUMP SAVE, DUMP LOAD, OPTIMIZE, and REPLICATION START return error 4011, so run the manual command between attempts or after the loader finishes.
The log records server_listening once the listeners are open and server_ready once every configured table has initial data. With neither automatic loading nor a startup dump, tables stay empty until SYNC or DUMP LOAD initializes them, and server_ready is logged when the last table is initialized.
Index Build
build:
mode: "select_snapshot"
batch_size: 5000| Key | Type | Default | Meaning |
|---|---|---|---|
mode | string | select_snapshot | Only select_snapshot is accepted |
batch_size | integer | 5000 | Rows fetched per round during the initial load started by SYNC, 100–100000 |
parallelism | integer | 2 | Reserved, 1–64 |
throttle_ms | integer | 0 | Reserved, 0–10000 |
Reserved build keys
parallelism and throttle_ms are validated but not yet enforced; the initial load is single-threaded and unthrottled.
Memory
memory:
hard_limit_mb: 8192
soft_target_mb: 4096
roaring_threshold: 0.18
normalize:
nfkc: true
width: "narrow"
lower: false
verify_text: "off"| Key | Type | Default | Meaning |
|---|---|---|---|
hard_limit_mb | integer | 8192 | Reserved; enforces no process memory limit. 256–2147483647 |
soft_target_mb | integer | 4096 | Reserved, 128–2147483647 |
arena_chunk_mb | integer | 64 | Reserved, 1–1024 |
minute_epoch | boolean | true | Reserved |
roaring_threshold | number | 0.18 | Posting-list density, 0.0–1.0, at which a delta-encoded list becomes a Roaring bitmap |
normalize.nfkc | boolean | true | Unicode NFKC normalization |
normalize.width | string | narrow | Character-width handling: keep, narrow, or wide |
normalize.lower | boolean | false | Lowercasing |
verify_text | string | off | N-gram candidate verification: off, ascii, or all; see below |
Size the host so the full index and stored normalized text fit in RAM.
The normalize settings affect indexed text and queries alike. A dump must use the same normalization settings as the running configuration.
About the memory limit
hard_limit_mb does not currently stop the process at the OS level. In production, estimate from the row count, stored text, verify_text mode, and cache size, then provision enough RAM.
verify_text values:
| Value | Behavior |
|---|---|
off | Fastest, no candidate verification; n-gram false positives are possible |
ascii | Verify ASCII-only queries |
all | Verify all queries; recommended when exact result semantics matter |
Normal startup retains normalized text regardless of verify_text, so HIGHLIGHT can use it with verify_text: "off" as well. BM25 _score sorting also uses stored text to count term frequency.
Persistence
dump:
dir: "/var/lib/mygramdb/dumps"
default_filename: "mygramdb.dmp"
load_on_startup: false
interval_sec: 7200
retain: 3
restore_memory_budget_mb: 4096
restore_max_section_mb: 2048| Key | Type | Default | Meaning |
|---|---|---|---|
dir | string | /var/lib/mygramdb/dumps | Dump directory |
default_filename | string | mygramdb.dmp | File used by DUMP SAVE when no path is given; a basename without / or \. DUMP SAVE . is refused |
load_on_startup | boolean | false | Tries the default dump before a MySQL snapshot, validates the source identity and GTID, and falls back to MySQL if the dump cannot be loaded. With replication enabled, requires replication.start_from: "snapshot" |
interval_sec | integer | 0 | Seconds between automatic dumps, 0–86400; 0 disables them. The example uses 7200 (two hours) |
retain | integer | 3 | Number of automatic dumps kept, 1–100; older automatic dumps in dir are deleted, manual dumps are not |
restore_memory_budget_mb | integer | 4096 | Bounds the total staged data during a V2 restore, 1–1048576 |
restore_max_section_mb | integer | 2048 | Bounds one encoded V2 section, 1–1048576 |
DUMP SAVE rejects documents that exceed the restore limits instead of writing a dump that cannot be loaded. Every configured table must have completed its initial load before DUMP SAVE, otherwise it returns error 6029. In a MySQL-enabled build with a binlog reader, a GTID position is also required, and a missing position returns 6029.
Put the dump directory on persistent storage
Under Docker or Kubernetes, point dump.dir at a persistent volume. Writing dumps to the container's ephemeral filesystem loses them when the container is recreated.
API Server
api:
tcp:
bind: "127.0.0.1"
port: 11016
max_connections: 10000
worker_threads: 0
recv_timeout_sec: 60
idle_timeout_sec: 300
reaper_interval_sec: 5
thread_pool_queue_size: 1000
max_write_queue_bytes: 16777216
max_total_buffered_bytes: 268435456
max_pending_frames: 1024
max_pending_frame_bytes: 4194304
keepalive:
enabled: true
idle_sec: 60
interval_sec: 20
probe_count: 3
unix_socket:
path: ""
http:
enable: false
bind: "127.0.0.1"
port: 8080
max_connections: 10000
trusted_proxies: []
enable_cors: false
cors_allow_origin: ""
max_body_bytes: 16777216
read_timeout_sec: 5
write_timeout_sec: 5
default_limit: 100
max_query_length: 128
admin_token: "replace-with-a-high-entropy-secret"api.tcp keys:
| Key | Type | Default | Meaning |
|---|---|---|---|
bind | string | 127.0.0.1 | Listen address: an IP literal or hostname |
port | integer | 11016 | Listen port, 1–65535 |
max_connections | integer | 10000 | Concurrent connections, 1–1000000 |
worker_threads | integer | 0 | Worker threads, 0–16384; 0 selects the count automatically |
recv_timeout_sec | integer | 60 | Deadline for a connection's first request, 0–86400; 0 disables it |
idle_timeout_sec | integer | 300 | Idle connections are closed after this many seconds, 0–86400; 0 disables idle reaping |
reaper_interval_sec | integer | 5 | Interval between idle-connection checks, 1–3600 |
thread_pool_queue_size | integer | 1000 | Tasks queued for workers, 0–1000000; 0 means unbounded |
max_write_queue_bytes | integer | 16777216 (16 MiB) | Unsent response bytes per connection, 4096–1073741824 |
max_total_buffered_bytes | integer | 268435456 (256 MiB) | Read and write buffer budget shared by all connections, 1048576–68719476736 |
max_pending_frames | integer | 1024 | Completed requests per connection waiting for a worker, 4–1000000 |
max_pending_frame_bytes | integer | 4194304 (4 MiB) | Per-connection byte budget for pending requests, 4096–1073741824 |
keepalive.enabled | boolean | true | Enables TCP keepalive |
keepalive.idle_sec | integer | 60 | Idle seconds before the first probe, 1–86400 |
keepalive.interval_sec | integer | 20 | Seconds between probes, 1–3600 |
keepalive.probe_count | integer | 3 | Unanswered probes before the connection is dropped, 1–32 |
Reads on a connection pause at 75% of either pending-request limit and resume when the queue falls to 50%.
api.http keys:
| Key | Type | Default | Meaning |
|---|---|---|---|
enable | boolean | false | Starts the HTTP listener |
bind | string | 127.0.0.1 | Listen address: an IP literal or hostname |
port | integer | 8080 | Listen port, 1–65535 |
max_connections | integer | 10000 | Admitted HTTP connections, including sockets waiting for workers, 1–1000000 |
trusted_proxies | string[] | [] | Numeric IP addresses of reverse proxies whose X-Forwarded-For value may set the client identity for ACLs and rate limiting; leave empty unless requests arrive through those proxies |
enable_cors | boolean | false | Enables CORS responses |
cors_allow_origin | string | "" | The single origin value returned with CORS enabled; it is not a list. Required when enable and enable_cors are both true |
max_body_bytes | integer | 16777216 (16 MiB) | Request body limit, 0–1073741824; 0 removes the limit |
read_timeout_sec | integer | 5 | Read timeout, 1–3600 |
write_timeout_sec | integer | 5 | Write timeout, 1–3600 |
Top-level api keys:
| Key | Type | Default | Meaning |
|---|---|---|---|
default_limit | integer | 100 | Result count when a query has no LIMIT, 5–1000. Mutable with SET |
max_query_length | integer | 128 | Query length limit in Unicode characters, 0–4096; 0 removes the limit. Mutable with SET |
admin_token | string | "" | Shared secret for administrative commands; see Administrative authentication |
unix_socket.path | string | "" | Unix socket path; empty disables it. A configured socket replaces the TCP listener |
To use a Unix socket, set api.unix_socket.path and connect with mygram-cli -s /path/to/mygramdb.sock. On startup, MygramDB removes an existing socket only when a connection probe confirms it is stale. It refuses to replace a regular file, an active socket, or a path whose status is uncertain, with error 6015.
What TCP and HTTP each handle
The TCP API serves search plus administrative commands such as SYNC, DUMP, and SET. The HTTP API covers search, count, facet, document lookup, health, metrics, and POST /optimize.
Administrative authentication
api.admin_token is a shared secret for administrative commands. Set it in the configuration file or through MYGRAM_API_ADMIN_TOKEN; use a high-entropy value and keep it out of source control. The environment override also applies when the api block is absent. The token is mandatory when TCP binds to a non-loopback address without a Unix socket, or when HTTP is enabled on a non-loopback address. A Unix socket only exempts the TCP listener; it does not exempt HTTP.
Authenticate a TCP connection before administrative commands:
AUTH replace-with-a-high-entropy-secret
SYNC articlesPOST /optimize requires the same token as an HTTP Bearer credential:
curl -X POST http://127.0.0.1:8080/optimize \
-H "Authorization: Bearer $MYGRAM_API_ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{}'Rate Limiting
api:
rate_limiting:
enable: true
capacity: 100
refill_rate: 10
max_clients: 10000| Key | Type | Default | Meaning |
|---|---|---|---|
enable | boolean | false | Turns rate limiting on. Mutable with SET |
capacity | integer | 100 | Maximum burst in requests per client, 1–10000. Mutable with SET |
refill_rate | integer | 10 | Tokens added per client per second, 1–1000. Mutable with SET |
max_clients | integer | 10000 | Tracked client buckets, 10–100000; it does not limit admitted clients |
TCP and HTTP share one rate limiter and one per-client token bucket, so a client cannot double its quota by spreading requests across protocols. Size capacity and refill_rate for a client's combined TCP and HTTP traffic.
Network Security
network:
allow_cidrs:
- "127.0.0.1/32"
- "10.0.0.0/8"| Key | Type | Default | Meaning |
|---|---|---|---|
allow_cidrs | string[] | [] | IPv4 and IPv6 CIDRs allowed to connect; an empty or omitted list denies every connection |
Add only the application server and operator networks that need access. MygramDB has no native TLS, so terminate TLS at a reverse proxy or load balancer when needed. Administrative commands use api.admin_token; ordinary search endpoints remain protected by the bind address and CIDR allowlist. The allowlist also applies to the health endpoints, so a probe running on the same host needs 127.0.0.1/32 (and ::1/128 when localhost resolves over IPv6).
IPv4-mapped IPv6 CIDRs with prefixes shorter than /96 are rejected because they do not map to a valid IPv4 range. Prefixes from /96 through /128 are folded into the corresponding IPv4 range.
Either 0.0.0.0/0 or ::/0 allows connections from every IPv4 and IPv6 address. Either is rejected when paired with a non-loopback TCP or enabled HTTP listener.
Never expose it directly to a public network
Do not publish MygramDB directly to the internet. A configuration with 0.0.0.0/0 or ::/0 in allow_cidrs and a non-loopback TCP or enabled HTTP bind is rejected at startup. Use a restrictive CIDR list, or keep the listener on loopback behind a reverse proxy.
Query Cache
cache:
enabled: true
max_memory_mb: 32
min_query_cost_ms: 10.0
ttl_seconds: 3600
invalidation_strategy: "ngram"
compression_enabled: true
eviction_batch_size: 10
invalidation:
batch_size: 1000
max_delay_ms: 100
max_queue_size: 100000| Key | Type | Default | Meaning |
|---|---|---|---|
enabled | boolean | true | Turns the cache on. Mutable with SET |
max_memory_mb | integer | 32 | Shared budget for cached results, cache containers, indexes, invalidation metadata, and the deferred invalidation queue, 1–1048576; with the cache enabled, also at most 50% of detected physical memory |
min_query_cost_ms | number | 10.0 | Only queries slower than this are cached; 0.0 or more, and finite when set at runtime. Mutable with SET |
ttl_seconds | integer | 3600 | Entry lifetime, 0–2147483647; 0 disables expiry. Mutable with SET |
invalidation_strategy | string | ngram | ngram or table; see below |
compression_enabled | boolean | true | Compresses cached results |
eviction_batch_size | integer | 10 | Minimum entries evicted per capacity pass, 1–2147483647 |
invalidation.batch_size | integer | 1000 | Queued entries that trigger an invalidation pass, 1–2147483647 |
invalidation.max_delay_ms | integer | 100 | Longest wait before queued invalidations are processed, 0–2147483647 |
invalidation.max_queue_size | integer | 100000 | Pending invalidations before backpressure, 1 or more |
If physical memory cannot be detected, the 50% check is skipped with a warning.
Caching only slow queries keeps cheap lookups from evicting useful entries. invalidation_strategy: "ngram" invalidates just the entries whose terms overlap a changed row; "table" drops every entry for the table, which is cheaper to compute but far more destructive.
See Operations Guide for the CACHE STATS / CACHE CLEAR commands.
Relevance Scoring (BM25)
bm25:
enable: false
k1: 1.2
b: 0.75| Key | Type | Default | Meaning |
|---|---|---|---|
enable | boolean | false | Enables BM25 scoring and SORT _score |
k1 | number | 1.2 | Term-frequency saturation, 0.0 or more; higher values let repeated terms keep raising the score |
b | number | 0.75 | Document-length normalization, from 0.0 (off) to 1.0 (full) |
SORT _score fails with SORT _score requires BM25 to be enabled in configuration until enable is true; normal startup stores the normalized text it needs regardless of memory.verify_text.
Logging
logging:
level: "info"
format: "json"
file: ""| Key | Type | Default | Meaning |
|---|---|---|---|
level | string | info | debug, info, warn, or error. Mutable with SET |
format | string | json | json or text. Mutable with SET |
file | string | "" | Log file path; empty logs to stdout, the recommended mode for Docker and systemd. A log file rotates at 100 MiB and keeps 5 rotated files |
Runtime Variables
Use MySQL-style commands over the TCP protocol:
SHOW VARIABLES
SHOW VARIABLES LIKE 'cache%'
SET logging.level = 'debug'
SET cache.enabled = false
SET api.default_limit = 200The mutable keys are api.default_limit, api.max_query_length, api.rate_limiting.enable, api.rate_limiting.capacity, api.rate_limiting.refill_rate, cache.enabled, cache.min_query_cost_ms, cache.ttl_seconds, logging.level, and logging.format; SHOW VARIABLES marks them mutable. Every other key requires a restart. If MygramDB was started with --schema, that schema's constraints also apply to SET. A failed SET returns one of these errors:
| Error | Cause |
|---|---|
| 1004 | The value is outside the key's range or violates the --schema constraints |
| 1008 | Unknown variable |
| 1009 | Startup-only variable |
Command-Line Options
mygramdb takes a configuration file path, either with -c or as a single positional argument. No option overrides a configuration key; the only override mechanism is the environment variables described above.
| Option | Effect |
|---|---|
-c, --config <file> | Configuration file to load |
-d, --daemon | Daemonize. Relative paths in dump.dir, logging.file, mysql.ssl_ca, mysql.ssl_cert, mysql.ssl_key, api.unix_socket.path, and each tables[].synonyms.file are made absolute first |
-t, --config-test | Load and validate the configuration and the files it references, print a summary, and exit without connecting to MySQL |
--check-source | Run the -t validation, then connect to the source once and run the startup source and table checks |
-s, --schema <file> | Validate the configuration against this schema in addition to the built-in one |
-h, --help | Print usage and exit 0 |
-v, --version | Print the version and exit 0 |
--print-surface | Print the external surface snapshot and exit 0 without reading a configuration file |
--check-source ignores -d, runs once even when repeated or combined with -t, and reports one of these outcomes:
Source check skipped: this configuration does not connect to MySQLand exit 0, when replication, automatic initial loading, and startup dump restore are all disabled.- A failed connection writes
[<code description> (<code>)] Failed to connect to MySQL: <client error>to stderr. Source requirement checks skipped: replication is disabledand exit 0, when the connection succeeds and replication is disabled.- With replication enabled, server requirements are checked first and a failure is reported alone. Otherwise each configured table is checked, and one line
[<code description> (<code>)] <message>is written to stderr per failing table in configuration order. Messages start withConnection validation failed:for the server andTable '<database>.<table>' does not meet the table requirements:for a table. The first diagnostic determines the exit status. Source meets the requirementsand exit 0 when every check passes.
The check covers the connection and source-validation stage of startup. Dump restore, reader initialization, and opening the listeners happen only in a normal start.
Exit Status
| Status | Condition |
|---|---|
| 0 | Normal exit, graceful startup cancellation, or a successful check, including a skipped source check |
| 78 | Argument, configuration file, configuration validation, or table initialization failure; an invalid TLS or synonym file reference found by -t; refusal to run as root; source authentication failure (2003); a diagnosed source requirement failure such as missing grants, an unsupported source setting, or an incompatible table |
| 1 | Anything else: an unreachable source, a source check that returns 2000, 2001, 2002, or 2004, log or dump directory setup failure, daemonization failure, reader initialization or start failure, or a listener bind failure |
With -d, the launcher exits 0 once it hands off to the daemon; a later daemon error does not change that status.
Status 78 means the same start will fail again. The systemd units shipped in the packages and in support/systemd set RestartPreventExitStatus=78 next to Restart=on-failure, so a configuration error stops the service instead of looping. A hand-written unit that uses Restart=on-failure should add the same line. After fixing the cause, start the service again.
Configuration Validation
Every load checks the file against the built-in schema and then the rules that span several keys, such as the start_from and admin_token requirements above. Any failure stops startup with status 78. Three commands run these checks without serving traffic:
| Command | Checks | Connects to MySQL |
|---|---|---|
mygramdb -t -c <file> | The configuration, plus the TLS files (when ssl_enable is true) and enabled synonym files it references | No |
mygramdb --check-source -c <file> | Everything -t checks, then the startup source and table requirements | Once |
CONFIG VERIFY <filepath> over TCP | A candidate file placed next to the active configuration | No |
CONFIG VERIFY does not apply environment overrides, so it inspects the file as written. A configuration that supplies mysql.user only through MYGRAM_MYSQL_USER starts normally but fails CONFIG VERIFY.
Path keys (mysql.ssl_ca, mysql.ssl_cert, mysql.ssl_key, dump.dir, logging.file, api.unix_socket.path, and tables[].synonyms.file) reject a .. component and NUL bytes.
These conditions log a warning and startup continues:
| Condition | Log event | Effect |
|---|---|---|
network.allow_cidrs is empty or omitted | network_acl_empty | Every connection is denied, health probes included |
| Physical memory cannot be detected | config_warning with reason system_memory_info_unavailable | The 50% check on cache.max_memory_mb is skipped |
dump.load_on_startup: true and the dump cannot be read or fails its integrity or identity check | startup_dump_load_failed with action: fallback_to_mysql_snapshot | Uninitialized tables load from MySQL in the background |