Eryri.FileDistributedCache
1.0.2
See the version list below for details.
dotnet add package Eryri.FileDistributedCache --version 1.0.2
NuGet\Install-Package Eryri.FileDistributedCache -Version 1.0.2
<PackageReference Include="Eryri.FileDistributedCache" Version="1.0.2" />
<PackageVersion Include="Eryri.FileDistributedCache" Version="1.0.2" />
<PackageReference Include="Eryri.FileDistributedCache" />
paket add Eryri.FileDistributedCache --version 1.0.2
#r "nuget: Eryri.FileDistributedCache, 1.0.2"
#:package Eryri.FileDistributedCache@1.0.2
#addin nuget:?package=Eryri.FileDistributedCache&version=1.0.2
#tool nuget:?package=Eryri.FileDistributedCache&version=1.0.2
Eryri.FileDistributedCache
Keep more reusable data without giving more RAM to your cache—or running another cache service. Eryri.FileDistributedCache stores disposable cache values on the local filesystem behind .NET's IDistributedCache and IBufferDistributedCache APIs. Give it a byte limit and it evicts entries to make room before admitting a new write; expired entries are cleaned up automatically.
It is built for a single process, with concurrent access, configurable eviction, synchronous and asynchronous operations, and Native AOT compatibility. Use it directly when local disk is the right cache, or register it as the secondary provider for HybridCache when you want a memory-first cache with a larger local-disk tier.
Local, ephemeral, not shared. IDistributedCache is the interface this package implements, not a promise of distributed storage. Each process has its own cache; entries are disposable and must be recoverable from your source of truth. Do not use this provider when replicas must share entries or cache contents must survive restarts.
Why use it?
- Keep RAM for your application. Store reusable payloads in files rather than retaining the whole disk-backed cache in memory. A local filesystem is useful when your reusable working set is larger than the memory budget you want to assign to caching.
- Keep writes moving near capacity. Set a byte limit and the cache evicts entries when needed to make room before adding a new one. Choose LRU, LFU, FIFO or TTL to decide what goes first.
- Let expired data clean itself up. Absolute and sliding expiration are supported. A background cleanup timer is rescheduled for the next expiry, using a priority queue rather than relying solely on fixed-interval sweeps.
- Fit familiar .NET APIs. Use
IDistributedCacheorIBufferDistributedCache; the implementation is thread-safe and Native AOT-compatible. - Avoid a new service for a local need. There is no cache server to deploy just to give one process more disposable cache capacity. The trade-off is that entries are not shared across processes.
Good fit: a single-process service or worker with reproducible cache values and useful local disk space. Not a fit: cross-replica consistency, persistence, or a filesystem you cannot afford to fill with disposable data. The cache's configured byte limit controls its own entries; it does not reserve free space for other applications.
Scope at a glance
| Requirement | This package |
|---|---|
| Familiar .NET caching interface | IDistributedCache and IBufferDistributedCache |
| Local disk for disposable cache values | Yes |
| Expiry eviction | Yes; automatic; rescheduled for the next expiry, using a priority queue rather than relying solely on fixed-interval sweeps |
| Capacity-based eviction | Yes; set a byte limit for automatic capacity eviction |
| Shared entries across application processes | No |
| Cache persistence across restarts | No |
| Automatic RAM-pressure-triggered spill | No; use as a disk-backed tier, not as an automatic memory overflow mechanism |
Install and get started
The NuGet package ID is Eryri.FileDistributedCache.
dotnet add package Eryri.FileDistributedCache
The namespace is Eryri.Extensions.Caching.FileSystem.
using Eryri.Extensions.Caching.FileSystem;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using var services = new ServiceCollection()
.AddDistributedFileCache()
.BuildServiceProvider();
var cache = services.GetRequiredService<IDistributedCache>();
await cache.SetStringAsync(
"product:42",
"Cached product data",
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
var value = await cache.GetStringAsync("product:42");
Console.WriteLine(value ?? "Cache miss");
Treat a miss as normal: an entry may have expired, been evicted, or disappeared when the process restarted. Retrieve or recompute the value from its source of truth and write it back.
Use with HybridCache
HybridCache can use an IDistributedCache provider as its secondary tier. Register this provider alongside HybridCache to put a local filesystem behind the usual in-memory tier. This is not a guarantee that values spill to disk only after RAM fills: HybridCache manages its tiers according to its own behavior and configuration.
using Eryri.Extensions.Caching.FileSystem;
using Microsoft.Extensions.Caching.Hybrid;
using Microsoft.Extensions.DependencyInjection;
using var services = new ServiceCollection()
.AddDistributedFileCache()
.AddHybridCache().Services
.BuildServiceProvider();
var cache = services.GetRequiredService<HybridCache>();
var options = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(10),
LocalCacheExpiration = TimeSpan.FromSeconds(5), // Keep in-memory items for only a short period
Flags = HybridCacheEntryFlags.DisableLocalCache // Disables the 'IMemoryCache' for the purpose of thie example
};
await cache.SetAsync("product:42", "Cached product data", options);
var value = await cache.GetOrCreateAsync(
"product:42",
_ => ValueTask.FromResult("Value to create on a miss"),
options);
Console.WriteLine(value);
Both tiers remain local to this process. For a shared secondary cache across replicas, use a backend designed for sharing.
Expiration and capacity
Set a byte-based size limit if you want the cache to control its footprint. When a new entry would exceed that limit, the cache evicts existing entries as needed before adding it. The configured eviction policy determines which eligible entries are selected. Expired entries are also removed automatically by a background timer scheduled for the next expiry.
| Policy | Entry selected for capacity eviction | Useful when |
|---|---|---|
| LRU | Least recently used | Recently accessed data is most likely to be needed again. |
| LFU | Least frequently used | Frequently requested data should survive short bursts of one-off reads. |
| FIFO | First added | Simple insertion order is preferable when older data becomes less useful over time. |
| TTL | Soonest to expire | Entries closest to expiry have the least remaining useful life. |
The package supports DistributedCacheEntryOptions: AbsoluteExpiration, AbsoluteExpirationRelativeToNow, and SlidingExpiration. Expiration controls whether an entry is valid; a capacity policy chooses which entries to remove to admit new data. The two are different mechanisms.
For manual capacity reduction, IFileDistributedCache.Compact(decimal percentage) selects entries according to the configured eviction policy. For example, Compact(0.10) requests removal of at least 10% of existing entries. This is useful even when no size limit is configured.
Configuration reference
| Option | Purpose |
|---|---|
EvictionPolicy |
Selection policy for capacity eviction and compaction. |
SizeLimitBytes |
Maximum configured cache size in bytes. |
SizeLimitMiB / SizeLimitGiB |
Alternative units for configuring the byte limit. |
ExpirationScanFrequency |
Minimum interval between expiry cleanup runs; zero or a negative value schedules the next run for the soonest upcoming expiration. |
DefaultSlidingExpiration |
Default sliding expiry where an entry does not specify one. |
DefaultAbsoluteExpirationRelativeToNow |
Default relative absolute expiry, calculated when an entry is added. |
Operational boundaries
- One process owns one cache. Do not share the cache directory or assume another process can observe its entries safely.
- Storage is temporary. The cache creates a temporary folder under the current user's temp directory at startup and removes it during normal shutdown. Crashes or forced termination may leave files behind; do not rely on shutdown cleanup for durability or guaranteed reclamation.
- Misses are expected. Cached values must be safe to lose and regenerable after expiration, eviction, restart, or storage failure.
- Filesystem access matters. The process needs permission to create, read, write, and delete files in its temp directory. A configured cache-size limit does not protect against another workload filling the underlying filesystem.
- Write failures: If the filesystem rejects a write, the entry is not added and an error is logged. Callers should not treat
Setas proof that the entry can later be read back.
Soak Benchmarks
The benchmark that matters most for this package is sustained operation while the cache is already full: this tests the cost of making room, not just writing into an empty directory. The figures below are useful directional evidence, not a cross-machine performance guarantee.
- PayloadSize=1 byte
- CacheSizeLimit=300
- InvocationCount=300
- IterationCount=5
- UnrollFactor=1
- WarmupCount=1
Tests located here: BenchmarkTests.cs
Eryri.FileDistributedCache
| Method | Mean | Error | StdDev |
|---|---|---|---|
| Write | 505.73 us | 97.77 us | 15.130 us |
| WriteAsync | 620.54 us | 236.39 us | 61.390 us |
| Read | 52.02 us | 13.57 us | 3.523 us |
| ReadAsync | 140.60 us | 27.10 us | 7.038 us |
Net.DistributedFileStoreCache
| Method | Mean | Error | StdDev |
|---|---|---|---|
| Write | 179,946.73 ns | 24,628.184 ns | 6,395.861 ns |
| WriteAsync | 236,976.73 ns | 17,474.210 ns | 4,537.997 ns |
| Read | 74.40 ns | 28.893 ns | 7.503 ns |
| ReadAsync | 209.08 ns | 8.319 ns | 1.287 ns |
DamianH.FileDistributedCache
1us == 1000ns
| Method | Mean | Error | StdDev |
|---|---|---|---|
| Write | 1,054.7 us | 341.63 us | 52.87 us |
| WriteAsync | 1,049.8 us | 235.54 us | 36.45 us |
| Read | 150.8 us | 40.47 us | 10.51 us |
| ReadAsync | 205.4 us | 15.04 us | 3.91 us |
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. |
-
net10.0
- Microsoft.Extensions.Caching.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.0)
- Microsoft.Extensions.Options (>= 10.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.