NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / EMBEDDED ENGINE / THE BUILDER

The Builder

rasterizeddb_embedded::Builder decides what the engine opens and how it runs. This page lists every setting with its default and effect. Each setting corresponds to a flag of the rasterizeddb server binary, so the server configuration page describes the same knobs from the server's side.

rust
use std::time::Duration;
use rasterizeddb_embedded::{Builder, IndexResidency};

let db = Builder::open("./data")
    .worker_threads(4)                         // the engine's runtime threads
    .query_threads(4)                          // workers one query may use
    .malloc_arenas(4)                          // fewer allocator arenas: less memory, less throughput
    .index_residency(IndexResidency::Disk)     // indexes on disk behind a 64 MiB cache
    .join_memory_mb(256)                       // a join past this fails instead of exhausting memory
    .synchronous_commit(false)                 // commits return before their fdatasync
    .wal_writer_delay(Duration::from_millis(100))
    .config("auto_compact.interval_secs", "300")
    .start()
    .await?;

Every method takes the Builder by value and returns it, so calls chain. Nothing happens until start (or start_blocking), which checks every setting and fails with std::io::ErrorKind::InvalidInput if one is unknown or refused, naming the setting.

Where the database lives

ConstructorWhat it opens
Builder::open(directory)A database kept in directory, which is created if it does not exist. The path must be valid UTF-8. A directory written by the server binary opens here, and the reverse. Only one engine at a time may have the directory open (see the directory lock).
Builder::in_memory()A database held in memory only, gone when the engine stops. It has no settings file.

Starting and serving

MethodDefaultEffect
start().awaitOpens the database and starts serving it. Returns io::Result<Embedded>. Callable from any async runtime, because the engine runs on threads of its own.
start_blocking()start for code outside any async runtime. Blocks until the engine is up. Do not call it from inside a runtime.
worker_threads(n)One per CPU, as tokio choosesThreads of the engine's own runtime. At least 1.
password(user, password)NoneRequires a SCRAM-SHA-256 login as user. A fresh database gets that role with this password; an existing database must already have the role. Embedded::connect logs in with it. Required on Windows (see below). On Unix it is optional, because the socket already admits only your operating-system user.
allow_unauthenticated_loopback(on)falseWindows only: serve the loopback endpoint without a password, so that any local process can use the database. Ignored on Unix.
request_timeout(duration)30 sHow long one statement may run before it is stopped and answered with SQLSTATE 57014. A connection idle this long is closed too, and the client reopens it before its next statement. Same as the server's --rdb-request-timeout.

On Windows, start with neither password nor allow_unauthenticated_loopback(true) fails with InvalidInput.

If you change request_timeout, adjust the client to match. Options::timeout is how long the client waits (30 s, plus a 2 s grace), and Options::idle_reconnect (20 s) must stay below the engine's idle close. Pass both through Embedded::connect_with; see Client options.

Memory

