MatrixCache
matrixcache is an open-source, standalone, Rust-native multi-tier cache
library extracted from TemporalStore and reusable by any Rust service. It is
licensed under Apache-2.0 and open to anyone, anywhere: use it, fork it, change
it, ship it, and send the changes back if you want to. It manages a hot in-memory
(DRAM) tier, a persistent-memory-like resident tier, and an SSD tier, with
admission control, cross-tier eviction, read-through refill, pinned handles,
invalidation, and asynchronous writeback with backpressure accounting.
Related Projects
On this page: Start here | Access patterns |
Usage | Durability | Sizing |
Measurement | Contributing.
All six projects are independently usable under Apache-2.0. Choose by workload
and execution model; MatrixCache itself does not start a network cache service.
| Project |
Use it for |
Execution model |
| MatrixCache (this repository) |
Tiered caching inside a Rust application |
Embedded library; the application owns authoritative data and network requests. |
| TemporalStore |
Temporal features, sequences, and context serving |
Serving engine with its own endpoints, persistence, and replication settings. |
| MatrixObject |
Distributed object storage |
Object API with separately configured metadata and replica services. |
| MatrixRaft |
Consensus inside a service |
Embedded library; the host supplies transport and state-machine application. |
| MatrixArk |
Context ingestion, retrieval, and feedback |
Python runtime with explicitly configured storage and model providers. |
| MatrixAdsDemo |
Exploring an ads retrieval and auction pipeline |
Standalone generated-data demonstration, not a cache-server benchmark. |
For cache integration, begin with access patterns
and durability, rather than treating a library call as a service acknowledgement.
Getting Help
Search public issues before
opening a report. Include the revision, Rust version, Cargo features, enabled tiers,
capacity and shard settings, key/value sizes, and the smallest reproducing call
sequence. Distinguish copied, shared, and pinned reads, and identify whether a
problem involves a resident hit, refill, eviction, writeback, or restart recovery.
Use synthetic values and remove credentials from backend configuration. Follow the
security policy for sensitive reports, not a public issue. For code
or documentation changes, start with CONTRIBUTING.md.
Implementation entry points
Bounded eviction groups candidates using a fixed-size position table rather than
sorting every grouped candidate window. Selection compares borrowed score rows,
retains the winning index, and clones only the selected victim key. Group score,
victim score, and key still determine ordering. The ungrouped shortcut and wider
fallback remain separate paths. This reduces selection work without increasing
configured cache capacity; it does not by itself establish higher application
throughput or reduce persistent bytes written.
Start Here
MatrixCache is an embedded library, not a network cache server. Applications own request
routing and authoritative data durability. Shared-buffer and pinned reads can retain old
value allocations after replacement; release handles promptly and size memory for the
active workload, not only the current key count. Cache-tier durability settings do not
replace the application's commit protocol.
Deployment Responsibilities
| MatrixCache provides |
The embedding application provides |
| Tier admission, eviction, and read-through refill |
Authoritative records, request routing, and consistency policy |
| Owned, shared-buffer, and pinned read choices |
Handle lifetimes and budgets for retained old values |
| Configurable tier persistence and writeback |
The commit boundary and crash-recovery guarantees of the service |
| Local sharding and placement helpers |
Network transport, membership, and replica coordination |
Memory-only operation skips SSD existence-key encoding when the SSD backend is disabled.
Enabled SSD backends still perform their existence checks; disabling a tier is not the same
as configuring an enabled tier with no capacity. This avoids unnecessary key-rendering work
without changing cache-hit results or the application's durability policy.
Deployment and Upgrade Checklist
- Pin the crate version or revision and choose Cargo features explicitly. The
default RocksDB SSD backend and the no-default-features compatibility backend
have different build requirements and storage paths.
- Keep authoritative records recoverable outside the cache. Select tier sync and
writeback policies using Durability, not cache-hit behavior.
- Include retained shared and pinned handles, queued work, and backend memory
in the process budget; configured tier capacity is not a process RSS limit.
- Register record-key indexes only for namespaces that need targeted lookup or
invalidation. Registration backfills keys and adds ongoing index maintenance;
unregistered namespaces retain the scan path.
- Compare the same backend, shard count, capacity, payloads, and promotion policy
when evaluating a change. Local cache operations are not network service QPS.
Choose an Access Pattern
| Workload |
Choice |
Cost to include |
| Caller needs independent mutable bytes |
Copied reads |
Result allocation and copying, including on a memory hit. |
| Caller can consume a shared immutable value |
Shared-buffer reads |
Old allocations remain live while handles exist; returned ownership is not a process-memory bound. |
| Scan should not warm upper tiers |
No-promotion reads or pinned handles |
Release retained handles; lower-tier decoding and I/O still apply. |
| Repeated invalidation of selected records |
Record-scoped lookup |
Opt-in namespace indexes consume metadata and require normal deletion afterward. |
| Placement across changing nodes |
Cluster topology helpers |
The host must transfer data and coordinate membership; a handoff plan does not move bytes. |
See read ownership before calling a path
zero-copy. Compare resident hits, SSD misses, refill, and writes at capacity
separately: each exercises different allocation, locking, and eviction work.
Budget read ownership alongside cache capacity
A copied read transfers independent bytes to the caller. Shared or pinned reads
can avoid that copy, but an overwritten value remains allocated while a caller
retains its handle. Release handles at the request boundary rather than storing
them indefinitely in another cache or work queue. Include those retained values,
refill buffers, and pending writeback in the application's memory budget.
Compare equivalent ownership and promotion modes when measuring latency. A warm
shared-buffer hit is not the same workload as a copied hit or an SSD refill, and
configured tier capacity alone does not bound total process memory.
Features
- Multi-tier placement across DRAM, a PMEM-like resident tier, and an SSD tier.
- Admission policy, cross-tier eviction, and read-through refill, with optional
bounded background promotion for PMEM and SSD hits. Queue pressure falls back
to immediate promotion so warming remains reliable.
- Opt-in bounded cold-tier migration prepositions least-recently-accessed DRAM
and PMEM values in SSD when write-through is disabled, with value
revalidation before each persistent write.
- Pinned (no-promotion) handles and pinned-acquire APIs.
- Shared-buffer reads for retrieval and scan paths that can consume cached
bytes without copying them.
- Asynchronous writeback with backpressure counters and cache-pressure helpers.
- Shared bounded executors with asynchronous fire-and-forget and joined work,
priority scheduling, queued-task expiration, runtime worker resizing, and
validated CPU placement for every persistent worker, including workers added
by later resizing. PMEM writer pools automatically use the CPUs available to
their NUMA node. Shared common and collection pools release idle workers and
recreate them as queued work arrives; NUMA-bound writer pools remain fixed.
Live pool and queue statistics report placement success. Shutdown can either
drain accepted work or cancel queued work while allowing active tasks to
finish.
- Persistent-tier auto-recovery and restart refill.
- Latency and tier metrics for observability.
Executor completion is not a durability acknowledgement
For joined work, CacheExecutorTask::try_join waits for completion; despite its
name, it is not a nonblocking poll. It returns None for panicked, expired, or
cancelled tasks. Handle that outcome explicitly before publishing state that
depends on the task. Queue expiration and cancelling shutdown do not interrupt
an already running closure. A completed closure establishes only what that
closure did, not that authoritative records were synced or replicated. See the
executor implementation and
durability policy.
Read ownership and refill cost
Use shared-buffer reads when the caller can consume an owned shared handle, and
copied reads when it needs independent mutable bytes. Raw RocksDB SSD reads use
scoped native pins while validating their encoded block; the native pin does not
escape into the caller. Returning independent bytes still requires an owned
result, and compressed blocks still require decoding. This is not a promise that
every cache read is zero-copy.
SSD batches containing one unique key use a point read after duplicate coalescing;
larger batches retain the native multi-get path. This avoids singleton multi-get
scratch buffers without changing miss handling, result ownership, or refill policy.
Run cargo run --release --example storage_batch_read_cost to measure warm reopened
storage at 1, 16, and 128 requested keys with 256-byte and 4,096-byte values. The
example includes owned result allocation and missing keys; its timings are local
storage costs, not network service QPS or cold-device latency.
An SSD hit refills an enabled upper tier: DRAM when it can admit the value, or
PMEM when DRAM cannot and PMEM can. With promotion disabled, SSD-instance-only
mode, or no upper-tier capacity, it skips refill work. Revalidation prevents a
raced refill from reinstalling an invalidated value. Idle background polls also
avoid taking the cache write lock when their read-side check finds no work.
These paths reduce copying and lock contention; benchmark hit, miss, promotion,
and concurrent-write workloads separately before treating them as a QPS result.
Record-Scoped Key Lookup
For invalidation or expiry work on selected records, call
enable_record_key_index(namespace) and then
keys_for_records(shard_id, namespace, records). Both MultiLayerCache and
ShardedMultiLayerCache expose these APIs. Enabling a namespace backfills
existing tier keys; repeated registration does no work. Other namespaces do
not allocate per-entry record-index rows and retain the full tier-key scan.
The returned CacheRecordKeySnapshot contains sorted, deduplicated keys,
an indexed flag, and entries_examined. Lookup does not read value bytes or
SSD files. It is a key snapshot, not an invalidation transaction: callers
still perform deletion, and sharded snapshots visit cache shards sequentially
rather than atomically. Budget the additional index metadata for enabled
namespaces instead of treating reduced scan work as free memory.
may_have_record_keys(shard_id, namespace, record_key) is a conservative
presence query on both cache types. It does not allocate a key snapshot, scan
tiers, access values, or probe the SSD backend.
| Result |
Meaning |
true |
Indexed selectors exist, the namespace is unregistered, or an SSD backend is enabled. It does not guarantee a readable cached value. |