Caching and memory

This page covers where the storage engine and the layers just above it hold memory: the block cache, the column-projection cache, bloom filters and block indexes, catalog caches, scan windows, and the bounds on memtables, recovery and compaction. It ends with the global allocator and the memory log. The operator summary is in Operations.

Summary of memory consumers

Consumer Bound Default Set by
Active memtable memtable_size before rotation 64 MiB [storage] memtable_size
Immutable memtables max_memtables; a rotation that finds that many flushes the oldest on the writer's thread 4 Code only
Block cache (decoded blocks) Byte budget, CLOCK eviction 1/8 of available memory, clamped to 256..2048 MiB SYNERGYDB_BLOCK_CACHE_MB
Column-projection cache Byte budget, least recently used out 512 MiB SYNERGYDB_COLUMN_CACHE_MB
SSTable readers (block index, bloom filter) One reader per live SSTable   Not configurable
Range scan One window of SSTable blocks at a time 16 MiB of on-disk blocks SYNERGYDB_SCAN_WINDOW_MB
WAL replay at open One memtable plus one batch   memtable_size
Compaction merge One decoded block per input file plus heap heads   Not configurable
Per-session catalog cache (MetaCache) Cleared when the catalog epoch moves   Not configurable
Storage catalog memo One entry per (namespace, name)   Not configurable

(source: src/storage/mod.rs, StorageConfig::default, rotate_memtable_locked, scan_window_bytes, replay_committed_run, catalog_memo_get; src/storage/sst.rs, block_cache; src/storage/columnar.rs, cache; src/storage/compaction.rs, CompactionCursor; src/query/engine.rs, MetaCache)

There is no engine-wide memory limit: no setting caps the process's total memory, and nothing above refuses work when the process is large. The bounds are per structure. Secondary indexes, vector indexes and some wires (Memcached, Redis Lua) hold their own in-memory state, covered on their own pages (source: src/config.rs; src/server/mod.rs, breakdown).

Block cache

sst::block_cache is one process-wide cache of decoded DataBlocks, shared by every SSTable reader (source: src/storage/sst.rs, block_cache::global).

Property Value
Key (reader id, block offset)
Value Arc<DataBlock> (decoded, decompressed, decrypted)
Shards 16, each a parking_lot::RwLock over a HashMap and a CLOCK ring
Per-shard budget budget / 16 bytes, measured with DataBlock::approx_bytes
Eviction CLOCK (second chance): a hit sets the slot's referenced bit if it is clear; insert evicts at the hand, clearing set bits as it passes
Hasher A multiply-mix BlockKeyHasher, not SipHash (the keys are not attacker-chosen)
Shard choice Both halves of the key mixed, top bits taken

(source: src/storage/sst.rs, BlockCache, Shard, Slot, BlockKeyHasher, shard_index)

A hit takes a shared lock and does one hash probe. A block larger than one shard's budget is never cached. Inserting a key already present replaces the block and fixes the byte count (source: src/storage/sst.rs, BlockCache::with_arc, BlockCache::insert).

The comments record two earlier designs: an LruCache behind one mutex, where relinking on every hit cost about 11% of a point read served from SSTables, and a shard function that never looked at low offset bits, so every block of one SSTable landed in one shard and a large table evicted its own blocks on every full scan (source: src/storage/sst.rs, BlockCache, shard_index).

Budget

SYNERGYDB_BLOCK_CACHE_MB, read once at first use, sets the budget in MiB; 0 disables the cache. Unset, the budget is one eighth of available memory, clamped to 256..2048 MiB. Available memory is the smaller of the cgroup limit (/sys/fs/cgroup/memory.max, or the cgroup v1 memory.limit_in_bytes) and MemTotal from /proc/meminfo; when neither can be read (for example off Linux) the budget is 256 MiB (source: src/storage/sst.rs, block_cache::global, default_budget_mb, available_memory_bytes). The module doc comment still says "default 256"; the code above is what runs.

Keys never go stale