MethodServer flag or keyDefaultEffect
low_memory()A preset that trades throughput for memory: malloc_arenas(4), index_residency(IndexResidency::Disk) (indexes on disk behind a 64 MiB cache) and join_memory_mb(256). A call after it overrides its choice for that setting.
malloc_arenas(n)server.malloc_arenas (read once)0, glibc's own (8 per core)Caps glibc's malloc arenas. Fewer arenas keep less freed memory per thread and cost throughput under concurrency. Measured at 16 clients, 4 arenas cost 20% of point reads and 12% of inserts for 16% less resident memory. It applies to the whole process, your own threads included, and binds only arenas not yet made, so start the engine before your own thread pools. A limit once set is not lifted. Ignored, with a logged warning, where the allocator is not glibc's.
idle_trim(on)trueGives freed memory back to the operating system once no statement has run for a few seconds. glibc only, where a process otherwise holds its high-water mark until it exits. false leaves the allocator alone, for a program that manages it itself.
tune_allocator(on)--tune-allocatorfalseKeeps large buffers out of the kernel's hands between statements. glibc only. Worth 1.4x on a single large scan and nothing on point lookups; costs about 15% when several clients run large scans at once, and holds more memory.
index_residency(r)index.residency (read once)IndexResidency::MemoryWhere B-tree, hash, path and GIN indexes keep their entries. Memory: every entry in RAM. Hybrid and Disk: sorted files beside the table, searched through a block cache, with only recent changes in memory (Hybrid with a large cache, Disk with a small one). Applies to tables opened afterwards.
index_cache_mb(mib)index.cache_mb (read once)0: 1024 for hybrid, 64 for diskThe paged indexes' block cache in MiB, shared by every table.
index_delta_mb(mib)index.delta_mb (read once)0: 256 for hybrid, 16 for diskThe in-memory part each paged index holds before writing it out, in MiB.
join_memory_mb(mib)the server's RDB_JOIN_MEMORY_MB1024The most memory one join may hold for its rows. A join that would grow past it fails with SQLSTATE 53200 instead of taking the process down. 0 is refused: there is no unlimited setting. Read once.
batch_size(rows)server.batch_size (read once)10 000Row pointers a scan fetches per batch. Must be above 0.
query_cache(on)cache.enabled (read once)falseServes repeated queries from a remembered position.
query_cache_entries(n)cache.size (read once)100 000Entries the query cache holds when it is on. Must be above 0; turn the cache off with query_cache(false). The first engine in a process to turn the cache on sizes it.
kv_max_memory(bytes)--kv-max-memory0 (unbounded)Bytes the key/value store may hold, like Redis's maxmemory.
kv_eviction(policy)--kv-evictionKvEviction::NoEviction (writes fail when full)What is dropped when the key/value store is full, like Redis's maxmemory-policy.

Durability

MethodServer flag or keyDefaultEffect
synchronous_commit(on)wal.synchronous_commit (hot)trueWhether a commit waits for its fdatasync. Off, a commit returns once its records are in the operating system's page cache. An operating-system crash or power loss can then lose the last wal_writer_delay of transactions: whole ones off the end of the log, never part of one. A crash of your process alone loses nothing.
wal_writer_delay(duration)wal.writer_delay_ms (hot)200 msHow long an asynchronous commit may go unsynced. Unused while commits are synchronous.
wal_checkpoint_bytes(bytes)wal.checkpoint_bytes (read once)64 MiBLog bytes between checkpoints. Larger means fewer checkpoints and a longer replay after a crash.
wal_prealloc_kb(kib)wal.prealloc_kb (read once)1024KiB of zeros the log is extended by ahead of its appends. It about halves a commit's sync time on ext4 and costs up to this much disk per log. 0 turns it off.
wal_truncate_damaged(on)--wal-truncate-damagedfalseStarts past a damaged log, losing what follows the damage. This start only: it is never saved, and the next start without it refuses a damaged log again.
kv_persist(on)--kv-persistfalse (it is a cache)Saves the key/value store periodically and at a clean shutdown, so it survives a restart.
kv_save_interval(duration)--kv-save-interval-secs300 sTime between two periodic saves while kv_persist is on. At least one second.

wal_truncate_damaged is in rasterizeddb_embedded 1.1.1 and later.

A log with a record that fails its checks, followed by whole records, counts as damage, not as the torn tail of a crash. Without wal_truncate_damaged, start refuses such a log, naming the log, the byte offset and the commits after it. With it on, the records before the damage are replayed, everything from the damage on is dropped, and an ERROR in the log says what was lost. Writes after the damage that had already reached the data files may survive in part, so the result is not a clean point in time: check it. When those commits matter, copy the log first and restore from a backup instead.

Threads and CPU

