MmapCache 1.1.0

dotnet add package MmapCache --version 1.1.0
                    
NuGet\Install-Package MmapCache -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MmapCache" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MmapCache" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="MmapCache" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MmapCache --version 1.1.0
                    
#r "nuget: MmapCache, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MmapCache@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MmapCache&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=MmapCache&version=1.1.0
                    
Install as a Cake Tool

MmapCache

An off-heap, append-only cache engine for .NET built for large read-mostly catalogs that must be mutated live, survive a restart, and reload without downtime.

MmapCache never holds a second copy of the data it serves. A Put appends one CRC-checksummed frame to an append-only data file and the process keeps only the unmanaged radix index that maps a key to (file, offset, length). Once a file is finished with it is sealed - memory-mapped read-only in place, no copy, no background flush task - and its values are sliced straight out of the mapping. A restarted process reuses the data files the previous one left behind, as long as the load stamp of that snapshot is still inside its TTL. The only managed payload values it can hold are the bounded hot keys you opt into through L1MaxSize.


Table of Contents


Why MmapCache?

Most in-process caches and embedded stores suffer from:

  • GC Fragmentation & Pauses - Constantly overwriting objects creates holes in the managed heap, leading to severe garbage collection compaction cycles.
  • Cold Starts - A restarted service re-reads the whole catalog from the database before it can serve traffic, even though the previous process wrote that catalog minutes ago.
  • Reload Lockouts - Rebuilding a large catalog in the request path is expensive, slow and resource-heavy.
  • All-or-nothing reloads - A reload that momentarily sees an empty source wipes a healthy catalog that is serving traffic.

MmapCache answers all four by making the file the table. Payloads are written once, sequentially, and never buffered in RAM on the way; the resident footprint is the index, so a 2-key catalog and a 100M-key catalog cost the same per key. Because the same bytes are both the write log and the stored dataset, restart is a bookkeeping decision (StartupFillPolicy), not a data movement, and a reload publishes a fully built engine in one atomic swap.


Features

Feature Description
Data Lives on Disk, Not in RAM Values are appended to segment_N.sst files and are not mirrored in native memory. The process holds the index, the Bloom filter, one file handle and one mapping per generation - plus, if you opt in, the bounded set of deserialized values the L1 tier keeps.
Append-Only Writes Put and Delete append a CRC32-checksummed frame under a lock and flush before publishing the record's location, so a value is readable the moment the call returns.
Sealing Instead of Flushing When a data file reaches its size cap, or a supplier load finishes, the engine maps that same file read-only. No sorting pass, no copy, no background flush task.
Warm Restart A snapshot left by an earlier process is served again - index rebuilt from the frames, values read from the mapping - while its recorded load time is still inside Ttl. The supplier is not called.
Concurrent Radix Tree The index is an unmanaged least-character-first radix tree: prefix sharing keeps memory low, keys stay lexicographically sorted, and scans are cheap.
Bloom Filter A bit-array filter (about 1.2 bytes per key at a 1% false-positive rate, set with atomic Or) sits in front of reads. A miss returns without touching the tree or the file.
Optional L1 Hot-Key Tier L1MaxSize keeps the most-read keys, already deserialized, in a bounded LRU of managed values. A hit skips the file read and the deserializer; L1MaxSize = 0 turns the tier off and the process holds no payload at all.
Live Mutations Put/Delete are visible immediately; a newer frame for a key replaces the older location in the index, and deletes append a tombstone.
Atomic, Coalesced Reload ReloadAsync builds a sibling engine in a new version directory and publishes it in one swap. Concurrent callers join the in-flight reload, and an empty supplier result is rejected instead of wiping the catalog.
On-Demand Compaction Compact rewrites a catalog's data files as one dense file, discarding the dead bytes that repeated Puts and tombstones leave behind, and returns what it reclaimed. It is a call, not a background task - nothing churns until you ask.
One Process Per Cache Register claims the cache name for the lifetime of the manager. A second process that points at the same directory fails immediately with a clear error instead of appending into files another process is reading.