SSTables are immutable and every SSTableReader::open takes a new id from the process-wide NEXT_READER_ID, which is never reused. A file deleted by compaction and a new file at the same path therefore cannot share entries; blocks of dropped readers are simply never hit again and age out by eviction (source: src/storage/sst.rs, block_cache module doc, NEXT_READER_ID). Engine refreshes of levels reuse the existing reader for every file still listed, so its cached blocks stay valid (source: src/storage/mod.rs, load_sstables_reusing).

What goes through it

Path Uses the cache
Point reads (with_newest_version, newest_versions_many) and scans through read_block / with_block Hit and fill
Code run inside block_cache::without_fill(f) Hit, no fill (per thread, like RocksDB fill_cache = false)
Compaction input (read_block_uncached) No
max_sequence() on an old file without the footer field No

(source: src/storage/sst.rs, read_block, with_block, without_fill, filling, read_block_uncached, max_sequence; src/storage/compaction.rs, CompactionCursor)

without_fill is used by the Memcached wire's startup load, so rebuilding its in-memory state does not fill the cache with blocks nothing reads again (source: src/protocol/memcached/mod.rs, without_fill call).

Resident bytes appear in the periodic memory log ("block cache N MB") and in the S3 wire's memory reporting. BlockCache::stats() returns hits, misses and resident bytes; hits and misses are not exported as metrics (source: src/server/mod.rs, breakdown; src/protocol/s3/mod.rs; src/storage/sst.rs, BlockCache::stats).

Tested by second_read_of_a_block_is_a_hit_and_returns_the_same_bytes, a_reopened_file_gets_a_fresh_id_so_stale_blocks_cannot_alias, budget_is_enforced_by_eviction, one_tables_blocks_spread_over_shards_and_stay_resident and clock_cache_keeps_hit_blocks_over_cold_ones (src/storage/sst.rs, block_cache_tests). Not verified: the default budget computation (cgroup and /proc/meminfo) has no test.

Bloom filters and block indexes

Every open SSTableReader keeps its bloom filter and its block index (BlockSeek, index entries in runs of 32 with fence keys) in memory for as long as the file is live. These are not part of the block cache budget. Formats and sizing (10 bits per key, 7 hash functions) are on SSTable format (source: src/storage/sst.rs, SSTableReader::open, BloomFilter, BlockSeek).

A point get skips an SSTable when the key is above its max_key, below its true_min_key, or rejected by its user-key bloom filter; the bloom hash is computed once per get and reused for every file. Only files whose footer has FOOTER_FLAG_USER_KEY_FILTER can be skipped by the filter (source: src/storage/mod.rs, get, consider_sstable). Range scans do not use bloom filters; they skip files by key bounds (source: src/storage/mod.rs, sst_may_overlap).

The load_sstables_reusing comment explains why readers are reused rather than reopened on each refresh: a reader of a multi-GB SSTable holds hundreds of MB of index and filter, and reopening every file after each background compaction, while in-flight scans kept the old sets alive, once reached 20 GB or more (source: src/storage/mod.rs, load_sstables_reusing). Tested by refreshing_levels_keeps_readers_of_files_still_on_disk (src/storage/mod.rs, reader_reuse_tests).

Column-projection cache

Large SSTables can be read through cached column projections (ColumnChunk) instead of row by row. The cache is a process-wide Mutex<HashMap> keyed by (reader id, lo || 0x00 || hi), bounded by SYNERGYDB_COLUMN_CACHE_MB (default 512, 0 disables), with least-recently-used eviction by a tick counter. A projection that would exceed the budget stops building as soon as it passes it, and the "cannot build" answer is cached so later scans go straight to rows. Only SSTables of at least SYNERGYDB_COLUMNAR_MIN_SST_BYTES (default 4 MiB, 0 disables) are projected (source: src/storage/columnar.rs, cache, chunk_for, ColumnChunk::build_within; src/storage/mod.rs, columnar_min_sst_bytes; docs/status/2026-11-27-startup-memory-bound.md). Details are on Columnar projections, time series and Parquet.

Scan windows