MethodServer flag or keyDefaultEffect
worker_threads(n)One per CPUThreads the engine's runtime runs on (see Starting and serving).
query_threads(n)server.concurrent_threads (read once)16Workers one query may use. At least 1.
simd(level)--simdThe best level this CPU supportsThe instruction set the vector kernels use: SimdLevel::Scalar, Avx2 or Avx512. A level the CPU cannot run makes start fail with InvalidInput instead of falling back.
scan_prefilter(on)--scan-prefiltertrueDrops rows a WHERE clause cannot match before fetching them.

Storage and maintenance

MethodServer flag or keyDefaultEffect
index_storage(s)index_snapshot.index_storage (hot)IndexStorage::RebuildWhat an open does with B-tree, hash and path indexes: Rebuild them from the rows, or load the Snapshot that a clean shutdown wrote.
auto_compact(on)auto_compact.enabled (hot)trueCompacts tables and partitions whose pointer slots are mostly dead, without being asked. Tune it with the other auto_compact.* keys through config.
query_stats(on)query_stats.enabled (hot)trueRecords what each statement cost, for SHOW QUERIES and SHOW QUERY STATS. Off, each statement skips the record and a lock it would otherwise take.
json_shadow_tables(on)--json-shadow-tablesfalseStores a new JSON/JSONB column by splitting its documents into a table of their own instead of storing bytes. Only for documents that share a small, stable set of keys. When the keys are data, such a column loads quadratically. Columns that already exist keep what they are. Read once.
settle_status(on)--settle-status-at-opentrueSettles long-finished transaction outcomes, so that the transaction status log's memory stops growing with every transaction ever run. false turns it off.
partition_open_budget(n)partition.open_budget (hot)0Partitions open at once in this process, across all tables. 0 derives it from the process's open-file limit: a soft limit of 1024 leaves 16.
partition_max_open(n)partition.max_open (read once)4096The most partitions a derived open budget allows.
raise_descriptor_limit(on)false (the limit is your program's)Raises the process's soft open-file limit toward its hard limit, as far as the largest partition budget needs (ten descriptors per partition), the way the server binary does at start. Unix only. Leave it off in a process that still uses select(2), which cannot watch a descriptor above 1023.

Any configuration key

config(key, value) sets any key that SHOW CONFIG KEYS lists, spelled as SET CONFIG key = value spells it:

rust
let db = Builder::open("./data")
    .config("auto_compact.enabled", "off")
    .config("filter.max_f", "14")
    .config("index.residency", "disk")
    .config("partition.idle_close_secs", "600")
    .start()
    .await?;

The typed methods above are this call with the key filled in, so the last call for a key wins, whichever method made it. Keys are case-insensitive. An unknown key, a value the key refuses, or wal.enabled (fixed on) makes start fail with InvalidInput.

These keys are available. The server configuration page explains each one.

SectionKeysKind
serverbatch_size, concurrent_threads, malloc_arenasread once
indexresidency, cache_mb, delta_mbread once
walcheckpoint_bytes, prealloc_kbread once
walsynchronous_commit, writer_delay_mshot
cacheenabled, sizeread once
filterenabled, backfill_on_open, min_pruning_ratio, checkpoint_interval_secs, min_f, default_f, max_f, min_selectivity, min_table_rows, zone_bounds, bloomhot
query_statsenabled, recenthot
vacuumenabledhot, acts on the open database
auto_compactenabled, interval_secs, min_slots, ratio, dead_fraction, dead_fraction_max_slots, cooldown_secshot
partitionopen_budget, idle_close_secshot
partitionmax_openread once
index_snapshotidle_checkpoint_secs, seal_timeout_ms, shutdown_deadline_secs, writeback_mb, index_storage, max_concurrent_loads, load_wait_ms, audit_ratehot
replicationactive, compression, mode, conflict, ack_timeout_ms, batch_max_records, batch_linger_ushot, acts on the open database

Hot keys are set before the database opens, so the open already sees them. The two kinds that act on one database, replication.* and vacuum.enabled, are set on the default database right after it opens.

Hot keys and read-once keys

The keys come in two kinds, as on a server.

Hot keys can also be changed on the running engine with SET CONFIG key = value, through any client:

rust
client.run("SET CONFIG wal.synchronous_commit = on").await?;

With a data directory, the change is also saved to rasterizeddb.conf in that directory, so the next start keeps it. The exceptions are replication.* and vacuum.enabled, which act on one database. A Builder value only sets where a hot key starts, and is not saved.

Read-once keys are read at start. SET CONFIG on one saves it to rasterizeddb.conf without applying it, and the next start on that directory applies it. SHOW CONFIG shows the saved value in its pending column until then. An engine in memory has no settings file, so SET CONFIG on a read-once key fails there.

Which value wins. For each key, a value given to the Builder wins over a saved one, which wins over the default, as a server's flag wins over its saved file. SHOW CONFIG shows each value's source: command line for a Builder value, saved for one from rasterizeddb.conf, or default.

rust
for row in &client.run("SHOW CONFIG").await? {
    let v = row.values()?;
    // section, key, value, hot_reload, set_with, help, pending, options, source
    println!("{:?}.{:?} = {:?} (source {:?})", v[0], v[1], v[2], v[8]);
}

Settings are process-wide

The engine keeps its settings in process-wide state, the way the server binary's flags leave them. That has three consequences when you start more than one engine in a process, one after another, as tests do:

  • Some values can be chosen once per process. query_threads, batch_size, wal_checkpoint_bytes, wal_prealloc_kb, query_cache, query_cache_entries, join_memory_mb and json_shadow_tables keep the first value an engine set for the life of the process, and malloc_arenas cannot be lifted once lowered. A later start that asks the Builder for a different value fails with InvalidInput ("… cannot take effect: it is process-wide and read once"), rather than run with a value nobody asked for. Asking for the same value again is fine. A different value from rasterizeddb.conf is only a logged warning, and stays pending.
  • Settings carry over. A setting a later Builder does not give keeps the value the previous engine in the process left, hot keys included.
  • malloc_arenas and tune_allocator change the allocator for your whole program, not just the engine.

The index settings (index_residency, index_cache_mb, index_delta_mb) and partition_max_open are applied again at every start.

Enumerations

The setting types are re-exported from rasterizeddb_embedded:

TypeValues
IndexResidencyMemory, Hybrid, Disk
IndexStorageRebuild, Snapshot
KvEvictionNoEviction, AllKeysLru, VolatileLru, AllKeysRandom, VolatileRandom, VolatileTtl
SimdLevelScalar, Avx2, Avx512

Cargo features

rasterizeddb_embedded has no Cargo features. The engine is built with its default features, the same set the server binary has, and it does not build with them off. The client's features (derive, chrono, uuid, serde_json) go on your own rasterizeddb_client dependency; see Getting started.

The running engine

start returns an Embedded:

MethodWhat it does
connect().awaitA Client for this database, with options().
connect_with(options).awaitA Client with the options you give. Their login is used as given, so start from options().
options()The client options connect uses: the client's defaults, this engine's login and, on Windows, trust in this engine's own certificate only.
endpoint()The address a client connects to: unix:/…/native.sock, or 127.0.0.1:<port> on Windows.
shutdown().awaitStops the engine: no new connections, statements in flight finish, index snapshots are written and the log is checkpointed. Returns what the listener ended with.
shutdown_blocking()shutdown for code outside any async runtime.

Dropping an Embedded stops the engine too, blocking the dropping thread until it is done. See Shutdown and drop order.

Limits

  • One engine runs per process at a time. A second start fails with AlreadyExists until the first has stopped.
  • Some values can be chosen only once per process; see Settings are process-wide.
  • malloc_arenas, idle_trim and tune_allocator work only with glibc's allocator. raise_descriptor_limit is Unix only.
  • There is no setting to serve PostgreSQL, MySQL, SQL Server, Redis or a TCP port on Unix. The only endpoint is the private one.
✓ page rendered in 206 µs axum + tera + htmx · no other javascript