Installation

dotnet add package MmapCache

Targets net8.0, net9.0, and net10.0.

MmapCache is released under the GPL-3.0 license. If you intend to use it inside a closed-source commercial product, review the license terms carefully.


Quick Start

using MmapCache.Cache;
using MmapCache.Config;
using System.Text.Json;

// -- 1. Initialize once at application startup --------------------------------
// Data files (segment_N.sst) and the .committed load stamp are written under this directory.
MmapCacheManager.Initialize("/var/cache/myapp");

// -- 2. Describe what to store ------------------------------------------------
var productDef = new MmapCacheDefinition<Product>
{
    Name = "products",

    // Runs at Register when there is no reusable snapshot on disk, and on every ReloadAsync.
    // Yield lazily so the whole catalog is never materialized into a List.
    Supplier = (ct) => db.Products.Select(p => (p.Id.ToString(), p)),

    Serializer   = p => JsonSerializer.SerializeToUtf8Bytes(p),
    Deserializer = span => JsonSerializer.Deserialize<Product>(span)!,

    Ttl       = TimeSpan.FromHours(1),   // per-record lifetime, and the window a snapshot may be reused in
    TtlJitter = TimeSpan.FromMinutes(6), // spreads expiry so the catalog does not age out at once

    // Restart reuses the on-disk snapshot while it is younger than Ttl; otherwise it reloads.
    OnStartup = StartupFillPolicy.ReuseIfFresh,

    MaxDataFileBytes = 64 * 1024 * 1024, // size cap of one append-only data file

    L1MaxSize = 10_000,                  // hot keys kept deserialized in RAM; 0 = never keep any
    L1Ttl = TimeSpan.FromMinutes(1)      // how long one hot key may be served while its record lives
};

// -- 3. Register the engine instance -----------------------------------------
// Serves the persisted snapshot when it is fresh; otherwise fills from the supplier.
MmapCacheManager.Instance.Register(productDef);

// -- 4. Active mutability (Put / Delete) --------------------------------------
MmapCacheManager.Instance.Put("products", "product_42", new Product("product_42", "Updated!", 9.99m, 50));
MmapCacheManager.Instance.Delete("products", "product_99");

// -- 5. Concurrent reads ------------------------------------------------------
var product = MmapCacheManager.Instance.Get<Product>("products", "product_42");

if (MmapCacheManager.Instance.TryGet<Product>("products", "product_42", out var p))
    Console.WriteLine(p!.Name);

// -- 6. Reload with zero downtime ---------------------------------------------
await MmapCacheManager.Instance.ReloadAsync<Product>("products");

// -- 7. Dispose on shutdown ---------------------------------------------------
await MmapCacheManager.Instance.DisposeAsync();

Supplier must be re-runnable: it is called whenever a snapshot cannot be reused, and on every reload.


Configuration Reference

MmapCacheDefinition<TValue> accepts the following properties:

Property Type Default Description
Name string (required) Logical name; also the sub-directory prefix ({name}_v{version}) of the engine instance under basePath.
Supplier Func<CancellationToken, IEnumerable<(string Key, TValue Value)>> (required) Produces the full dataset. Called at Register when the snapshot on disk is not reusable, and on every reload.
Serializer Func<TValue, byte[]> (required) Converts the model to bytes for writes.
Deserializer SpanDeserializer<TValue> (delegate TValue (ReadOnlySpan<byte> span)) (required) Reads the value straight out of the mapped file, with no intermediate array.
Ttl TimeSpan 1 hour Per-record lifetime; TimeSpan.Zero or negative disables expiry. The same window decides whether a snapshot left on disk is fresh enough to be served at startup.
TtlJitter TimeSpan? null = 10% of Ttl Per-key expiry is pushed forward by a stable offset inside this window, so a catalog does not age out in the same second. Offsets are forward-only: no key expires before Ttl.
AllowEmptyReload bool false When false, a reload that yields nothing while the running snapshot holds records keeps serving it and throws instead of publishing an empty catalog. An empty reload onto an already empty cache loses nothing, so it stays a quiet success.
RadixTreeCapacity int 100,000 Expected key count. Sizes the Bloom filter and the index's initial expectation; the tree grows lazily beyond it, so under-sizing costs Bloom accuracy on missing keys rather than correctness. The filter is allocated up front at roughly 1.2 bytes per expected key (100,000 ≈ 117 KB of native memory per cache), so a cache of a few hundred keys can name its own order of magnitude.
MaxDataFileBytes int 67,108,864 (64 MB) How large one append-only data file may grow before the engine seals it and starts a new one. Sealing is bookkeeping, not a copy, so this trades file count against the size of each mapping. Values below 64 KB are raised to 64 KB.
L1MaxSize int 10,000 How many of the most-read keys the L1 tier keeps as deserialized values. A hit skips the file read and the deserializer. 0 disables the tier, so no payload value is ever held in memory.
L1Ttl TimeSpan? null Extra bound on how long one L1 entry may be served while its record on disk is still live. null = the entry lives until its record expires, a reload replaces the engine, or the LRU evicts it.
OnStartup StartupFillPolicy ReuseIfFresh What Register does with the data files a previous process left on disk. See Startup Policies.

Startup Policies

Value Supplier at Register Snapshot on disk Use it for
ReuseIfFresh (default) Only when the snapshot is stale, empty or unusable Served while now - loadedAt <= Ttl, then replaced by a fresh load Catalogs that can afford to be a TTL old at boot
AlwaysReload Always Ignored, then replaced Data that must be current the instant the process starts
LeaveEmpty Never Served if present Callers that fill the cache themselves with Put, or trigger ReloadAsync after the host is warm

loadedAt is not inferred from the file timestamps: the engine writes a .committed stamp when a load finishes, and LastReload reports the same value in-process. After a warm restart LastReload is the original load time, not the boot time, so a staleness check keeps firing when it should.


API Reference

Member Notes
Register<TValue>(def, ct) Serves a reusable snapshot from disk, or builds a new engine and fills it from the supplier.
Get<TValue>(cache, key) / TryGet<TValue>(cache, key, out value) L1 first, then the data file. Deserializes on a zero-copy span, caches the value if the tier is on; expired records return default and are tombstoned.
Exists(cache, key) Liveness check without deserializing the payload; a live L1 entry answers it without touching the file.
Put<TValue>(cache, key, value, customTtl = null) Live mutation; customTtl overrides the definition TTL for this record only. Refreshes the L1 entry for the key instead of dropping it.
Delete(cache, key) Appends a tombstone and evicts the key from L1; it stops resolving immediately.
Size(cache) Number of live keys, not the number of writes.
ScanKeys(cache, prefix = "", ct) Keys under prefix; an empty prefix walks the whole tree.
ScanKeysZeroAlloc(cache, consumer, prefix = "", ct) Push-based scan that hands each key to a delegate as a ReadOnlySpan<char> without allocating.
LastReload(cache) UTC stamp of the load that produced the current snapshot - including a snapshot resumed from disk; DateTime.MinValue while the cache has never been filled.
ReloadAsync<TValue>(cache, ct) Builds a new engine, publishes it atomically, clears the cache's L1 tier, then disposes and deletes the previous engine.
Compact(cache) Rewrites the cache's data files as one dense file, dropping the bytes superseded writes and tombstones left behind, and returns what it removed. Nothing calls it automatically.
ShutdownToken Cancelled when the manager is disposed; pass it into suppliers to abort work at shutdown.

MmapCache.Lsm types (LsmEngine, Segment, DataFileWriter, RecordFormat) are public for callers that want the raw engine; the manager covers the common case.


How It Works