A range scan whose SSTable blocks exceed the window is merged window by window: next_window_end walks each SSTable's block index lazily from the window start and ends the window at the user key of the block where the on-disk bytes reach the budget. Boundaries are block-last user keys, so all versions of a user key fall in one window, and each window holds only its own decoded blocks (source: src/storage/mod.rs, next_window_end, scan_window_bytes).

Caller Window bytes Block cap
scan, scan_visit and everything built on them SYNERGYDB_SCAN_WINDOW_MB (default 16; 0 or unparsable means 16) None
scan_visit_windowed, as used by the query engine's chunked re-index 1 MiB 4 blocks
scan_visit_windowed from the vector sources caller's values caller's values

(source: src/storage/mod.rs, scan_window_bytes, scan_visit_windowed; src/query/engine.rs, scan_visit_windowed call; src/vector/sources.rs)

The block cap exists because the byte budget counts compressed bytes: a block holding one large compressible value (an S3 body) can decode to far more than its on-disk size (source: src/storage/mod.rs, next_window_end doc comment). The status entry that introduced windows records a count(*) over a 60M-row table in a 1.3 GB SSTable that decoded about 12 GB of blocks at once before the change (source: docs/status/2026-11-27-startup-memory-bound.md).

Tested by windows_match_one_pass_across_versions_deletes_and_prefix_keys and block_cap_splits_windows_of_compressible_rows (src/storage/mod.rs, windowed_scan_tests), and scan_callbacks_run_without_an_epoch_pin (scan_epoch_tests).

Memtables

Memtable size is accounted as user_key + value + 16 bytes per entry, which leaves out skip-list node and point-index overhead, so real memory per memtable is above memtable_size. While a snapshot transaction is live, older versions stay in the memtable as well (source: src/storage/memtable.rs, insert_inner, insert_versioned). Rotation and back-pressure are on Memtable. Not verified: no test measures memtable memory against memtable_size.

Recovery and compaction

Both used to need memory proportional to the data and are now bounded:

  • WAL replay streams one segment at a time, applies each committed batch as its marker is read and flushes whenever the memtable fills (see Crash recovery). Opening no longer decodes every SSTable block to find the sequence high water, because the footer carries it (see SSTable format).
  • Compaction streams each input block by block, outside the block cache, so a job holds one decoded block per input (see Compaction).

(source: src/storage/mod.rs, StorageEngine::open, replay_committed_run; src/storage/compaction.rs, CompactionCursor)

The guide, following deploy/README.md, tells operators that compaction is memory-hungry and to size RAM for peak compaction. That advice predates the streaming merge in CompactionCursor; whether it still holds is not measured in these files (source: deploy/README.md; Operations). Not verified: no test or status entry measures compaction peak memory after the change.

Catalog and statement caches

Cache Scope Invalidation Source
MetaCache One per QueryEngine (session) Everything cleared when StorageEngine::catalog_epoch has moved src/query/engine.rs, MetaCache, meta_cache_locked
Catalog memo Process-wide in StorageEngine, per (namespace, name) An entry is used only if built at the current epoch src/storage/mod.rs, catalog_memo_get, catalog_memo_put; src/storage/namespaced.rs, catalog_memo
Regex cache Process-wide LRU of 512 compiled patterns LRU src/query/engine.rs, cached_regex
MySQL PreparedStatementCache Per MySQL handler; HashMap by statement id COM_STMT_CLOSE src/protocol/mysql/mod.rs, PreparedStatementCache

MetaCache holds raw __catalog__:* blobs (including cached absence), decoded column definitions, constraints, unique-index and check definitions, foreign keys, enum, domain and trigger definitions, and whether any view exists. The comments attribute 9% to 64% of various insert and TPC-B profiles to the lookups it replaces (source: src/query/engine.rs, MetaCache).

The catalog epoch is bumped before and after any write to a __catalog__: (or, on the replica apply path, __sequence__:) key, so a reader that samples the epoch between the two cannot cache pre-write state under the new epoch (source: src/storage/namespaced.rs, put; src/storage/mod.rs, replicated apply path). The catalog memo is used by the PostgreSQL catalog views (pg.constraint_model, pg.tables_with_columns, pg.indexes) (source: src/protocol/postgres/catalog.rs). Tested by catalog_epoch_makes_other_sessions_ddl_visible_to_cached_metadata (src/query/engine.rs, tests).

