Skip to content

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 ​

yaml
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.

yaml
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: []
KeyTypeDefaultMeaning
hoststring127.0.0.1Source host
portinteger3306Source port, 1–65535
userstringnone (required)Replication account; must be non-empty after environment overrides
passwordstring""Account password
databasestringnone (required)Default database for tables; a non-empty SQL identifier
use_gtidbooleantrueOnly true is accepted
binlog_formatstringROWAsserts the source's value; only ROW is accepted
binlog_row_imagestringFULLAsserts the source's value; only FULL is accepted
connect_timeout_msinteger3000Connect timeout in milliseconds, 100–60000
read_timeout_msinteger3600000Read timeout in milliseconds, 1000–86400000
write_timeout_msinteger3600000Write timeout in milliseconds, 1000–86400000
session_timeout_secinteger3600Session timeout in seconds, 60–86400
datetime_timezonestring+00:00Offset (±HH:MM) used to interpret DATETIME and DATE values and temporal required_filters literals
ssl_enablebooleanfalseTurns TLS on
ssl_verify_server_certbooleantrueVerifies the server certificate; keep true for verified TLS
ssl_castring""CA certificate that signed the server certificate; required when ssl_enable and ssl_verify_server_cert are both true
ssl_cert, ssl_keystring""Client certificate and key; needed only if the source requires client-certificate authentication
ignored_ddl_prefixesstring[][]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.

KeyEnvironment variable
mysql.hostMYGRAM_MYSQL_HOST
mysql.portMYGRAM_MYSQL_PORT
mysql.userMYGRAM_MYSQL_USER
mysql.passwordMYGRAM_MYSQL_PASSWORD
mysql.databaseMYGRAM_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, or TRUNCATE. 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 ​

ini
log_bin = ON
binlog_format = ROW
binlog_row_image = FULL
binlog_row_metadata = FULL
binlog_checksum = CRC32

These 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:

ini
gtid_mode = ON
enforce_gtid_consistency = ON

For 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 ​

sql
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.

yaml
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: " "
KeyTypeDefaultMeaning
namestringnone (required)Source table name
databasestringvalue of mysql.databaseSource database
primary_keystringidA single-column PRIMARY KEY, or a single-column UNIQUE key declared NOT NULL
text_source.columnstringnoneOne text column to index
text_source.concatstring[]noneTwo or more columns concatenated before indexing
text_source.delimiterstring" " (one space)Separator inserted between concat columns
required_filterslist[]Conditions a row must meet to be indexed; see Filters
filterslist[]Columns available to query-time FILTER; see Filters
ngram_size, kanji_ngram_size, cross_boundary_ngrams, postingSee N-gram And Posting Lists
synonymsobjectdisabledSee 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, GEOMETRY or its subtypes, VECTOR, ZEROFILL, BINARY, VARBINARY, any BLOB type, or a type this build cannot decode from a row image.
  • Character columns must use an utf8mb4, utf8/utf8mb3, or ascii collation.

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.

yaml
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:

KeyTypeDefaultMeaning
namestringnone (required)Column name
typestringnone (required)One of the filter types in the table below
opstringnone (required)=, !=, <, >, <=, >=, IS NULL, IS NOT NULL; a boolean filter accepts only =, !=, IS NULL, IS NOT NULL
valuestring, number, or booleannoneComparison value; omitted with IS NULL and IS NOT NULL, required otherwise. An empty string is accepted only for string, varchar, and text
bitmap_indexbooleanfalseReserved; 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.

yaml
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:

KeyTypeDefaultMeaning
namestringnone (required)Column name
typestringnone (required)One of the filter types in the table below
dict_compressbooleanfalseReserved; no effect
bitmap_indexbooleanfalseReserved; no effect
bucketstring""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 typeAccepted source declaration
tinyintsigned tinyint, including tinyint(1)
tinyint_unsignedtinyint unsigned
smallintsigned smallint
smallint_unsignedsmallint unsigned
mediumintsigned mediumint
mediumint_unsignedmediumint unsigned
intsigned int or integer
int_unsignedint unsigned or integer unsigned
bigintsigned bigint
bigint_unsignedbigint unsigned
doubledouble or real
string, varchar, textchar, varchar, tinytext, text, mediumtext, or longtext
datetime, date, timestamp, timethe corresponding source type
booleansigned 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 typerequired_filters valueSearch-time FILTER value
datetime, date, timestampEpoch 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 rejectedEpoch seconds
timeSigned duration seconds, or a MySQL TIME clock such as HH:MM:SS with optional fractional seconds, from -838:59:59 through 838:59:59Signed 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 ​

yaml
tables:
  - name: "articles"
    ngram_size: 2
    kanji_ngram_size: 1
    cross_boundary_ngrams: true
    posting:
      block_size: 128
      freq_bits: 0
      use_roaring: "auto"
KeyTypeDefaultMeaning
ngram_sizeinteger2N-gram length for kana, ASCII/alphanumeric text, and other scripts outside CJK ideographs, 1–10
kanji_ngram_sizeintegereffective ngram_sizeN-gram length for CJK ideographs only, 0–10; 0 means use ngram_size
cross_boundary_ngramsbooleantrueGenerates n-grams that cross a script boundary, such as 字A
posting.block_sizeinteger128Reserved, 8–1024
posting.freq_bitsinteger0Reserved; 0, 4, or 8
posting.use_roaringstringautoReserved; 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.