One append-only file per generation is both the write log and the stored dataset. There is no memtable, no WAL that later gets rewritten, and no flush task: writing a record and storing a record are the same operation.

{basePath}/{name}.lock    held by one process: the claim on this cache name
{basePath}/{name}_v{version}/
    .committed          layout={n};loadedAtUtcTicks={n};records={n}
    segment_0.sst       sealed, memory-mapped
    segment_1.sst       sealed, memory-mapped
    segment_2.sst       open, still being appended to

Data Files and Framing

Each file starts with an 8-byte header - magic ('M' 'M' 'C' '2'), layout version, two reserved bytes - and continues with frames:

[crc32:4][op:1][keyLen:4][valueLen:4][key bytes][value bytes]

The CRC covers everything after itself, so a torn or foreign tail cannot be mistaken for a record. op is Put or Delete (a tombstone carries an empty value). Frames over 8 KB are assembled from ArrayPool rather than the stack.

Writing, Sealing and Rotation

Put/Delete build a frame, append it under the engine's append lock, flush it, and only then publish (file, offset, length) into the radix index. The offset a reader sees is therefore the offset the bytes actually landed at.

When the open file reaches MaxDataFileBytes the engine seals it - maps the same file read-only and starts a new one - under the engine write lock, so no append is in flight at the moment of the swap. A supplier load ends with an explicit Seal() too, so a fully built catalog is served from its mapping instead of a positioned read per key. Nothing is copied and no task runs in the background.

Size counts live keys, tracked through the index's own absent-to-live and remove transitions, so rotation and overwrites cannot drift it.

Reading

A read consults the Bloom filter, then the radix index. If the record's file is sealed, the value is a ReadOnlySpan<byte> slice of the mapping; if it is still being appended to, the value is read at its offset through a dedicated read-only handle, so the read never disturbs the writer's append position. The engine's reader-writer lock runs readers in parallel; sealing, rotation and disposal take the write lock and are short, and Compact is the one exception - it holds that lock for the length of its merge, on that one cache only.

L1 Hot-Key Tier

L1MaxSize opts a cache into a bounded least-recently-used set of the keys traffic keeps repeating. It stores the deserialized value, so a hit costs one dictionary lookup instead of a positioned read plus a Deserializer pass - the two costs that dominate a read of a mapped file. L1MaxSize = 0 disables it entirely and the process holds no payload values at all.

The tier is a cache of one engine's answers, and it is invalidated as such:

  • An entry carries the generation of the engine its value came from. A read tags the entry with the version it consulted, and only entries of the current version are served, so a value from a discarded engine cannot answer for the new one. ReloadAsync also clears the tier, which releases those managed values instead of waiting for them to be evicted one by one.
  • An entry's deadline is the earlier of its record's expiry and now + L1Ttl. Because the deadline can never pass the record's own, an entry cannot outlive its record: a key that aged out on disk stays aged out in L1.
  • Put refreshes the entry with the value it just wrote, Delete evicts it, and a supplier load deliberately fills nothing - warming the tier with every key of a catalog would displace the keys traffic actually repeats on.

Eviction, lookups and inserts share one short lock, and a bounded tier means the memory cost is a fixed multiple of L1MaxSize, not of the dataset.

Warm Restart

A directory only becomes loadable once the load that filled it finished: .committed is written with the layout version, the UTC tick at which the load finished, and the record count. Without that stamp, a process killed mid-reload would leave half a catalog that the next boot treats as complete.

Register walks the version directories of a cache, keeps the highest one whose marker matches the current layout, and discards the rest - a stale, superseded or unmarked directory is deleted rather than left to be chosen between later. It then bootstraps the chosen directory: frames are read for their key, offset, length and CRC, live versions are inserted into the index and Bloom filter, payloads are never deserialized. If the snapshot is reusable under OnStartup and Ttl, reads start serving from it immediately; otherwise the files are dropped and the supplier fills a fresh engine in the same slot.

Durability and Crash Behaviour

