skip to content

A remittance service caps its exchange-rate IMemoryCache with SizeLimit; what must every entry then carry, and what happens when the limit is reached?

level: seniorimportance: should knowfreq 34%

answer

  1. SizeLimit null by default, units arbitrary
  2. SetSize or InvalidOperationException
  3. over-limit write is dropped, reason Capacity
  4. compact to 95 percent, CompactionPercentage 0.05
  5. dedicated MemoryCache instance, not the shared one

basics

~10 s

Once MemoryCacheOptions.SizeLimit is set, every entry needs a Size or committing it throws InvalidOperationException. A write that would exceed the limit is not stored, and a background compaction evicts expired, then low-priority, least-recently-used entries.

solid answer

~50 s

`SizeLimit` is `null` by default, so the cache is unbounded and entry sizes are ignored. When you set it, sizes are unitless numbers you choose (one per rate, or an estimated byte count), and **every** entry written to that instance must call `SetSize` or set `Size`; otherwise committing it throws `InvalidOperationException` ("Cache entry must specify a value for Size when SizeLimit is set."). A write that would push the total over the limit is **not added**: the new entry is evicted with `EvictionReason.Capacity`, any older entry for that key is dropped too, and a background compaction removes entries until the total is `CompactionPercentage` (0.05) below the limit, taking expired entries, then `Low`, `Normal` and `High` priority by least recent access; `NeverRemove` is never compacted. Because the limit applies to every consumer of the shared `AddMemoryCache` instance, give size-limited data its own `MemoryCache`.

code

csharp · 8 lines
csharp
public sealed class RateWriter(RateCache rates)
{
    public decimal Store(string pair, decimal rate) =>
        rates.Cache.Set($"fx:{pair}", rate, new MemoryCacheEntryOptions()
            .SetSize(1)
            .SetPriority(CacheItemPriority.High)
            .SetAbsoluteExpiration(TimeSpan.FromSeconds(30)));
}

go deeper

for a junior

Recall that IMemoryCache has no size limit by default and that once SizeLimit is set every entry needs SetSize.

for a middle

Explain that sizes are unitless, the InvalidOperationException for a missing size, and how priority and least recent access choose which entries compaction removes.

for a senior

Explain why a limit on the shared AddMemoryCache instance breaks other writers, that over-limit writes are silently dropped with reason Capacity, and how statistics reveal it.

for a principal

Decide how to budget process memory across caches with arbitrary units, and when a bounded in-process tier stops paying for itself compared with a shared store.