yaml
tables:
  - name: "articles"
    text_source:
      column: "content"
    synonyms:
      enable: true
      file: "/etc/mygramdb/articles-synonyms.tsv"
KeyTypeDefaultMeaning
synonyms.enablebooleanfalseTurns synonym expansion on for this table
synonyms.filestring""TSV file of synonym groups; required when enable is true

TSV format, one group per line:

tsv
car	automobile	vehicle
fast	quick	rapid	speedy
# comments are ignored

Search 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:

ItemLimit
Stored primary-key value1 MiB
Filters per document1,000
Filter name1 KiB
String filter value64 KiB
Original text and normalized text16 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 ​

yaml
replication:
  enable: true
  auto_initial_snapshot: false
  server_id: 83917
  start_from: "snapshot"
  queue_size: 10000
KeyTypeDefaultMeaning
enablebooleantrueFollows the source binlog
server_idinteger0Replication 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_snapshotbooleanfalseLoads uninitialized tables in the background at startup
start_fromstringsnapshotWhere replication starts; see the table below
queue_sizeinteger10000Capacity of the binlog reader's event queue, 100–1000000
reconnect_backoff_min_msinteger500Reserved, 100–60000
reconnect_backoff_max_msinteger10000Reserved, 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:

ValueBehavior
snapshotResume from the GTID captured by the snapshot/dump
latestStart 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 ​

yaml
build:
  mode: "select_snapshot"
  batch_size: 5000
KeyTypeDefaultMeaning
modestringselect_snapshotOnly select_snapshot is accepted
batch_sizeinteger5000Rows fetched per round during the initial load started by SYNC, 100–100000
parallelisminteger2Reserved, 1–64
throttle_msinteger0Reserved, 0–10000

Reserved build keys

parallelism and throttle_ms are validated but not yet enforced; the initial load is single-threaded and unthrottled.

Memory ​

yaml
memory:
  hard_limit_mb: 8192
  soft_target_mb: 4096
  roaring_threshold: 0.18
  normalize:
    nfkc: true
    width: "narrow"
    lower: false
  verify_text: "off"
KeyTypeDefaultMeaning
hard_limit_mbinteger8192Reserved; enforces no process memory limit. 256–2147483647
soft_target_mbinteger4096Reserved, 128–2147483647
arena_chunk_mbinteger64Reserved, 1–1024
minute_epochbooleantrueReserved
roaring_thresholdnumber0.18Posting-list density, 0.0–1.0, at which a delta-encoded list becomes a Roaring bitmap
normalize.nfkcbooleantrueUnicode NFKC normalization
normalize.widthstringnarrowCharacter-width handling: keep, narrow, or wide
normalize.lowerbooleanfalseLowercasing
verify_textstringoffN-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:

ValueBehavior
offFastest, no candidate verification; n-gram false positives are possible
asciiVerify ASCII-only queries
allVerify 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 ​

yaml
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
KeyTypeDefaultMeaning
dirstring/var/lib/mygramdb/dumpsDump directory
default_filenamestringmygramdb.dmpFile used by DUMP SAVE when no path is given; a basename without / or \. DUMP SAVE . is refused
load_on_startupbooleanfalseTries 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_secinteger0Seconds between automatic dumps, 0–86400; 0 disables them. The example uses 7200 (two hours)
retaininteger3Number of automatic dumps kept, 1–100; older automatic dumps in dir are deleted, manual dumps are not
restore_memory_budget_mbinteger4096Bounds the total staged data during a V2 restore, 1–1048576
restore_max_section_mbinteger2048Bounds 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 ​

yaml
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:

KeyTypeDefaultMeaning
bindstring127.0.0.1Listen address: an IP literal or hostname
portinteger11016Listen port, 1–65535
max_connectionsinteger10000Concurrent connections, 1–1000000
worker_threadsinteger0Worker threads, 0–16384; 0 selects the count automatically
recv_timeout_secinteger60Deadline for a connection's first request, 0–86400; 0 disables it
idle_timeout_secinteger300Idle connections are closed after this many seconds, 0–86400; 0 disables idle reaping
reaper_interval_secinteger5Interval between idle-connection checks, 1–3600
thread_pool_queue_sizeinteger1000Tasks queued for workers, 0–1000000; 0 means unbounded
max_write_queue_bytesinteger16777216 (16 MiB)Unsent response bytes per connection, 4096–1073741824
max_total_buffered_bytesinteger268435456 (256 MiB)Read and write buffer budget shared by all connections, 1048576–68719476736
max_pending_framesinteger1024Completed requests per connection waiting for a worker, 4–1000000
max_pending_frame_bytesinteger4194304 (4 MiB)Per-connection byte budget for pending requests, 4096–1073741824
keepalive.enabledbooleantrueEnables TCP keepalive
keepalive.idle_secinteger60Idle seconds before the first probe, 1–86400
keepalive.interval_secinteger20Seconds between probes, 1–3600
keepalive.probe_countinteger3Unanswered 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:

KeyTypeDefaultMeaning
enablebooleanfalseStarts the HTTP listener
bindstring127.0.0.1Listen address: an IP literal or hostname
portinteger8080Listen port, 1–65535
max_connectionsinteger10000Admitted HTTP connections, including sockets waiting for workers, 1–1000000
trusted_proxiesstring[][]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_corsbooleanfalseEnables CORS responses
cors_allow_originstring""The single origin value returned with CORS enabled; it is not a list. Required when enable and enable_cors are both true
max_body_bytesinteger16777216 (16 MiB)Request body limit, 0–1073741824; 0 removes the limit
read_timeout_secinteger5Read timeout, 1–3600
write_timeout_secinteger5Write timeout, 1–3600

Top-level api keys:

KeyTypeDefaultMeaning
default_limitinteger100Result count when a query has no LIMIT, 5–1000. Mutable with SET
max_query_lengthinteger128Query length limit in Unicode characters, 0–4096; 0 removes the limit. Mutable with SET
admin_tokenstring""Shared secret for administrative commands; see Administrative authentication
unix_socket.pathstring""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:

mygram
AUTH replace-with-a-high-entropy-secret
SYNC articles

POST /optimize requires the same token as an HTTP Bearer credential:

bash
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 ​

yaml
api:
  rate_limiting:
    enable: true
    capacity: 100
    refill_rate: 10
    max_clients: 10000
KeyTypeDefaultMeaning
enablebooleanfalseTurns rate limiting on. Mutable with SET
capacityinteger100Maximum burst in requests per client, 1–10000. Mutable with SET
refill_rateinteger10Tokens added per client per second, 1–1000. Mutable with SET
max_clientsinteger10000Tracked 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 ​

yaml
network:
  allow_cidrs:
    - "127.0.0.1/32"
    - "10.0.0.0/8"
KeyTypeDefaultMeaning
allow_cidrsstring[][]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 ​

yaml
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
KeyTypeDefaultMeaning
enabledbooleantrueTurns the cache on. Mutable with SET
max_memory_mbinteger32Shared 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_msnumber10.0Only queries slower than this are cached; 0.0 or more, and finite when set at runtime. Mutable with SET
ttl_secondsinteger3600Entry lifetime, 0–2147483647; 0 disables expiry. Mutable with SET
invalidation_strategystringngramngram or table; see below
compression_enabledbooleantrueCompresses cached results
eviction_batch_sizeinteger10Minimum entries evicted per capacity pass, 1–2147483647
invalidation.batch_sizeinteger1000Queued entries that trigger an invalidation pass, 1–2147483647
invalidation.max_delay_msinteger100Longest wait before queued invalidations are processed, 0–2147483647
invalidation.max_queue_sizeinteger100000Pending 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) ​

yaml
bm25:
  enable: false
  k1: 1.2
  b: 0.75
KeyTypeDefaultMeaning
enablebooleanfalseEnables BM25 scoring and SORT _score
k1number1.2Term-frequency saturation, 0.0 or more; higher values let repeated terms keep raising the score
bnumber0.75Document-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 ​

yaml
logging:
  level: "info"
  format: "json"
  file: ""
KeyTypeDefaultMeaning
levelstringinfodebug, info, warn, or error. Mutable with SET
formatstringjsonjson or text. Mutable with SET
filestring""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:

sql
SHOW VARIABLES
SHOW VARIABLES LIKE 'cache%'
SET logging.level = 'debug'
SET cache.enabled = false
SET api.default_limit = 200

The 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:

ErrorCause
1004The value is outside the key's range or violates the --schema constraints
1008Unknown variable
1009Startup-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.

OptionEffect
-c, --config <file>Configuration file to load
-d, --daemonDaemonize. 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-testLoad and validate the configuration and the files it references, print a summary, and exit without connecting to MySQL
--check-sourceRun 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, --helpPrint usage and exit 0
-v, --versionPrint the version and exit 0
--print-surfacePrint 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 MySQL and 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 disabled and 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 with Connection validation failed: for the server and Table '<database>.<table>' does not meet the table requirements: for a table. The first diagnostic determines the exit status.
  • Source meets the requirements and 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 ​

StatusCondition
0Normal exit, graceful startup cancellation, or a successful check, including a skipped source check
78Argument, 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
1Anything 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:

CommandChecksConnects to MySQL
mygramdb -t -c <file>The configuration, plus the TLS files (when ssl_enable is true) and enabled synonym files it referencesNo
mygramdb --check-source -c <file>Everything -t checks, then the startup source and table requirementsOnce
CONFIG VERIFY <filepath> over TCPA candidate file placed next to the active configurationNo

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:

ConditionLog eventEffect
network.allow_cidrs is empty or omittednetwork_acl_emptyEvery connection is denied, health probes included
Physical memory cannot be detectedconfig_warning with reason system_memory_info_unavailableThe 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 checkstartup_dump_load_failed with action: fallback_to_mysql_snapshotUninitialized tables load from MySQL in the background