Every append is flushed, so frames written by this process survive a killed process: the bytes are already handed to the OS and reach the file. The engine does not write through to the device, so a machine-level power loss can still take back the frames the storage never persisted.

A hard crash cannot poison a restart. Two guards cover it: an unmarked directory is never served, and a frame whose length or CRC does not check out ends the scan - the records before it are indexed, the torn tail is ignored. Writing continues in a new file after restart, so a torn tail never blocks a Put.

Compaction

Superseded values and tombstones stay as dead bytes inside the file that holds them; the index always points at the newest record, and a reload rewrites the dataset entirely, so garbage is bounded by one generation. There is no automatic compaction: MmapCacheManager.Compact(cache) merges every data file of a cache into one dense file, drops the dead frames, relocates the live keys in the index and returns the bytes it removed - 0 when the files already were one dense file, so a periodic caller is not paying for a full rewrite of a healthy catalog. It runs under the engine write lock, which is what lets it close and delete the files it replaced; a reload is still the cheaper answer for a catalog that can afford one, because compaction copies every live value.

The engine allocates the id of the merged file itself, and allocates it before opening the file that takes the next writes: a restart replays a directory in id order, so a merged copy must never look newer than a write that came after it. A merge that failed before the index moved onto it leaves the original files serving reads and its partial file deleted.

One Process Per Cache

Register claims {basePath}/{name}.lock and holds it until the manager is disposed. Two processes pointed at the same BasePath would pick the same next version directory and their FileMode.Create writers would truncate one another's frames, so the second one gets an InvalidOperationException naming the cache instead. The claim opens the file with FileOptions.DeleteOnClose: a killed owner leaves no lock behind for the next one to reason about. Caches with distinct names, or processes with distinct base paths, are unaffected.

TTL and Lazy Expiration

MmapCacheManager prefixes every payload with an 8-byte little-endian expireTicks timestamp; the engine, index and Bloom filter stay agnostic and store raw bytes. On read the timestamp is checked in place; an expired record is dropped through the normal delete path (lazy tombstone) and reported as a miss.

Because expiry is per record, Ttl is a lifetime, not a refresh interval - and because each record's deadline is offset forward by a hash of its key inside TtlJitter, a 100k-key catalog ages out across a window instead of all at once. The same Ttl also bounds how long a persisted snapshot may be reused at startup, which is what keeps a warm restart from serving a day-old catalog. Callers still decide when to reload; see LastReload.

Reload

await MmapCacheManager.Instance.ReloadAsync<Product>("products");
  1. A sibling engine is created in {name}_v{n+1} with bootstrapping disabled, so stale shards cannot resurrect.
  2. The supplier streams into it while the previous engine keeps serving every read, and its data files seal themselves as they reach the size cap.
  3. If the result is empty while the running snapshot holds records and AllowEmptyReload is false, the new engine and its directory are discarded and an InvalidOperationException is thrown - the running snapshot is untouched.
  4. The .committed stamp is written first, then the new engine, version and LastReload are published in one swap and the cache's L1 tier is cleared; the old engine is disposed and its directory deleted shortly after.

Writing the marker before the swap matters: the marker is what makes a directory loadable by a future process, so it must never describe an engine this process is not serving.

A second ReloadAsync for the same cache while one is in flight joins the running task rather than starting a duplicate load, so a stampede of staleness checks performs one supplier pass. Cancellation (caller token or manager shutdown) discards the partial engine directory and leaves the old engine intact.


Limits

Limit Value
Maximum key length ConcurrentRadixTree.MaxKeyDepth = 512 characters. Longer keys throw ArgumentException instead of silently disappearing.
Character set Keys are matched on full char values, so non-ASCII keys (sessiyon_ı vs sessiyon_i) are distinct.
Value size Unlimited; frames larger than 8 KB are assembled from pooled buffers.
Nodes per radix tree Indices are int, so a tree addresses up to ~2.1 billion nodes (28 bytes each) and throws on the write path at that ceiling.
Data file count Roughly dataset bytes / MaxDataFileBytes, plus one file being appended to. Each sealed file costs one mapping.
L1 entries per cache L1MaxSize (default 10,000; 0 disables the tier). The values held are bounded by that count, not by the dataset.
Reload concurrency One reload per cache; different caches reload independently.
Processes per cache name One. Register holds {basePath}/{name}.lock, so a second process on the same base path throws instead of sharing the directory.