There is no row cache: repeated point reads are served by the memtable point index or by the block cache (source: src/storage/memtable.rs, PointIndex; src/storage/sst.rs, block_cache).

Not wired: these plan and statement caches exist but have no caller on the query path:

  • query::stmt_cache::StatementCache and global_statement_cache() (LRU of parsed LogicalPlans, default capacity 1000): exported from src/query/mod.rs, no caller outside stmt_cache.rs.
  • plan::adaptive::AdaptivePlanCache, used only inside AdaptiveOptimizer, which is used only by AdaptiveQueryOptimizer in src/plan/optimizer.rs; no code outside src/plan/ constructs either.
  • plan::statistics::PlanCache: no caller outside src/plan/statistics.rs.

(source: src/query/stmt_cache.rs; src/plan/adaptive.rs; src/plan/optimizer.rs; src/plan/statistics.rs)

Allocator

The global allocator is heap::Counting<mimalloc::MiMalloc> (crate mimalloc 0.1). The system-allocator Cargo feature (off by default, not in full) uses heap::Counting<std::alloc::System> instead, so heap profilers that hook malloc (heaptrack, valgrind) see every allocation. The comment on the allocator says glibc malloc, free and memcpy were 38 to 44% of a 2,000-row scan's samples (source: src/lib.rs, GLOBAL; Cargo.toml, [features], mimalloc).

heap::Counting wraps the allocator and, once heap::enable() has been called, keeps:

  • live heap bytes, in 64 cache-line-aligned shards selected per thread;
  • per-thread Trackers (net, peak, gross bytes) attached with attach / attach_thread; the storage flush thread attaches as "storage flush" and each compaction worker as "compaction", and the slow-query log attaches one per statement;
  • the largest single allocation of 64 MiB or more since the last read.

When counting is off, the cost is one relaxed atomic load per allocation (source: src/heap.rs, module doc, Counting, Tracker, attach_thread, take_largest_alloc; src/storage/mod.rs, StorageEngine::open; src/storage/compaction.rs, start).

Memory log

SYNERGYDB_MEMORY_LOG_SECS=<n> (n > 0) enables heap counting at process start and logs every n seconds: RSS, anonymous RSS, peak RSS, live heap bytes, thread count, active memtable size and immutable memtable count, then block-cache bytes, secondary-index entries, SQL vector indexes and vector collections, and the per-thread tracker summary (source: src/main.rs, memory_log_secs; src/server/mod.rs, spawn_periodic, breakdown). RSS far above live heap bytes means memory the allocator holds after it was freed, not live data (source: src/heap.rs, module doc).

Startup memory lines ("startup memory: …") are logged after storage open, after any wire whose construction grew RSS by 256 MB or more, once all listeners are up, and every 10 s for the first 3 minutes (source: docs/status/2026-11-27-startup-memory-bound.md; src/server/mod.rs). Not verified: the memory log has no test.

Configuration reference

Variable / key Default Read
SYNERGYDB_BLOCK_CACHE_MB 1/8 of available memory, 256..2048 MiB; 0 disables Once, at first block access
SYNERGYDB_COLUMN_CACHE_MB 512; 0 disables Once
SYNERGYDB_COLUMNAR_MIN_SST_BYTES 4 MiB; 0 disables projections Once
SYNERGYDB_SCAN_WINDOW_MB 16 Once
SYNERGYDB_MEMORY_LOG_SECS unset (off) At startup
[storage] memtable_size 64 MB At open
Cargo feature system-allocator off Build time

(source: src/storage/sst.rs, block_cache::global; src/storage/columnar.rs, cache; src/storage/mod.rs, columnar_min_sst_bytes, scan_window_bytes; src/main.rs; src/config.rs; Cargo.toml)

All four storage variables are read once per process into a static, so changing them needs a restart.