## The default is unbounded `MemoryCacheOptions.SizeLimit` is `null` unless you set it. With no limit, `MemoryCache` grows until the process runs out of memory: the ASP.NET Core docs say plainly that the runtime does not trim the cache under memory pressure. Entry sizes are ignored when no limit is set. ## What a limit demands `SizeLimit` has **no unit**. The cache only adds up the `Size` values entries declare and compares the sum to the limit, so you pick a unit and every writer must use it - one unit per exchange rate, or an estimated byte count for larger objects. Once a limit is set, each entry written to that cache instance must declare a size, through `SetSize(long)` on `MemoryCacheEntryOptions` or `ICacheEntry`, or the `Size` property. An entry without one fails when it is committed (on `Set`, or when the `ICacheEntry` from `CreateEntry` or a `GetOrCreate` factory is disposed): - `InvalidOperationException`: "Cache entry must specify a value for Size when SizeLimit is set." Negative sizes are rejected with `ArgumentOutOfRangeException`. ## Why the shared instance is the wrong place `AddMemoryCache(o => o.SizeLimit = 2_000)` configures the **one** `IMemoryCache` every class in the container shares. Any code that writes to it without a size - your own older features, or a library that injects `IMemoryCache` - starts throwing the moment you add the limit. The caching docs warn about exactly this and recommend a dedicated cache. In the remittance service: ```csharp public sealed class RateCache : IDisposable { public MemoryCache Cache { get; } = new(new MemoryCacheOptions { SizeLimit = 2_000, TrackStatistics = true }); public void Dispose() => Cache.Dispose(); } builder.Services.AddSingleton<RateCache>(); ``` Each rate is written with `.SetSize(1)`; the shared `IMemoryCache` stays unbounded for everything else. ## What happens at the limit The size check runs on every commit. If the new total would exceed `SizeLimit`: 1. The **new entry is not added**. It is marked expired with `EvictionReason.Capacity` and its eviction callbacks run; `Set` still returns the value, so the caller does not notice. 2. Any **existing entry for the same key is removed** as well, so an over-limit update can leave the key empty. 3. An **overcapacity compaction** is queued on the thread pool (one at a time). It removes entries until the total is at or below `SizeLimit - SizeLimit * CompactionPercentage`; with the default `CompactionPercentage` of **0.05** that is 95 percent of the limit. Compaction picks victims in this order: | Step | Entries removed | |---|---| | 1 | already expired entries | | 2 | `CacheItemPriority.Low`, least recently accessed first | | 3 | `CacheItemPriority.Normal` (the default priority), least recently accessed first | | 4 | `CacheItemPriority.High`, least recently accessed first | | never | `CacheItemPriority.NeverRemove` | The docs page adds "earliest absolute expiration" and "earliest sliding expiration" as later tie-breakers; the .NET 10 source sorts each priority bucket by last access only and lists those ideas as unimplemented comments. `MemoryCache.Compact(double percentage)` triggers the same procedure manually, but it removes that fraction of the entry **count**, treating every entry as size one. ## Choosing sizes Three approaches cover most services: - **Count entries.** `SetSize(1)` on everything turns `SizeLimit` into a maximum entry count. Good when entries are similar, as exchange rates are. - **Estimate bytes.** For strings or arrays, length times element size is a fair estimate; for object graphs a rough constant per type is enough, since the goal is a bound, not accounting. - **Weight by cost.** Give entries that are expensive to rebuild a `High` priority instead of inflating their size, so compaction prefers cheaper victims. ## Watching it Set `TrackStatistics = true` and call `GetCurrentStatistics()` to read `CurrentEntryCount`, `CurrentEstimatedSize` (the summed sizes, only when a limit is set), `TotalHits` and `TotalMisses`. A rising miss count with a size pinned near the limit means writes are being rejected and compacted. ## The traps - **A limit on the shared cache** breaks every writer that never called `SetSize`. - **Sizes in mixed units** make the limit meaningless; one writer counting bytes and another counting items starves one of them. - **`NeverRemove` everywhere** leaves compaction nothing to remove, so every new write is rejected. - **Expecting the write to fail loudly.** At the limit the value is silently not cached; the symptom is a falling hit rate, not an exception.

  • Your team set SizeLimit through AddMemoryCache and an unrelated endpoint now returns 500 errors; what happened?
    The limit applies to the single `IMemoryCache` every component shares. The endpoint's code, or a library it calls, writes entries without `SetSize`, and since a limit now exists, committing those entries throws `InvalidOperationException`. Move the size-limited data to its own `MemoryCache` instance and remove the limit from the shared one.
  • How does Compact(0.25) differ from the compaction triggered by reaching SizeLimit?
    Both evict expired entries first and then go through the Low, Normal and High priority buckets by least recent access. `Compact(0.25)` aims to remove a quarter of the entry count, treating every entry as size one. Overcapacity compaction targets the summed `Size` values and stops at `SizeLimit` minus `CompactionPercentage`.

  • Setting SizeLimit makes MemoryCache measure each entry's memory footprint in bytes
  • Without SizeLimit the runtime evicts entries automatically when memory runs low
  • A write over the size limit throws, so callers always know caching failed
  • Entries without SetSize are simply ignored by the limit once SizeLimit is set
  • CacheItemPriority.NeverRemove entries are evicted last once lower priorities are exhausted