Benchmarks

1.1.0 - measured on this layout

PerformanceBenchmark_Measurements (100,000 Product records, RadixTreeCapacity = 101,000, MaxDataFileBytes = 64 MB, default L1MaxSize = 10,000, net10.0, Release, Windows). These numbers are the live-mutation path: the catalog is written with Put after Register, so the data file stays open and reads are positioned reads rather than mapping slices - and every key is read once, which is the workload shape L1 cannot help (see the L1 table below).

Phase Duration Throughput p50 p95 p99 p99.9 Working set LOH Disk
Write (append) 778 ms 128,448 ops/s - - - - 84.84 MB 1.56 MB 11.89 MB
Read (positioned) 640 ms 156,052 ops/s 5.40 us 9.20 us 13.80 us 41.30 us 87.09 MB 2.32 MB -

GC across both phases: 8 Gen0, 7 Gen1, 1 Gen2; roughly 103 MB of cumulative allocations - serialization, the deserialized TValue, and the 10,000 hot values the default L1 tier keeps. The payload itself never enters the heap.

L1 Hot-Key Tier (Measured)

A 50,000-key catalog, net10.0 Release, Windows, measured by HotKeyBenchmarkTests. The same definition run twice, with only L1MaxSize different:

Workload L1MaxSize = 0 L1MaxSize = 10,000 Effect
40,000 reads over a 1,000-key hot set 97-105 ms (2.42-2.62 us/op) 10-11 ms (0.25-0.28 us/op) 9-10x faster
49,000 reads, every key exactly once 118-129 ms (2.4 us/op) 165-190 ms (3.4 us/op) ~1.4x slower

The tier pays for keys that repeat and costs bookkeeping for keys that do not: a workload that streams the whole catalog once, or whose key set is far larger than L1MaxSize, should set L1MaxSize = 0 and keep the read path exactly as the "off" column.

Historical ledger (1.0.x layout, kept for scale reference)

The rows below come from StressTest_Scale_Measurements on the previous engine, which buffered writes in an off-heap MemTable arena behind a write-ahead log and flushed them into SSTables. That layout no longer exists in 1.1.0, where the appended file is the table; "Flush threshold" names the knob of that build (MemTableFlushThresholdBytes, now replaced by MaxDataFileBytes). The throughput, latency and GC columns stay informative about the index and the read path, which did not change.

Record Count RadixTree Capacity Flush threshold Write Duration Write Throughput Read Duration Read Throughput Avg Latency Disk Footprint Post-Write Working Set Post-Read Working Set GC Collections (Gen0/Gen1/Gen2)
1K 2,000 64 MB 39 ms 25,570/s 10 ms 91,557/s 10.64 us 0.11 MB 62.20 MB 62.47 MB 0 / 0 / 0
10K 15,000 64 MB 157 ms 63,410/s 39 ms 250,872/s 3.94 us 1.16 MB 34.29 MB 40.50 MB 0 / 0 / 0
100K 150,000 32 MB 779 ms 128,268/s 332 ms 300,333/s 3.30 us 11.89 MB 63.45 MB 73.13 MB 5 / 1 / 0
1M 1,500,000 32 MB 5,101 ms 196,028/s 1,749 ms 571,649/s 1.72 us 118.03 MB 180.23 MB 258.03 MB 55 / 12 / 7
5M 7,000,000 16 MB 36,427 ms 137,259/s 7,678 ms 651,128/s 1.46 us 602.43 MB 15.68 MB 40.84 MB 310 / 114 / 78
10M 12,500,000 16 MB 76,647 ms 130,467/s 16,002 ms 624,918/s 1.52 us 1,208.15 MB 7.84 MB 79.22 MB 608 / 222 / 150
50M 65,000,000 4 MB 390,336 ms 128,095/s 83,076 ms 601,853/s 1.57 us 6,167.18 MB 2.62 MB 387.79 MB 3,591 / 1,978 / 1,136
100M 115,000,000 2 MB 813,904 ms 122,865/s 196,056 ms 510,057/s 1.86 us 12,365.99 MB 2.56 MB 766.00 MB 7,039 / 4,154 / 2,686

Note: GC counts are cumulative across both write and read phases for each iteration. Write throughput stays above 120K ops/sec even at 100M scale, which is the point of a sequential append with an in-memory index.

Read latency distribution (percentile analysis, 1.0.x layout)

Record Count p50 p95 p99 p99.9 Max Latency
1K 2.60 us 3.40 us 12.60 us 7,619.00 us 7,619.00 us
10K 3.10 us 6.90 us 12.10 us 21.20 us 151.20 us
100K 3.10 us 4.50 us 6.10 us 11.30 us 1,691.40 us
1M 1.40 us 3.30 us 5.10 us 15.50 us 10,994.80 us
5M 1.30 us 2.20 us 3.20 us 7.00 us 2,598.30 us
10M 1.40 us 2.30 us 3.60 us 7.20 us 2,171.90 us
50M 1.40 us 2.30 us 4.60 us 23.70 us 5,312.80 us
100M 1.30 us 2.20 us 5.00 us 42.00 us 36,225.70 us

Key insight: p50 latency stays at or below 3.1 us across all scales. Even at 100M records the median read is 1.30 us: a Bloom pre-check plus a pointer chase through unmanaged memory, then one slice of a mapped page.

Detailed heap metrics (100M records, 1.0.x layout)

Phase Working Set Target Heap Fragmentation Net Allocated Gen0 Gen1 Gen2 LOH POH
Baseline (Empty) 11.96 MB 1.31 MB 0.05 MB 0.03 MB 0 0 0 0.09 MB 0.02 MB
Post-Write 2.56 MB 5.42 MB 0.00 MB 70,471.95 MB 7,039 4,154 2,686 0.09 MB 0.02 MB
Post-Read 766.00 MB 767.64 MB 0.00 MB 54,856.30 MB 4,801 401 401 763.03 MB 0.02 MB
After Cleanup 0.81 MB - - - - - - - -
  • Memory stabilization: writes are chunked and each iteration disposes its engine, so at 5M-100M scale (20x growth) the post-write working set stayed between 2.56-15.68 MB, and every iteration returned to a ~0.8 MB baseline after cleanup.
  • Near-constant read latency: total read duration grows with the dataset, per-operation latency does not (1K: 10.64 us avg, 1M: 1.72 us, 100M: 1.86 us).
  • Managed bloat: despite roughly 134 GB of cumulative allocated bytes in the 100M run, post-write LOH stayed at the 0.09 MB baseline - the payload never entered the managed heap, and the only per-read allocation is the deserialized TValue.
  • GC pressure: the write phase dominates it, through serialization and temporary buffers; at 100M, read-phase Gen2 collections (401) were about 15% of the write-phase count (2,686).

Performance Notes

  • Early Read Exits: every Get consults the Bloom filter first; a key that was never added returns without traversing the tree or touching the file. The filter is append-only, so it can produce false positives but never false negatives.
  • Mapped, Not Buffered: sealed values are ReadOnlySpan<byte> slices of the OS mapping, so the pages a workload actually reads are the only ones resident. Records in the file still being appended to cost one positioned read; that is why a supplier load seals explicitly and why a hot catalog reloads rather than accumulating Put traffic forever.
  • Prefix Memory Sharing: replacing a Dictionary with a ConcurrentRadixTree lets keys with a common prefix (session_xyz, session_abc) share nodes, which cuts allocation and makes prefix scans follow pointers instead of filtering a hash map.
  • L1 For Keys That Repeat: a hot key costs a dictionary lookup instead of a file read plus a Deserializer pass - measured at 9-10x on a 1,000-key hot set (Benchmarks). Keys that never repeat pay the tier's bookkeeping instead, so a scan-each-key-once workload sets L1MaxSize = 0.
  • Concurrent Reads: reads take the engine lock in read mode, so thousands run in parallel. Sealing, rotation and disposal take the write lock and are short; compaction is the deliberate exception, pausing its own cache for the length of the merge.
  • Deterministic Cleanup: mappings, views, native pointers and file handles are released on dispose, which is why each stress iteration returns to a sub-1 MB working set.

Migrating from 1.0.x

1.0.x 1.1.0
MemTableFlushThresholdBytes MaxDataFileBytes - the size cap of one append-only file. The in-RAM table and the flush threshold it triggered are gone.
ReloadOnInit (bool) OnStartup (StartupFillPolicy). Note the inversion: ReloadOnInit = false meant "do not read what is on disk, start empty". LeaveEmpty still means that, and ReuseIfFresh is the new default that does serve a fresh snapshot from disk.
wal_N.log files No separate log. segment_N.sst frames are written once and serve both roles. Old WAL files are ignored and deleted with their directory.
LsmEngine.ForceClearWalAndIndex() Removed. To wipe a cache, delete its version directories and ReloadAsync.
Lsm.Compactor (the caller supplied the segment id) Removed. LsmEngine.Compact() and MmapCacheManager.Compact(cache) merge the files and allocate the id themselves: an id handed in from outside is free to collide with the next file the engine opens, and FileMode.Create would truncate the merge through it.
CacheAlreadyReloadingException Removed. A second ReloadAsync joins the in-flight reload.
Write-through WAL (FileOptions.WriteThrough on every frame) Flushed but not write-through appends. Frames survive a killed process; a power loss is no longer covered by the log.
Snapshot reuse at boot Register reads the .committed load stamp and reuses the snapshot while it is inside Ttl.
L1MaxSize / L1Ttl Declared in 1.0.x but never read by any code path. Both now drive a real bounded LRU of deserialized hot keys. A 1.0.x definition that set them silently got no tier; the same definition on 1.1.0 gets one, so L1MaxSize = 0 is the switch back to the old behaviour.
RadixTreeCapacity default 1,000,000 100,000. The Bloom filter is allocated up front at ~1.2 bytes per expected key, so the old default held ~1.2 MB of native memory per cache even for a catalog of tens of keys. Name your own expected count if the catalog is larger.
Two processes on one BasePath Register claims {basePath}/{name}.lock for the life of the process, so the second one throws InvalidOperationException rather than truncating the first one's data files.

A directory written by 1.0.x carries no .committed marker, so the first 1.1.0 start rebuilds from the supplier and stamps the result. From then on restarts are warm. The file header also changed (MMC2, layout 2), so foreign files are detected by their header and never indexed.


Contributing

Pull requests are welcome. For significant architectural adjustments, please open an issue first to discuss your proposed strategy.

git clone https://github.com/BurakKontas/MmapCache
cd MmapCache
dotnet build
dotnet test MmapCache.Tests/MmapCache.Tests.csproj -v normal

Please note that contributions are subject to the terms of the GPL-3.0 license - by submitting a pull request you agree that your contribution will be distributed under the same license terms.


License

Copyright (C) 2026 Arda Burak Kontas

MmapCache is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License v3.0 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 269 11/3/2026
1.0.7 165 5/29/2026
1.0.6 149 5/28/2026
1.0.5 139 5/28/2026
1.0.4 134 5/27/2026
1.0.3 128 5/26/2026
1.0.2 139 5/26/2026
1.0.1 127 5/26/2026