↑↓ to navigate Enter to open "…" all these words ANDOR to combine

Onboarding guide

9. Caching

What this group covers. Caching in this codebase is small, deliberate, and woven into the CQRS pipeline rather than scattered across handlers. The group is sixteen types: one port the Application layer depends on (ICacheService), two Infrastructure adapters that implement it (the in-process MemoryCacheService and the two-level HybridCacheService, the one cache service over a shared Redis), the prefix rule both adapters enforce (CachePrefixContract), the generation-token engine that lets both adapters invalidate a prefix without walking the keyspace (CachePrefixGenerations and its per-boundary RememberedToken), the hard-coded TTL default (CacheOptions) with the bound settings object that reproduces it from configuration (CacheSettings), the key-namespace pair (CacheKeyPrefixOptions plus its internal applier CacheKeyNamespace, checked at start-up by CacheKeyPrefixOptionsValidator) that keeps two applications sharing one Redis instance out of each other's keyspace by default, the two atomic fixed-window counter stores that live beside the cache rather than inside it (RedisCounterStore and its process-local fallback InMemoryCounterStore, with its immutable CounterWindow), and the hook every framework Redis connection runs before it connects (IRedisConfigurationOptionsConfigurator and its options-pipeline bridge RedisConfigurationOptionsPostConfigure). No handler ever talks to Redis or IMemoryCache directly: the read-through and invalidate-on-write behavior lives in two pipeline decorators taught in Group 5, CQRS Pipeline. This chapter is the cache's own machinery, the contract, the two backends, the prefix rule and the generation tokens, the TTL policy and its configuration object, the namespace, the counter stores and the connection hook, plus how they plug into that pipeline.

The contract. ICacheService (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICacheService.cs:9) is a textbook Clean Architecture port/adapter split (see primer §1): the interface lives in MMCA.Common.Application, both implementations live in MMCA.Common.Infrastructure, and application code compiles against the interface alone. It declares six members, all abstract, with no default bodies: GetAsync<T> returning T? with null for a miss (ICacheService.cs:16), TryGetAsync<T> (ICacheService.cs:32), GetFromSharedStoreAsync<T> (ICacheService.cs:59), SetAsync<T> with an optional TimeSpan? TTL (ICacheService.cs:68), RemoveAsync for one key (ICacheService.cs:78), RemoveByPrefixAsync for bulk eviction by key prefix (ICacheService.cs:102) and GetOrCreateAsync<T> (ICacheService.cs:130). TryGetAsync<T> reports presence separately from the value, because for a value-type T a GetAsync miss answers default(T) and cannot be told apart from a cached 0 or false (ICacheService.cs:18-22); every implementation reports real presence, since inferring it from a non-null value would report a value-type miss as found (ICacheService.cs:28-31). GetFromSharedStoreAsync<T> reads past any process-local copy, for values whose change on one replica must be visible on every other one at once (ICacheService.cs:35-39): single-use records (an OAuth exchange code, a password-reset or email-confirmation token, a second-factor time step) and flags another replica can set or clear, the login lockout flag and the soft-deleted-user marker. Everything read many times stays on GetAsync and loses only the local hit rate by coming here (ICacheService.cs:47-52); a store with no process-local tier answers it exactly as GetAsync (ICacheService.cs:55-56). GetOrCreateAsync<T> returns the cached value or runs the factory and caches its result, with concurrent misses on one key running the factory once per process (ICacheService.cs:104-110). Its XML doc is explicit about two limits that matter: it caches whatever the factory returned, failed Result included, which is exactly why the caching decorators do not route through it, and its stampede protection is per process (ICacheService.cs:117-128). Counters are deliberately not on this interface: they live in ICounterStore, because a cache entry written through a get and a set cannot be incremented atomically (ICacheService.cs:6-7); the counter section below covers the two stores. RemoveByPrefixAsync is the load-bearing member: it is what lets a single write evict every cached read it could have staled. Its argument has a contract: the prefix must be empty (every entry) or end at a : boundary, so "MMCA.Sample.Event:" is accepted and "MMCA.Sample.Ev" is rejected with an ArgumentException (ICacheService.cs:80-101). That boundary rule is what lets the shipped stores invalidate without enumerating keys: each keeps one generation token per : boundary and folds the tokens into every stored key, so invalidating a prefix is one write, and every shipped store enforces it so behavior does not depend on the backend (ICacheService.cs:91-94). The backends had to be built rather than used off the shelf because neither primitive offers it (IMemoryCache has no key enumeration, and HybridCache's tag invalidation does not reach a replica that has already met the tag, as the generation-token section below explains). [Rubric §3, Clean Architecture] assesses whether dependencies point inward and infrastructure stays replaceable; this is that rule in one file, since the only thing Application knows about caching is seven method signatures.

Backend selection happens once, at the composition root, and refuses to guess. AddCaching(IConfiguration?) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:29, called from AddInfrastructure at DependencyInjection.cs:147) always calls AddMemoryCache() (DependencyInjection.Caching.cs:31), then binds the shared Cache configuration section three ways when configuration was supplied (DependencyInjection.Caching.cs:43-62): to CacheKeyPrefixOptions for the key namespace, validated at start-up by CacheKeyPrefixOptionsValidator (DependencyInjection.Caching.cs:47-51), to CacheSettings for the TTL policy, validated at start-up (DependencyInjection.Caching.cs:53-56), and to QueryCachePipelineSettings for the one knob the Application-layer query decorator needs (DependencyInjection.Caching.cs:58-61, defined in that layer because it cannot reference Infrastructure). Without configuration both settings objects are still registered at their defaults (DependencyInjection.Caching.cs:63-67), so IOptions<T> always resolves. It also post-configures the Redis output-cache store, when one is registered, with the same key namespace as its InstanceName unless a host set one, so two applications on one Redis do not share output-cache entries or tag sets (DependencyInjection.Caching.cs:69-82). ICacheService itself is registered through TryAddSingleton with a factory (DependencyInjection.Caching.cs:84-105) that has only one answer to give: a MemoryCacheService over a size-limited cache instance of its own rather than the shared IMemoryCache, handed the bound cache settings (DependencyInjection.Caching.cs:100-104). If the factory finds a real out-of-process IDistributedCache registered (anything but the default MemoryDistributedCache), it throws an InvalidOperationException that names AddCommonHybridCache and its guarded form instead (DependencyInjection.Caching.cs:91-98), because falling back to the in-process cache would silently make single-use records and the lockout flag per-replica (DependencyInjection.Caching.cs:88-90). A shared store is served by the two-level cache only. The same method registers the IDistributedLock that the five in-framework callers pair with the cache (the API idempotency filter, password-reset token redemption, the two-factor authenticator, OAuthControllerBase when given a lock, and passkey challenges, DependencyInjection.Caching.cs:107-114), Redis-backed when a multiplexer is present and process-local otherwise (DependencyInjection.Caching.cs:115-129), and the ICounterStore, chosen exactly as the lock is: a RedisCounterStore on the multiplexer and the cache namespace when one is registered, an InMemoryCounterStore otherwise (DependencyInjection.Caching.cs:131-146). A single-process monolith therefore caches and counts in-process for free, and the identical application code uses Redis the moment the host wires it: no flag, no per-environment branch in a handler. This is the same "abstraction in Application, transport chosen at the edge" pattern the message bus and gRPC clients use, which is what [Rubric §7, Microservices Readiness] looks for (can a module move to its own process without a code change) and part of what [Rubric §12, Performance and Scalability] rewards (the scaled-out deployment gets a shared cache without touching business code).

The shared-store substrate is explicit. AddCommonHybridCache(Action<HybridCacheOptions>?) (DependencyInjection.Caching.cs:195) is required for, and intended for, hosts with a distributed L2; a memory-only host gains nothing, since MemoryCacheService is already in-process (DependencyInjection.Caching.cs:160-163). It refuses to run without one: its first step throws an InvalidOperationException when no shared distributed cache is registered, or only the in-memory MemoryDistributedCache would resolve, naming the Redis connection string and the guarded form (DependencyInjection.Caching.cs:197, DependencyInjection.Caching.cs:309-326), because without a real L2 the shared-store path would store nothing (DependencyInjection.Caching.cs:165-171). It then calls AddHybridCache() (DependencyInjection.Caching.cs:199) and configures HybridCacheOptions through the options pipeline rather than through the AddHybridCache callback (DependencyInjection.Caching.cs:205-219), because the TTL policy comes from the bound CacheSettings and the callback has no service provider to read it from; the framework sets Expiration from DefaultDuration and LocalCacheExpiration from LocalCacheDuration (falling back to HybridCacheService.LocalCacheDefault) at DependencyInjection.Caching.cs:212-216, and the host's own hook runs last so it can override anything (DependencyInjection.Caching.cs:218). The swap of the cache implementation is deliberately RemoveAll<ICacheService>() followed by AddSingleton (DependencyInjection.Caching.cs:221-240) rather than TryAdd, so the call wins whether it runs before or after AddInfrastructure; the source is equally explicit that this also removes a host's own bespoke ICacheService, so calling it is a statement that the two-level cache is the cache (DependencyInjection.Caching.cs:182-185). The factory hands the new service the optional IConnectionMultiplexer that holds the generation tokens, the host's key namespace, the bound settings and the cross-service namespace (DependencyInjection.Caching.cs:224-239). Because the unguarded call throws without Redis, the framework also ships the guarded form, AddCommonHybridCacheWhenRedisConfigured(IConfiguration, string) (DependencyInjection.Caching.cs:261), which calls it only when the redis connection string (the default connectionName) is non-empty (DependencyInjection.Caching.cs:267-270) and otherwise leaves the in-process registration untouched. Service hosts do not make these calls by hand: the composed start-up AddMmcaServiceHost (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs:65) runs AddRedisCaching(), then AddRedisOutputCaching() when the host asks for it, then the guarded hybrid call (ServiceHostBuilderExtensions.cs:91-97), and both deployed applications compose through it (ADC Conference at MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:88, Store Catalog at MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:32). Without Redis the guard declines and the host keeps the in-process substrate, which is the point: an L1 in front of an in-process L2 buys nothing (ADR-077).

The in-process adapter. MemoryCacheService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/MemoryCacheService.cs:38) wraps IMemoryCache and takes the bound CacheSettings (framework defaults when none is passed, MemoryCacheService.cs:74), so an entry written without an expiration gets the same DefaultDuration every other store applies (MemoryCacheService.cs:138). The container does not hand it the host's shared IMemoryCache: CreateOwned builds it over a MemoryCache of its own whose SizeLimit is Cache:MemoryEntryLimit (MemoryCacheService.cs:92-97), every entry is written with a size of one so that limit counts entries (MemoryCacheService.cs:134-140), and the store disposes the instance it owns (MemoryCacheService.cs:100). The shared IMemoryCache stays unlimited because the framework's other writers to it set no entry size and would throw under a limit (MemoryCacheService.cs:24-28). Reads return the stored instance, never a copy: nothing is serialized, so a caller that mutates a cached value changes it for every later reader, and cached values are to be treated as immutable on both stores (MemoryCacheService.cs:31-35). Prefix invalidation uses the same generation-token model as the two-level cache: the constructor builds its own CachePrefixGenerations with no Redis, the empty namespace and the local duration, so the tokens are authoritative in this process (MemoryCacheService.cs:79-83), and every entry is stored under the caller's key plus its generation suffix (MemoryCacheService.cs:199-203). RemoveByPrefixAsync checks the boundary contract and replaces one token (MemoryCacheService.cs:157-161), so every entry under the prefix is a miss from then on. IMemoryCache cannot enumerate its keys, and a generation token needs no key index to stay in agreement with the cache (MemoryCacheService.cs:14-20); the cost is memory, not correctness, since an invalidated entry stays in the cache, unreachable, until its TTL or until the entry limit compacts it away (MemoryCacheService.cs:22-26). The "invalidation is process-local" warning the token engine would log goes to a discarding logger, because for this store it states the design rather than a misconfiguration (MemoryCacheService.cs:76-78). GetAsync is TryGetAsync with the presence flag dropped (MemoryCacheService.cs:103-107), and TryGetAsync matches on the stored object rather than using the generic TryGetValue<T> overload, so a key reused under a different T surfaces as a clean miss instead of an InvalidCastException and presence is real rather than inferred (MemoryCacheService.cs:111-118). GetFromSharedStoreAsync is GetAsync, since this store has no tier other than the process (MemoryCacheService.cs:122-124). GetOrCreateAsync spells the stampede shape out: get, then the key's stripe, then a double-check, then factory and set (MemoryCacheService.cs:168-193), with stripes from a per-instance KeyedSemaphoreStripe (MemoryCacheService.cs:58) and presence taken from TryGetAsync on both checks, so a cached default(T) of a value type counts as a hit (MemoryCacheService.cs:165-166).

One prefix rule, enforced by both stores. CachePrefixContract (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CachePrefixContract.cs:8) is the argument contract of RemoveByPrefixAsync in one internal static class: the boundary character : (CachePrefixContract.cs:11) and EnsureBoundary, which throws ArgumentNullException for null and ArgumentException for a non-empty prefix that does not end with it (CachePrefixContract.cs:17-27). Both adapters call it first, MemoryCacheService at MemoryCacheService.cs:159 and HybridCacheService at HybridCacheService.cs:331. Since both stores keep their tokens per : boundary, a mid-segment prefix is not expressible on either, and the one shared check keeps the rejection identical whichever backend a host runs (ICacheService.cs:91-94). On the write path the caching command decorator treats that exception as a bug in the command rather than a transient fault, logging it at Error and skipping the delayed retry, which would fail identically (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingCommandDecorator.cs:115-122).

Prefix invalidation by generation token. CachePrefixGenerations (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CachePrefixGenerations.cs:70) is how the two-level cache evicts a prefix without walking the keyspace. Every invalidation boundary of a key, the empty root and each prefix ending at a : (A:B:C yields "", A: and A:B:, CachePrefixGenerations.cs:241-260), carries a generation token, and SuffixAsync folds the non-empty tokens in force into the key the entry is stored under (CachePrefixGenerations.cs:150-203, CachePrefixGenerations.cs:265-273), after a | separator (CachePrefixGenerations.cs:80). A key whose boundaries were never invalidated keeps its plain shape (CachePrefixGenerations.cs:142-144). InvalidateAsync (CachePrefixGenerations.cs:218) replaces one token, so every entry written under the old token simply stops being addressed and expires on its own TTL (CachePrefixGenerations.cs:8-14): one Redis write whatever the size of the keyspace. The source records why this is not HybridCache.RemoveByTagAsync: in Microsoft.Extensions.Caching.Hybrid 10.11.0 each process reads a tag's invalidation timestamp once and never refreshes it, so a replica that has already met the tag never learns of a later invalidation (CachePrefixGenerations.cs:17-25); the Redis-tier HybridCacheCrossInstanceInvalidationTests (MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Redis.Tests/HybridCacheCrossInstanceInvalidationTests.cs:22) pins the property this class provides instead. Tokens are 64 random bits, hex encoded (CachePrefixGenerations.cs:277), not INCR counters, so concurrent invalidations need no atomicity (CachePrefixGenerations.cs:27-29). They live under {namespace}hcg:{prefix} (CachePrefixGenerations.cs:77, CachePrefixGenerations.cs:282), a segment disjoint from the cache entries, with no TTL, so Redis holds one short string per distinct invalidated prefix (CachePrefixGenerations.cs:43-45). Each process remembers the tokens it has seen as a RememberedToken (CachePrefixGenerations.cs:418), a private record struct of the token, the tick count it must be refreshed after, a monotonic version stamp and whether this process stored it by invalidating. A remembered token is reused without a read for one local cache duration, then still served while one background read per boundary refreshes it (CachePrefixGenerations.cs:176-184), for up to RetentionMultiplier = 10 local durations, five minutes at the default (CachePrefixGenerations.cs:82-87); concurrent readers of one boundary share a single in-flight read (CachePrefixGenerations.cs:108-109, CachePrefixGenerations.cs:292-298), and long-expired entries are swept once per 1024 inserts (CachePrefixGenerations.cs:93, CachePrefixGenerations.cs:395-402). The invalidating process adopts its new token locally before the Redis write, so it stops serving the prefix even if the write fails (CachePrefixGenerations.cs:235-238), and the version snapshot taken before any read means a read that began before that invalidation can never put the old token back (CachePrefixGenerations.cs:168-170, CachePrefixGenerations.cs:388-393). Another replica therefore sees an invalidation within one local duration plus one refresh round trip (CachePrefixGenerations.cs:37-46). The failure posture is spelled out too: a failed token read never fails the cache call, it answers with the last token this process knew or the empty baseline (CachePrefixGenerations.cs:358-371), and the baseline is deliberate, since the lockout flag, the failure counters and the idempotency records sit under boundaries nobody invalidates, so lockout and rate limits keep working on a cold replica during an outage; the cost, a cold replica addressing pre-invalidation entries of an invalidated prefix during a partial outage, is stated beside it (CachePrefixGenerations.cs:53-68), as is the matching caveat that a lost generation key brings back only the baseline, never an older non-baseline token (CachePrefixGenerations.cs:29-35). Without a multiplexer the tokens live in this process only (CachePrefixGenerations.cs:111-112), which is exact for a single-process host, and the first such invalidation logs one warning naming AddRedisCaching (CachePrefixGenerations.cs:225-232, CachePrefixGenerations.cs:410). That warn-once-versus-silent choice is a small but real [Rubric §13, Observability and Operability] decision: an invalidation that quietly reaches no other replica is exactly the failure mode that hides from dashboards. This is also why Cache:LocalCacheDuration, when set, must be at least one second: it bounds how long a token is reused, so zero would turn every cache call into a Redis read (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheSettings.cs:63-68).

The two-level cache. HybridCacheService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/HybridCacheService.cs:53) puts an in-process L1 in front of the registered distributed L2 and lets the platform's HybridCache supply serialization, L1 promotion and stampede protection. It builds its own CachePrefixGenerations from the multiplexer, the namespace and the local duration (HybridCacheService.cs:163-167). Its structural decision is the disjoint keyspace: every key is written as {prefix}hc:{key} plus any generation suffix (HybridCacheService.cs:59, HybridCacheService.cs:390-399), so an entry can never meet a value another writer put on the same server, a host's own IDistributedCache use or the hcg: generation keys, in a format it cannot parse (HybridCacheService.cs:19-24). RemoveByPrefixAsync checks the boundary contract and replaces one generation token; nothing is scanned or deleted (HybridCacheService.cs:314-333). Reads are fail-soft: a fault is logged, answered as a miss, and the offending entry is dropped best-effort so the next write repopulates it (HybridCacheService.cs:179-198, HybridCacheService.cs:429-439). GetFromSharedStoreAsync bypasses L1 entirely through one options instance that disables the L1 read and the L1 write (SharedStoreReadOptions, HybridCacheService.cs:88-93), because its values are ones whose correctness depends on every replica seeing the same thing; the reasoning is a [Rubric §11, Security] point rather than a performance one. A single-use record (an OAuth exchange code, a password-reset or email-confirmation token, the last accepted second-factor time step) consumed on one replica is therefore a miss on every other replica at once rather than usable a second time for up to the local expiration (HybridCacheService.cs:35-39, HybridCacheService.cs:262-281); it stays fail-soft like GetAsync, and for such a record a miss is a refusal, the safe direction. The same path serves the reads whose correctness depends on seeing a removal at once, the login lockout flag and the soft-deleted-user marker (HybridCacheService.cs:39-41). Counters are not kept in this service at all: they live in the ICounterStore, whose Redis store increments atomically (HybridCacheService.cs:41-42). Its single-use callers are OAuthControllerBase (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:363), PasswordResetTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:133), EmailConfirmationTokenService (.../Auth/EmailConfirmationTokenService.cs:96) and TwoFactorAuthenticator (.../Auth/TwoFactor/TwoFactorAuthenticator.cs:197); the others are LoginProtectionService for the lockout flag and its expiry (.../Auth/LoginProtectionService.cs:85, LoginProtectionService.cs:91) and SoftDeletedUserMiddleware (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/SoftDeletedUserMiddleware.cs:95). That last record is also the one key outside the host's namespace: a CrossServiceCacheKeys key is qualified with the cross-service namespace every service of a deployment shares and carries no generation suffix, so the record Identity writes is the record every other service reads (HybridCacheService.cs:47-50, HybridCacheService.cs:392-395). TryGetAsync is overridden with a real presence check (HybridCacheService.cs:220-245), because inferring presence would report a value-type miss as found and HybridCache has no presence-reporting read: presence is read from whether HybridCache had to call the factory, which on a miss throws a KeyNotFoundException tagged with a private marker (HybridCacheService.cs:62, HybridCacheService.cs:370-375) that the method catches as "not found" (HybridCacheService.cs:235-238). A thrown sentinel rather than a flag the factory sets, because a concurrent read of the key joins the first caller's in-flight lookup and never runs its own factory, while the exception reaches every joined caller (HybridCacheService.cs:209-211). The probe carries its own PresenceProbeOptions (HybridCacheService.cs:102-105), whose flags no other call uses, since HybridCache joins only callers with identical flags and a GetOrCreateAsync in flight on the same key must never be handed that miss (HybridCacheService.cs:214-216); faults stay fail-soft as on GetAsync (HybridCacheService.cs:239-244). GetOrCreateAsync is HybridCache's own implementation, which also deduplicates concurrent callers before they reach L2 while keeping the interface's unconditional caching and per-process stampede guarantees (HybridCacheService.cs:336-363). Replica staleness after an invalidation is bounded by the local expiration, the shorter of the entry's TTL and Cache:LocalCacheDuration (30 seconds by default, HybridCacheService.cs:69, HybridCacheService.cs:408-419), the same window in which another replica picks up a replaced generation token (HybridCacheService.cs:26-32), and the source names that as the accepted cost of the L1 hit rate.

Counters live beside the cache, not in it. Rate limits and brute-force throttles need an increment that cannot undercount, so they go through the ICounterStore port (MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICounterStore.cs:23): a fixed-window IncrementAsync(key, window) (ICounterStore.cs:34), GetAsync (ICounterStore.cs:43) and ResetAsync (ICounterStore.cs:52), giving the ADR-029 counters one entry point. RedisCounterStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/RedisCounterStore.cs:36) keeps one plain Redis string per counter under its own ctr: segment inside the cache namespace (RedisCounterStore.cs:39, RedisCounterStore.cs:165), disjoint from the cache entries (hc:), the generation tokens (hcg:), the locks (lock:) and the rate-limit windows (rl:), and never an IDistributedCache hash, which is what lets INCRBY work on it (RedisCounterStore.cs:17-21). The increment and its TTL run as one Lua script, the same RedisCounterScript the distributed rate limiter runs, so the increment is atomic across replicas and only the creating increment sets the expiry (RedisCounterStore.cs:9-13, RedisCounterStore.cs:90-94); the window is rounded up to whole seconds so a sub-second window still expires (RedisCounterStore.cs:80-81). A Redis fault never fails the caller: it is logged at Warning at most once a minute across the process (RedisCounterStore.cs:167-177, RedisCounterStore.cs:179), and instead of answering zero, which would switch every limit off for the outage, the call is served by a process-local fallback, so each replica keeps enforcing its limits on what it saw itself until Redis answers again (RedisCounterStore.cs:24-28, RedisCounterStore.cs:96-100). A fault also opens the connection's RedisOutageCircuit (RedisCounterStore.cs:70, RedisCounterStore.cs:171): for its window every call goes straight to the fallback instead of waiting out the client timeout again, and one call probes Redis once the window has passed (RedisCounterStore.cs:30-34, RedisCounterStore.cs:83-86). Only the caller's own cancellation propagates; a cancellation the caller did not request counts as a fault (RedisCounterStore.cs:152-160), and a reset clears the fallback copy first, so a count taken during an outage cannot outlive it (RedisCounterStore.cs:133-134). That fallback is InMemoryCounterStore (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/InMemoryCounterStore.cs:24), which is also the whole store of a host with no Redis (InMemoryCounterStore.cs:6-9). It is atomic per key because every change is one AddOrUpdate compare-and-swap of an immutable CounterWindow (InMemoryCounterStore.cs:68-74), a private record of the count and the instant the window ends, that end fixed by the increment that opened the window and never moved by a later one (InMemoryCounterStore.cs:98-101, InMemoryCounterStore.cs:12-15). Ended windows read as zero (InMemoryCounterStore.cs:46), are replaced when their key is next touched, and are swept once per SweepInterval = 1024 increments (InMemoryCounterStore.cs:27, InMemoryCounterStore.cs:76-79), removing only the record that was seen so a window reopened in between survives (InMemoryCounterStore.cs:92-93); keys that are never touched again, one per client IP or address, therefore cannot grow the table without bound (InMemoryCounterStore.cs:18-21). The degrade-to-local posture is the [Rubric §29, Resilience] answer for a security control: an outage weakens the limit to per-replica, it never removes it.

The key namespace and the TTL policy. CacheKeyPrefixOptions (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheKeyPrefix.cs:30) binds the Cache configuration section (CacheKeyPrefix.cs:33) and carries two settings. KeyPrefix still defaults to empty (CacheKeyPrefix.cs:45), but empty does not mean "no prefix": it means take the framework's per-application default, and a host sets the value explicitly only to pin a keyspace two hosts of the same application must share (CacheKeyPrefix.cs:35-40). The reason is recorded on the property itself: it used to default to no prefix at all, so two applications sharing one Redis shared one keyspace for both cache entries and distributed locks, silently (CacheKeyPrefix.cs:41-44). CrossServiceKeyPrefix (CacheKeyPrefix.cs:55) names the keyspace of the cross-service records, defaulting to the token audience (Jwt:Audience), which every service accepting the same tokens shares and two applications do not (CacheKeyPrefix.cs:47-54). Both are concatenated verbatim, so a value that is set must end in : (adc would yield keys like adchc:... and a prefix invalidation could never name the boundary): CacheKeyPrefixOptionsValidator (CacheKeyPrefix.cs:63), an internal IValidateOptions<CacheKeyPrefixOptions>, checks Cache:KeyPrefix and Cache:CrossServiceKeyPrefix and fails start-up with one message per offending key that names the fix, while an empty value passes and takes the default (CacheKeyPrefix.cs:58-62, CacheKeyPrefix.cs:66-86). CacheKeyNamespace (CacheKeyPrefix.cs:90) is the internal applier. It keeps a None instance for the untouched case (CacheKeyPrefix.cs:96) and an options-taking From overload that tolerates an unregistered section (CacheKeyPrefix.cs:102-106), but the composition root calls the container-taking overload (CacheKeyPrefix.cs:116-131), which returns the configured prefix when a host set one (CacheKeyPrefix.cs:120-124) and otherwise builds {application namespace}: from ApplicationNamespace.Resolve (CacheKeyPrefix.cs:126-130). That resolver reads Application:Namespace, falls back to the host's application name, and falls back again to the literal app (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Configuration/ApplicationNamespace.cs:60-74, keys at ApplicationNamespace.cs:38 and ApplicationNamespace.cs:41), so the resolved prefix is never empty and isolation is automatic rather than opt-in. CrossServiceFrom resolves the second namespace the same way: configured value, then the sanitized audience, then this host's own namespace (CacheKeyPrefix.cs:147-161). Qualify (CacheKeyPrefix.cs:164-165) prepends a prefix. The same namespace instance is handed to the Redis distributed lock registered beside the cache (DependencyInjection.Caching.cs:122-123) and to the Redis counter store (DependencyInjection.Caching.cs:142), and becomes the output-cache store's InstanceName (DependencyInjection.Caching.cs:75-82), so one application's cache entries, generation keys, lock keys, counters and output-cache entries carry one prefix. The two-level cache applies it inside the adapter rather than through RedisCacheOptions.InstanceName; the rationale in the source (CacheKeyPrefix.cs:16-24) is precise, since InstanceName is prepended by IDistributedCache below this abstraction, where the generation keys written directly to Redis would not carry it, so two applications on one server would share invalidation tokens while keeping separate entries. MemoryCacheService ignores prefixes entirely because a per-process keyspace is private by construction (CacheKeyPrefix.cs:25-28; it passes CacheKeyNamespace.None to its token engine, MemoryCacheService.cs:81). TTL policy is centralized the same way: CacheOptions (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheOptions.cs:11) is a static class with one member, a deliberately short 30-second DefaultDuration (CacheOptions.cs:17) as a bare TimeSpan, the one value every store defaults to rather than a second hard-coded 30 seconds (CacheOptions.cs:13-16). It is the hard-coded framework default and the single source of truth for the configurable path as well, and the place to change the policy per host is the Cache section (CacheOptions.cs:3-10): CacheSettings defaults DefaultDuration to CacheOptions.DefaultDuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheSettings.cs:41), so a host that configures nothing behaves exactly as it did before that section existed, and a configured value must be at least one second, validated at start-up, because a zero or negative TTL would make every write without its own expiration throw (CacheSettings.cs:33-40). The same object carries MemoryEntryLimit, 100,000 entries by default (CacheSettings.cs:27-28, CacheSettings.cs:54-55), which bounds the in-process store's own cache instance so a high-cardinality key set, or the entries a prefix invalidation leaves unreachable until their TTL, cannot grow the process without bound; the two-level cache ignores it, since the HybridCache library bounds its L1 (CacheSettings.cs:43-53). The short default is a staleness guard: caching is opt-in and conservative, and a read earns a longer life only by asking for one. One policy object with many call sites is the [Rubric §12, Performance & Scalability] habit this framework applies everywhere.

One hook for every Redis connection. IRedisConfigurationOptionsConfigurator (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/IRedisConfigurationOptionsConfigurator.cs:30) has a single member, Configure(ConfigurationOptions) (IRedisConfigurationOptionsConfigurator.cs:34), that adjusts the StackExchange.Redis options of a connection before it connects: a token credential, a client certificate, a timeout (IRedisConfigurationOptionsConfigurator.cs:5-9). It reaches every Redis connection the framework opens, the Redis client and the distributed cache over it, the output-cache store, the SignalR backplane and the PING health check's own connection, each running every registered configurator once on its own options instance parsed from the connection string (IRedisConfigurationOptionsConfigurator.cs:10-15). It runs synchronously, may run more than once per process, and throwing from it fails that connection, which is the place to reject a connection string it cannot serve (IRedisConfigurationOptionsConfigurator.cs:25-29). With none registered every connection is made from the connection string exactly as before (IRedisConfigurationOptionsConfigurator.cs:20-23). Registration is AddRedisConfigurationOptionsConfigurator (DependencyInjection.Caching.cs:288), idempotent per configurator type (DependencyInjection.Caching.cs:292), and it also adds the bridge RedisConfigurationOptionsPostConfigure (DependencyInjection.Caching.cs:294-296; MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/RedisConfigurationOptionsPostConfigure.cs:15), an IPostConfigureOptions<ConfigurationOptions> that runs every configurator on each options instance the options system builds, for every name (RedisConfigurationOptionsPostConfigure.cs:21-29). The bridge is what lets MMCA.Common.Aspire, which may not reference this package, reach the configurators: both sides name only a StackExchange.Redis type and the options abstractions (RedisConfigurationOptionsPostConfigure.cs:6-13). The shipped adapter is the Azure one, which registers a configurator from its own call (MMCA.Common/Source/Hosting/MMCA.Common.Azure/AzureServiceCollectionExtensions.cs:254), keeping the vendor credential out of the core packages as ADR-134 requires.

How it fires at runtime. The query-cache decorators are a host opt-in before they are a use-case opt-in: AddQueryCaching() (MMCA.Common/Source/Core/MMCA.Common.Application/DependencyInjection.cs:223) records a flag the decorator registration reads, and without it the caching pair is left out of the pipeline entirely, so the two marker interfaces below are inert and no ICacheService call is made (DependencyInjection.cs:162). Opted in, the pair sits in the CQRS decorator pipeline (ViewAs then FeatureGate then Authorization then Logging then Caching then Validating then Timeout then Transactional then handler for commands, and the same chain without ViewAs and Transactional for queries; the order is documented at DependencyInjection.cs:90-114, Authorization sits outside Caching so a denied request neither reads nor populates the cache (DependencyInjection.cs:123-125), and the two caching decorators are added conditionally at DependencyInjection.cs:174 and DependencyInjection.cs:186, taught in Group 5). On the read path, CachingQueryDecorator<TQuery, TResult> tests the query for IQueryCacheable and passes straight through when it is absent (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:64-65). When present it scopes the key to the target user for a caller-scoped query through UserCacheKey and then to the resolved tenant through TenantCacheKey (CachingQueryDecorator.cs:58-59, so two tenants or two users can never share an entry), takes a lock-free fast path on a hit (CachingQueryDecorator.cs:74-79), and on a miss acquires a per-key stripe from the process-wide QueryCacheKeyLocks (CachingQueryDecorator.cs:185), re-checks (CachingQueryDecorator.cs:100-105), records the miss on CqrsMetrics exactly once (CachingQueryDecorator.cs:113), and only then runs the inner handler. That stripe wait is itself bounded by Cache:PopulateLockTimeout (CachingQueryDecorator.cs:84-85, five seconds by default, the QueryCachePipelineSettings.DefaultPopulateLockTimeout that CacheSettings also defaults to at CacheSettings.cs:84, with zero or a negative value meaning no bound, CacheSettings.cs:81-82): when the budget elapses the waiter logs, counts a miss, and runs the query itself uncached rather than queueing behind a pathologically slow populate (CachingQueryDecorator.cs:87-96, CachingQueryDecorator.cs:179-198). The lock table is a fixed-width KeyedSemaphoreStripe (MMCA.Common/Source/Core/MMCA.Common.Shared/Concurrency/KeyedSemaphoreStripe.cs:22, 256 stripes by default at KeyedSemaphoreStripe.cs:25), which bounds memory no matter how many parameterized cache keys the process sees. Every cache call is fail-open: a read fault is logged and treated as a miss (CachingQueryDecorator.cs:217-239) and a populate fault returns the result uncached (CachingQueryDecorator.cs:120-131), so a cache outage degrades reads instead of turning cacheable queries into 500s, which is the [Rubric §29, Resilience] posture in miniature. Results are stored only when they are not a failed Result (CachingQueryDecorator.cs:118). On the write path, CachingCommandDecorator<TCommand, TResult> runs the inner handler first and then, only if the command implements ICacheInvalidating, the prefix is non-blank (a blank prefix is the opt-out, and the guard is load-bearing since an empty prefix would evict the whole cache) and the result is not a failure, invalidates the tenant-scoped prefix with CancellationToken.None (.../Decorators/CachingCommandDecorator.cs:80-85, CachingCommandDecorator.cs:94-114); a prefix that breaks the boundary contract is logged at Error and not retried (CachingCommandDecorator.cs:115-122), and any other fault is logged without failing the committed command (CachingCommandDecorator.cs:123-128). A handler that throws still triggers the eviction before the exception is rethrown unchanged, because the write may already have committed (a post-save hook that threw on a command that is not transactional), and after a rollback the eviction costs only a cache miss (CachingCommandDecorator.cs:71-78). It then schedules a second invalidation five seconds later (CachingCommandDecorator.cs:55, CachingCommandDecorator.cs:136, CachingCommandDecorator.cs:143-156) to catch a read that began before the commit and repopulated the entry with pre-write state. Because the Caching decorator sits outside the Transactional one, eviction runs after the transaction committed: against persisted state, never in-flight state, and never for a command that returned a failed result.

Two tiers, not one. These sixteen types are only Tier 1 of the caching story that ADR-026 records. Tier 2 is a separate HTTP output-cache edge: MMCA.Common.API always runs app.UseOutputCache() as a named step in the shared middleware pipeline (MMCA.Common/Source/Presentation/MMCA.Common.API/Startup/Pipeline/MiddlewarePipelineBuilder.cs:131-133, see MiddlewarePipelineBuilder) but ships no policies, so each host opts in with its own output-cache configuration. The read-heavy public services declare real cacheable policies through OutputCacheOptionsExtensions and its AddPublicEndpointPolicy (MMCA.Common/Source/Presentation/MMCA.Common.API/Caching/OutputCacheOptionsExtensions.cs:20), backed by PublicEndpointOutputCachePolicy (.../Caching/PublicEndpointOutputCachePolicy.cs:35), which caches GET and HEAD regardless of an Authorization header (PublicEndpointOutputCachePolicy.cs:110, ADR-040), and evict it across replicas through the OutputCacheEvictionRequested integration event and its OutputCacheEvictionHandler. Both adopters back that edge with Redis by setting UseRedisOutputCaching (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/Program.cs:135; MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/Program.cs:53), which the composed host turns into AddRedisOutputCaching() (ServiceHostBuilderExtensions.cs:92-95), so the two tiers ride the same Redis instance from opposite ends: Tier 1 through HybridCache, Tier 2 through the output-cache store. There is no third tier on the client: ADR-026 records that the optional client-side read cache was removed in MMCA.Common v1.301.0, so a UI service read in EntityServiceBase<TEntityDTO, TIdentifierType> is a plain GET through the retry pipeline, SendGetAsync<T> (MMCA.Common/Source/Presentation/MMCA.Common.UI/Services/Api/EntityServiceBase.cs:248), and any client-side memoization is an application decision that belongs to Group 15, Common UI Framework. Tier 2 belongs to Group 12, API Hosting; both are named here only so you do not confuse them with Tier 1 when you meet [OutputCache] on a controller.

Adoption reality, so you read the code with the right expectations. The shared substrate is live in the deployed services: the composed host registers the Aspire Redis integration through RedisCachingExtensions, whose AddRedisCaching() brings the IConnectionMultiplexer the generation tokens, the locks and the counters live on along with the distributed cache, and then the hybrid substrate through the framework's connection-string guard (ServiceHostBuilderExtensions.cs:91-97). The query-cache decorators are not: no ADC source calls AddQueryCaching(), so the caching pair is not in ADC's pipeline. No ADC type declares ICacheInvalidating itself; ADC commands carry it only through the framework's generic CRUD commands, which implement it with an aggregate-scoped CachePrefix default (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Crud/UpdateEntityCommand.cs:52, the prefix at :65), for example MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Speakers/UseCases/Update/UpdateSpeakerCommand.cs:25-31 deriving from it, and without the opt-in those prefixes are inert markers. Read-side adoption is absent as well: no ADC query implements IQueryCacheable. Its one hot public read, GetNowNextQuery, opts out on purpose and relies on a Redis-backed output-cache policy instead (MMCA.ADC/Source/Modules/Conference/MMCA.ADC.Conference.Application/Sessions/UseCases/NowNext/GetNowNextQuery.cs:10-12). The substrate's production consumers are therefore not decorators at all: LoginProtectionService takes both ports, the ICounterStore for its brute-force and rate-limit counters and ICacheService for the lockout flag and its expiry (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:16-17, LoginProtectionService.cs:43-44), incrementing at LoginProtectionService.cs:155 and LoginProtectionService.cs:260 and reading the flag back through GetFromSharedStoreAsync (LoginProtectionService.cs:104, LoginProtectionService.cs:110), covered in Group 8, Authentication and Authorization; the password-reset and email-confirmation token services count requests through the counter store (PasswordResetTokenService.cs:69, EmailConfirmationTokenService.cs:59) and redeem their single-use records through GetFromSharedStoreAsync as described above; and IdempotencyFilter resolves the cache per request to store and replay responses (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:145). The key namespace is live in both deployed applications, and the two pin it differently. ADC's services share one keyspace: Cache:KeyPrefix is adc: alongside Application:Namespace adc, pinned to exactly what the namespace resolves to so a host rename cannot move it (MMCA.ADC/Source/Services/MMCA.ADC.Conference.Service/appsettings.json:53-62, rationale at :45-52 and :56-59). Store goes the other way: its services share Application:Namespace store for the broker topics but keep separate Redis keyspaces, so Catalog pins store-catalog: (MMCA.Store/Source/Services/MMCA.Store.Catalog.Service/appsettings.json:39-44, rationale at :29-38), a value the per-application default would not have produced. CacheKeyNamespace.None is therefore only the constructor fallback the adapters use when no namespace is passed, not the deployed state. Two honest caveats round this out. The stampede lock is per process (CachingQueryDecorator.cs:255-261): across replicas over a shared Redis you get at most one handler execution per replica, not one cluster-wide, which is deliberate (a distributed lock is not attempted) and harmless because the duplicated writes carry equal content. And GetOrCreateAsync has no first-party caller outside tests today: it is a published extension point that both adapters implement.

What the cache is not. This is a request-result read-through cache for query handlers plus a single-use record store and an idempotency record store, not a counter, not a session store and not a write-behind buffer; counting is the counter store's job and cross-source consistency in this codebase is the outbox's job (ADR-003, ADR-006), not the cache's. The short default TTL and the two failure-skipping rules (never cache a failed result, never invalidate on a failed command) mean the layer errs toward correctness over hit rate, which is the right default for an opt-in cache bolted onto a database-per-service system. Everything in the bound Cache section is fail-open by design (CacheSettings.cs:13-18): no value there can turn a cache outage or a slow populate into an error. The unit tests for these types, including the Redis-backed HybridCacheServiceRedisTests and HybridCacheCrossInstanceInvalidationTests, are catalogued in Group 27, Testing and Quality Infrastructure.

CacheKeyPrefixOptions

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheKeyPrefix.cs:30 · Level 0 · class (public sealed, options)

  • What it is: the bound options object for two settings in the Cache section. Cache:KeyPrefix is the namespace prepended to every cache key written through HybridCacheService, to the Redis distributed lock and to the Redis output-cache store; Cache:CrossServiceKeyPrefix is the namespace of the few keys one service writes and another reads. It exists so several applications sharing one Redis instance cannot read each other's entries by accidentally choosing the same key. Leaving either unset does not mean "no prefix": the empty value is a signal to fall back to a framework default (CacheKeyPrefix.cs:35-45, :47-55).
  • Depends on: nothing first-party for the options object itself; it is a plain POCO bound by Microsoft.Extensions.Options / IConfiguration (BCL). Its values are turned into behavior by CacheKeyNamespace, which is what the cache adapters actually hold, and which falls back to ApplicationNamespace when KeyPrefix is unset (CacheKeyPrefix.cs:126-130) and to the token audience when CrossServiceKeyPrefix is unset (CacheKeyPrefix.cs:157-160).
  • Concept introduced, keyspace isolation for a shared cache, on by default. [Rubric §7, Microservices Readiness] assesses whether a module keeps working, and keeps its data to itself, once it is lifted into its own process next to its siblings. A cache instance is exactly the kind of shared infrastructure that survives extraction unchanged, so the isolation a private process gave you for free has to be re-created explicitly. Set KeyPrefix explicitly to pin a shared keyspace across hosts of the same application, or leave it unset and let ApplicationNamespace derive a distinct keyspace per application automatically. [Rubric §11, Security] assesses whether the system prevents data reaching a caller who should not see it; SEC-Common-53 (CacheKeyPrefix.cs:41-44) records that this option used to default to no prefix at all, so two applications sharing one Redis silently shared one keyspace for both cache entries and distributed locks. Isolation is now automatic rather than opt-in. The second setting handles the opposite need: a record such as the soft-deleted-user marker (CrossServiceCacheKeys) must be addressed identically by every service of one deployment even though each service has its own KeyPrefix.
  • Walkthrough
    • SectionName (CacheKeyPrefix.cs:33), const string = "Cache". The same section carries the TTL policy (CacheSettings) and the query pipeline's populate-lock knob (QueryCachePipelineSettings), all three bound side by side in AddCaching (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:43-67).
    • KeyPrefix (CacheKeyPrefix.cs:45, doc at CacheKeyPrefix.cs:35-44), string with { get; init; } and a default of string.Empty. An empty value tells CacheKeyNamespace.From(IServiceProvider) to resolve the per-application default ("{application namespace}:"). Setting it explicitly is for the narrower case, pinning a keyspace two hosts of the same application must share.
    • CrossServiceKeyPrefix (CacheKeyPrefix.cs:55, doc at CacheKeyPrefix.cs:47-54), string, default string.Empty. Empty means "use the token audience (Jwt:Audience)", which every service accepting the same tokens shares and two applications do not, falling back to the host's own namespace when no audience is configured. The doc is explicit that a value set here must be the SAME on every service of the deployment (CacheKeyPrefix.cs:52-53).
  • Why it's built this way: the class remarks (CacheKeyPrefix.cs:16-28) record why this type exists rather than Redis's built-in RedisCacheOptions.InstanceName: InstanceName is prepended by IDistributedCache below this framework's abstraction, where the cache adapter cannot see it, so applying the prefix inside the adapter keeps get, set, remove and prefix invalidation working from one key shape. ADR-026 records the same reasoning (026-caching-strategy.md:420-421). The output-cache store is the one place InstanceName is safe, because that store prefixes its value and tag keys itself; AddCaching therefore post-configures RedisOutputCacheOptions.InstanceName from the same namespace unless a host set one (DependencyInjection.Caching.cs:69-82).
  • Where it's used: bound in AddCaching() (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:47-49) via services.AddOptions<CacheKeyPrefixOptions>().Bind(configuration.GetSection(CacheKeyPrefixOptions.SectionName)).ValidateOnStart(), with CacheKeyPrefixOptionsValidator registered beside it (DependencyInjection.Caching.cs:50-51), and only when a non-null IConfiguration was passed (DependencyInjection.Caching.cs:43). AddInfrastructure always passes one (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.cs:147), so a host composing through the normal entry point gets the binding; a test calling the parameterless AddCaching() overload does not. The bound options are read through CacheKeyNamespace: From(IServiceProvider) at the output-cache post-configure (DependencyInjection.Caching.cs:80), the Redis lock factory (DependencyInjection.Caching.cs:122) and the hybrid cache factory (DependencyInjection.Caching.cs:229), and CrossServiceFrom once, for the hybrid cache's cross-service namespace (DependencyInjection.Caching.cs:239).
  • Caveats / not-in-source: MemoryCacheService never sees either prefix, because a per-process keyspace is private by construction (CacheKeyPrefix.cs:25-28, DependencyInjection.Caching.cs:100-104). Because the empty default resolves through ApplicationNamespace, every host that never sets Cache:KeyPrefix still gets a non-empty, per-application prefix at runtime.

CacheOptions

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheOptions.cs:11 · Level 0 · class (public static)

  • What it is: the framework's hard-coded TTL default in one place: a single TimeSpan property, so no store and no caller re-types the number (CacheOptions.cs:3-5).
  • Depends on: nothing first-party and nothing beyond the BCL TimeSpan, which is what puts it at Level 0. It is the seed value for CacheSettings.DefaultDuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheSettings.cs:41), and it is indirectly fed by the per-query IQueryCacheable CacheDuration, which arrives as the expiration argument when a cacheable query's result is stored.
  • Concept introduced, TTL as the freshness dial. [Rubric §12, Performance & Scalability] assesses whether the system bounds staleness and avoids unbounded growth. The deliberately short 30-second default (CacheOptions.cs:17) is the conservative knob: a cached read is served for at most 30 seconds before falling through to the source, so a query that never declares its own duration cannot serve dangerously stale data. Callers that can tolerate more staleness widen the window per query. The same category also asks whether concerns like caching live in one place instead of being re-decided per handler; TTL policy here is one property in one file rather than a TimeSpan.FromSeconds(30) scattered through call sites.
  • Walkthrough: one member.
    • DefaultDuration (CacheOptions.cs:17), a static TimeSpan get-only property = TimeSpan.FromSeconds(30). Its doc (CacheOptions.cs:13-16) states the contract: it is the TTL applied when a caller passes no expiration, and every store defaults to this one value rather than a second hard-coded 30 seconds. A null expiration on ICacheService.SetAsync therefore reads as "use the 30s default" (by way of CacheSettings, below).
  • Why it's built this way: a static class (no instance, no shared mutable state) makes the default a single, allocation-cheap decision point. The stores apply it as absolute expiration (AbsoluteExpirationRelativeToNow at MemoryCacheService.cs:138, Expiration on the HybridCacheEntryOptions projection at DependencyInjection.Caching.cs:214), so an entry's lifetime is bounded no matter how often it is read, which is the safer default for read-through query caching: a hot key cannot keep itself alive indefinitely on stale data. The class remarks (CacheOptions.cs:6-10) name the split: this class is the source of truth for the value, while per-host tuning goes through the bindable Cache section (CacheSettings), which defaults to what this class exposes so the configured and hard-coded paths cannot drift. ADR-026 records the short default as the backstop behind best-effort invalidation (026-caching-strategy.md:42).
  • Where it's used: DefaultDuration seeds CacheSettings.DefaultDuration (CacheSettings.cs:41), which is what both shipped stores actually read at runtime (HybridCacheService at HybridCacheService.cs:410, MemoryCacheService at MemoryCacheService.cs:138, and the two-level projection at DependencyInjection.Caching.cs:214). Unit-tested by CacheOptionsTests, and asserted as the default by CacheSettingsTests.cs and HybridCacheServiceTests.cs.

CachePrefixContract

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CachePrefixContract.cs:8 · Level 0 · class (internal static)

  • What it is: the argument contract of ICacheService.RemoveByPrefixAsync as one guard method: a prefix is either empty (every entry) or ends at a : boundary (CachePrefixContract.cs:3-7).
  • Depends on: BCL only (ArgumentNullException, ArgumentException).
  • Concept introduced, one contract enforced identically by every backend. [Rubric §15, Best Practices & Code Quality] assesses whether behavior is predictable rather than incidental. The two-level store can only invalidate at : boundaries (see CachePrefixGenerations); the in-process store could honor any prefix. Checking the same rule in both means a prefix that only one store could serve fails in a unit test against the memory cache rather than first in production on the two-level cache (MemoryCacheService.cs:152-159).
  • Walkthrough
    • Boundary (CachePrefixContract.cs:11), internal const char = ':'.
    • EnsureBoundary(string prefix) (CachePrefixContract.cs:17-27): null-checks the prefix (:19), then throws ArgumentException when it is non-empty and its last character is not Boundary (:21-26), with a message giving 'MMCA.Sample.Event:' as the expected shape.
  • Why it's built this way: the interface documents the rule (ICacheService.cs:81-101), but a documented rule is only uniform if one piece of code enforces it; a shared internal static guard keeps the two stores from drifting.
  • Where it's used: the first statement of RemoveByPrefixAsync in HybridCacheService (HybridCacheService.cs:331) and MemoryCacheService (MemoryCacheService.cs:159).

CounterWindow

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/InMemoryCounterStore.cs:101 · Level 0 · record (private sealed, nested in InMemoryCounterStore)

  • What it is: the immutable value InMemoryCounterStore holds per counter key: the increments taken in the current window and the instant that window ends (InMemoryCounterStore.cs:101, parameter docs at :98-100).
  • Depends on: BCL only (long, DateTimeOffset), which is what puts it at Level 0. It is nested and private, so nothing outside its owner can name it.
  • Concept introduced, an immutable record as the unit of compare-and-swap. [Rubric §12, Performance & Scalability] assesses whether hot paths stay cheap under concurrency. Because a window is replaced rather than mutated, ConcurrentDictionary.AddOrUpdate swaps one record for the next atomically, so two concurrent increments never overwrite each other and no lock is taken (InMemoryCounterStore.cs:12-15, :68-74).
  • Walkthrough: two positional members. Count is the increments counted in this window; EndsAt is fixed by the increment that opened the window and never moved by a later one (:99-100). An increment inside the window yields current with { Count = current.Count + 1 }, leaving EndsAt untouched; an increment at or after EndsAt starts a fresh new CounterWindow(1, state.Now + state.Window) (InMemoryCounterStore.cs:70-73).
  • Why it's built this way: carrying the end instant inside the value lets a read decide expiry on its own (now < current.EndsAt, InMemoryCounterStore.cs:46) and lets the sweep remove exactly the record it saw, through the KeyValuePair overload of TryRemove, so a window reopened in between survives (InMemoryCounterStore.cs:92-93). A record gives the value equality that overload compares with.
  • Where it's used: only inside InMemoryCounterStore, as the value type of _counters (InMemoryCounterStore.cs:30).
  • Caveats / not-in-source: the window is fixed, not sliding: a burst that straddles a window end can count up to twice the limit across the two windows, the usual fixed-window trade.

ICacheService

MMCA.Common.Application · MMCA.Common.Application.Interfaces · MMCA.Common/Source/Core/MMCA.Common.Application/Interfaces/ICacheService.cs:9 · Level 0 · interface

  • What it is: the Application layer's cache port. Get by key, look a key up and report presence separately from the value, read straight from the shared backing store, set with an optional TTL, remove by exact key, remove every key under a :-bounded prefix, and get-or-create with stampede protection. It hides whether the backing store is an in-process IMemoryCache or a two-level HybridCache over Redis. Counters are deliberately not here: they live in ICounterStore, because a cache entry written through a get and a set cannot be incremented atomically (ICacheService.cs:3-8).
  • Depends on: BCL types at the signature level only (Task, CancellationToken, TimeSpan?, Func<CancellationToken, Task<T>>, value tuples), which is what puts it at Level 0: the file opens with its namespace and no using directive (ICacheService.cs:1). Implemented by MemoryCacheService and HybridCacheService.
  • Concept introduced, dependency inversion for infrastructure. [Rubric §3, Clean Architecture] assesses whether business code depends on abstractions while concrete technology sits at the edges. The Application layer defines this contract; the Infrastructure layer implements it. Handlers, decorators and the auth services never see StackExchange.Redis or Microsoft.Extensions.Caching; they program against this interface and the container decides which adapter they get. Second concept, a contract with no defaults. [Rubric §15, Best Practices & Code Quality] assesses whether a contract states what every implementer must get right. Every member here is abstract. Presence, the shared-store read and get-or-create are each a store-specific question, and the remarks name the trap a generic answer would fall into: inferring presence from a non-null GetAsync result would report a value-type miss as found (ICacheService.cs:28-31). So each shipped store answers all seven members itself. [Rubric §12, Performance & Scalability]: RemoveByPrefixAsync (ICacheService.cs:102) is the member that makes scoped invalidation possible, so one mutation invalidates a whole family of cached query results without enumerating individual keys.
  • Walkthrough: members in declaration order.
    • Task<T?> GetAsync<T>(string key, CancellationToken) (ICacheService.cs:16), returns default / null on a miss.
    • Task<(bool Found, T? Value)> TryGetAsync<T>(string key, CancellationToken) (ICacheService.cs:32). It exists for a value-type T, where GetAsync answers a miss with default(T) (0, false, Guid.Empty) that cannot be told apart from a cached default(T) (ICacheService.cs:18-22); every implementation must report real presence (:28-31).
    • Task<T?> GetFromSharedStoreAsync<T>(string key, CancellationToken) (ICacheService.cs:59). It reads from the shared backing store, bypassing any process-local copy, and is meant for values whose change on one replica must be visible to every other replica at once: single-use records (an OAuth exchange code, a password-reset or email-confirmation token, a second-factor time step) and flags that another replica can clear or set (the login lockout flag, the soft-deleted-user marker) (ICacheService.cs:34-40). The remarks give the usage rule: read a single-use record through this member, then remove it; read a cross-replica flag through it so a set or clear on one replica takes effect everywhere at once; everything else, a value read many times such as a query result or a replay cache, stays on GetAsync and loses only the local hit rate by coming here (ICacheService.cs:47-52). A store with no process-local tier answers it exactly as GetAsync; HybridCacheService reads past its tier (ICacheService.cs:55-56).
    • Task SetAsync<T>(string key, T value, TimeSpan? expiration = null, CancellationToken) (ICacheService.cs:68-72). A null expiration means "use the implementation's default TTL", resolved from CacheSettings on both shipped stores (whose own default is CacheOptions.DefaultDuration).
    • Task RemoveAsync(string key, CancellationToken) (ICacheService.cs:78), single-key eviction.
    • Task RemoveByPrefixAsync(string prefix, CancellationToken) (ICacheService.cs:102), bulk invalidation of every key starting with prefix. The prefix must end at a : boundary (for example "MMCA.Sample.Event:", the shape every ICacheInvalidating.CachePrefix takes) or be empty to remove every entry; a prefix that stops mid-segment is rejected with ArgumentException (ICacheService.cs:81-86, :101). The remarks give the reason: the shipped stores each keep one generation token per : boundary and fold the tokens into every stored key, so invalidating a prefix is one write that a mid-segment prefix could not express, and every shipped store enforces the rule (through CachePrefixContract) so behavior does not depend on the backend (ICacheService.cs:91-94). Callers that must not clear the whole cache guard against an empty prefix themselves (ICacheService.cs:97-98). This is what CachingCommandDecorator<TCommand, TResult> invokes after a successful mutation.
    • Task<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, Task<T>> factory, TimeSpan? expiration = null, CancellationToken) (ICacheService.cs:130-134): return the cached value, or run the factory and cache its result, with concurrent misses on one key running the factory once per process (ICacheService.cs:104-109). That is the same read-through-with-stampede-protection shape CachingQueryDecorator<TQuery, TResult> applies to cacheable queries, made available to any caller. MemoryCacheService implements it as get, per-key stripe, double-check, factory, set; HybridCacheService hands it to HybridCache's own primitive.
  • Why it's built this way: keeping the port in MMCA.Common.Application rather than Infrastructure is what lets the CQRS decorators, which also live in Application, depend on caching without dragging a Redis reference into the business layers. The optional TimeSpan? expiration lets callers override the global TTL without a second overload. GetFromSharedStoreAsync makes the single-use-record rule a named member rather than a convention, so a caller states "this read must not be answered from a replica's own memory" at the call site. Moving counters out to ICounterStore keeps this contract to what a cache can do honestly. Note the boundary the GetOrCreateAsync remarks draw (ICacheService.cs:118-123): caching is unconditional there, so a failed Result would be cached, which is exactly why the caching decorators do NOT route through this member and keep their own read/execute/write sequence.
  • Where it's used: both caching decorators take ICacheService by constructor injection (MMCA.Common/Source/Core/MMCA.Common.Application/UseCases/Decorators/CachingQueryDecorator.cs:45, .../CachingCommandDecorator.cs:35). Outside the pipeline, LoginProtectionService takes it (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:43) to read the lockout flag and the lockout end through GetFromSharedStoreAsync (LoginProtectionService.cs:104, :91), while its counters go through ICounterStore (:136, :233); PasswordResetTokenService, EmailConfirmationTokenService and SignInLinkTokenService follow the same split, reading the token entry through GetFromSharedStoreAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/PasswordResetTokenService.cs:133, .../EmailConfirmationTokenService.cs:96, .../SignInLinks/SignInLinkTokenService.cs:105) and counting requests in ICounterStore; TwoFactorAuthenticator reads the last accepted time step through GetFromSharedStoreAsync (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/TwoFactor/TwoFactorAuthenticator.cs:197); PasskeyChallenges redeems a challenge the same way (MMCA.Common/Source/Core/MMCA.Common.Application/Auth/Passkeys/PasskeyChallenges.cs:74); SoftDeletedUserMiddleware reads the soft-deleted marker through it (MMCA.Common/Source/Presentation/MMCA.Common.API/Middleware/SoftDeletedUserMiddleware.cs:95); IdempotencyFilter passes it to its replay helpers (MMCA.Common/Source/Presentation/MMCA.Common.API/Idempotency/IdempotencyFilter.cs:221); and OAuthControllerBase takes it as a constructor dependency (MMCA.Common/Source/Presentation/MMCA.Common.API/Controllers/OAuthControllerBase.cs:54) and redeems the exchange code through GetFromSharedStoreAsync (OAuthControllerBase.cs:363). Exactly one implementation is live per host: AddCaching() registers MemoryCacheService via TryAddSingleton (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:84), and AddCommonHybridCache() replaces it (DependencyInjection.Caching.cs:223).
  • Caveats / not-in-source: stampede protection in GetOrCreateAsync is per process (ICacheService.cs:124-128): with several replicas over one shared cache the factory can still run once per replica, and a cluster-wide guarantee would need a distributed lock, which is deliberately not attempted here. The cross-replica guarantee of GetFromSharedStoreAsync holds only where the call site chooses it: a single-use record read through plain GetAsync on the two-level store still gets the L1 window.

IRedisConfigurationOptionsConfigurator

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/IRedisConfigurationOptionsConfigurator.cs:30 · Level 0 · interface

  • What it is: an extension point that adjusts the StackExchange.Redis ConfigurationOptions of every Redis connection the framework opens, before it connects: a token credential, a client certificate, a timeout (IRedisConfigurationOptionsConfigurator.cs:5-9).
  • Depends on: StackExchange.Redis.ConfigurationOptions (NuGet). Bridged into the options pipeline by RedisConfigurationOptionsPostConfigure.
  • Concept introduced, a vendor-neutral hook for vendor-specific connection auth. [Rubric §7, Microservices Readiness] assesses whether infrastructure choices stay at the edges. The core package names only a StackExchange.Redis type; an adapter package (for example AzureRedisEntraAuthenticationConfigurator) supplies the Entra token logic and registers itself, so the core never references a cloud SDK (ADR-134).
  • Walkthrough: one member, void Configure(ConfigurationOptions options) (IRedisConfigurationOptionsConfigurator.cs:34), given options already parsed from the connection string. The remarks (:24-28) state the contract: it runs synchronously inside the options pipeline, may run more than once per process (once per connection point), and throwing from it fails that connection, which is the place to reject a connection string the configurator cannot serve.
  • Why it's built this way: the connections it reaches are spread across packages: the Redis client and distributed cache, the output-cache store, the SignalR backplane and the redis PING health check (IRedisConfigurationOptionsConfigurator.cs:11-15). Routing them all through one registered interface, run once per connection on that connection's own options instance, keeps a credential change a single registration rather than four. With none registered, every connection is made from the connection string exactly as before (:20-22).
  • Where it's used: registered through AddRedisConfigurationOptionsConfigurator (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:288-299), which TryAddEnumerables the instance (idempotent per type, :257) plus the post-configure bridge (:260-261). Read by RedisConfigurationOptionsPipeline in MMCA.Common.Aspire and by the push-notification backplane registration (DependencyInjection.Notifications.cs); implemented by AzureRedisEntraAuthenticationConfigurator.

RememberedToken

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CachePrefixGenerations.cs:418 · Level 0 · record struct (private readonly, nested in CachePrefixGenerations)

  • What it is: the value CachePrefixGenerations remembers per invalidation boundary: the token, the tick count after which it must be refreshed, a monotonic version stamp, and whether this process stored it by invalidating the prefix (CachePrefixGenerations.cs:413-418).
  • Depends on: nothing; four positional members (string Token, long ExpiresAt, long Version, bool FromInvalidation).
  • Concept introduced: none of its own; it carries the "an older read never overwrites a newer invalidation" rule taught on CachePrefixGenerations. ExpiresAt is in Environment.TickCount64 units (:414), and Version plus FromInvalidation are what the AddOrUpdate merge in Remember compares (CachePrefixGenerations.cs:390-393).
  • Why it's built this way: a readonly record struct keeps the dictionary value immutable and allocation-free, so an update is a whole-value swap inside ConcurrentDictionary.AddOrUpdate.
  • Where it's used: only inside the defining class, as the value type of _remembered (CachePrefixGenerations.cs:106), built in Remember (:385) and read in SuffixAsync (:175-184) and FallbackToken (:369-370).

CacheKeyNamespace

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheKeyPrefix.cs:90 · Level 1 · class (internal sealed)

  • What it is: the behavioral half of CacheKeyPrefixOptions. It holds a resolved prefix string and exposes one operation, Qualify, that turns a caller-supplied cache key into the key actually stored, plus the factories that decide which prefix applies. Living in the same file as the options class keeps the settings and their only interpretation together.
  • Depends on: CacheKeyPrefixOptions, ApplicationNamespace (Resolve and Sanitize), JwtSettings (only for the Jwt:Audience key name, CacheKeyPrefix.cs:93), and IOptions<T> / IConfiguration / IHostEnvironment (BCL). Consumed by HybridCacheService, CachePrefixGenerations and RedisDistributedLock.
  • Concept introduced, the null object as a configuration default, with a non-empty fallback. [Rubric §15, Best Practices & Code Quality] assesses whether the code avoids incidental complexity and defensive noise. Rather than making every call site ask "is a prefix configured?", the no-prefix case is a real instance, None, whose Qualify returns the key unchanged: one branch (CacheKeyPrefix.cs:164-165) instead of a null check at every use. [Rubric §11, Security] assesses whether the system prevents data reaching a caller who should not see it: the composition-root factory, From(IServiceProvider), turns an unset Cache:KeyPrefix into a non-empty, per-application prefix (SEC-Common-53, CacheKeyPrefix.cs:108-112) rather than into None, so cross-application key collisions are closed by construction. [Rubric §14, Testability] assesses whether behavior can be exercised without standing up the world: the type is a plain object the cache takes as an optional constructor parameter, so a test passes new CacheKeyNamespace("svc:") directly (the shape used throughout HybridCacheServiceTests.cs).
  • Walkthrough: primary constructor CacheKeyNamespace(string prefix) (CacheKeyPrefix.cs:90).
    • AudienceConfigurationKey (CacheKeyPrefix.cs:93), a private static string built as "Jwt:Audience" from JwtSettings.SectionName and nameof(JwtSettings.Audience), so a rename of either cannot silently break the lookup.
    • None (CacheKeyPrefix.cs:96), a static property initialised to new(string.Empty): one shared immutable instance meaning "leave keys alone", used when a caller constructs HybridCacheService without a namespace (HybridCacheService.cs:160).
    • Prefix (CacheKeyPrefix.cs:99), get-only, initialised with prefix ?? string.Empty, so a null argument degrades to the no-op prefix rather than throwing later inside string.Concat.
    • From(IOptions<CacheKeyPrefixOptions>? options) (CacheKeyPrefix.cs:102-106): tolerates a null options object, reads KeyPrefix, and returns None when it is null or empty. The plain, options-only overload; production DI code does not call it.
    • From(IServiceProvider serviceProvider) (CacheKeyPrefix.cs:116-131), the overload the DI factories call. It returns new CacheKeyNamespace(configured) when Cache:KeyPrefix is set (CacheKeyPrefix.cs:120-124); otherwise it resolves ApplicationNamespace.Resolve against the container's IConfiguration and IHostEnvironment and returns "{applicationNamespace}:" (CacheKeyPrefix.cs:126-130). Because ApplicationNamespace.Resolve never returns empty (ApplicationNamespace.cs:54-55), this overload never returns None.
    • CrossServiceFrom(IServiceProvider serviceProvider) (CacheKeyPrefix.cs:147-161), the namespace for CrossServiceCacheKeys. Three-step fallback: the configured Cache:CrossServiceKeyPrefix (:120-124); otherwise the Jwt:Audience value run through ApplicationNamespace.Sanitize plus :; otherwise, with no audience, From(serviceProvider), the host's own namespace (:126-129). The remarks (:110-115) give the reason the audience is the default: it names exactly the set of services that must see a cross-service record, since every service of a deployment accepts the same audience while its Application:Namespace and Cache:KeyPrefix differ, and a different application accepts a different audience.
    • Qualify(string key) (CacheKeyPrefix.cs:164-165), expression-bodied: returns key unchanged when Prefix.Length == 0, otherwise string.Concat(Prefix, key). No separator is inserted for an explicit prefix, so a configured Cache:KeyPrefix must carry its own delimiter ("conference:", not "conference"); the fallback paths add the : themselves.
  • Why it's built this way: internal sealed because it is an implementation detail of the Infrastructure caching code, never part of the package's public surface. Splitting an init-only options POCO from this behavior object keeps the configuration contract (bindable, public) separate from the runtime helper (internal, immutable, allocation-free on the common path). Resolving the prefix once at construction rather than per call means the options (and, on the fallback paths, the application name or audience) are read a single time for the lifetime of the singleton.
  • Where it's used: From(IServiceProvider) in three registrations in MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs: the Redis output-cache InstanceName post-configure (:75), the RedisDistributedLock factory (:116) and the HybridCacheService factory (:194); CrossServiceFrom once, as the hybrid cache's cross-service namespace (:204). Inside the hybrid cache the namespace lands in _keys with a ?? CacheKeyNamespace.None fallback (HybridCacheService.cs:160), and the same instance is handed to CachePrefixGenerations so the generation keys live in the same namespace as the entries (HybridCacheService.cs:163-167). The in-process branch of AddCaching() builds MemoryCacheService through CreateOwned with no namespace at all (DependencyInjection.Caching.cs:100-104), because the keyspace is private to the process.
  • Caveats / not-in-source: because Qualify is applied inside the cache service and not by Redis, a key written by code that bypasses ICacheService and talks to IDistributedCache directly lands unprefixed. Nothing in the framework's cache path does that, but it is the invariant the design depends on. An explicitly configured CrossServiceKeyPrefix that differs between two services of one deployment silently splits the cross-service keyspace; nothing in source checks that the value matches across hosts.

CacheKeyPrefixOptionsValidator

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheKeyPrefix.cs:63 · Level 1 · class (internal sealed, options validator)

  • What it is: the startup check that refuses a CacheKeyPrefixOptions prefix which is set but does not end in : (CacheKeyPrefix.cs:58-62).
  • Depends on: CacheKeyPrefixOptions, the Level 0 type it validates, which puts it at Level 1, and Microsoft.Extensions.Options.IValidateOptions<T> / ValidateOptionsResult (NuGet).
  • Concept: fail-fast configuration, the same contract CacheSettings gets from data annotations, here expressed as a hand-written IValidateOptions<T> because the rule (a suffix check that allows empty) is not an attribute. [Rubric §15, Best Practices & Code Quality] assesses whether misconfiguration is caught early; this one turns a silent keyspace defect into a host that refuses to start. The doc names the defect: both prefixes are concatenated verbatim, so "adc" would yield keys like adchc:... and a prefix invalidation could never name the boundary (CacheKeyPrefix.cs:59-61), the same boundary rule CachePrefixContract enforces per call.
  • Walkthrough
    • Validate(string? name, CacheKeyPrefixOptions options) (CacheKeyPrefix.cs:66-75): null-checks the options (:68), runs Check over KeyPrefix and CrossServiceKeyPrefix under their configuration key names Cache:KeyPrefix and Cache:CrossServiceKeyPrefix (:71-72), and returns Success when nothing failed, otherwise Fail with every failure (:74). The failure list is allocated lazily, only on the first bad value (:70).
    • Check (:77-86): an empty or null prefix, or one whose last character is :, passes (:79-82); anything else adds a message naming the key, the value, the corrected form ('{prefix}:'), and the option to leave it empty for the framework default (:84-85).
  • Why it's built this way: empty stays legal because empty is the documented "take the default" value of both properties (CacheKeyPrefix.cs:35-55); only a value an operator actually typed is checked. Collecting both failures before returning reports every bad key in one startup error rather than one per restart.
  • Where it's used: registered by AddCaching(IConfiguration) through TryAddEnumerable as an IValidateOptions<CacheKeyPrefixOptions> singleton, next to the section binding with ValidateOnStart (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:45-51), so it runs only when a configuration is passed.
  • Caveats / not-in-source: no test in MMCA.Common/Tests names this type or its message; Not determinable from source whether it is covered indirectly through a host-startup test.

CacheSettings

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CacheSettings.cs:25 · Level 1 · class (public sealed, options)

  • What it is: the Cache section's TTL and sizing policy: the default entry lifetime, the entry limit of the in-process store, the ceiling on the in-process copy of a two-level entry, and how long a cache miss waits for the per-key populate lock before giving up.

  • Depends on: CacheOptions, whose DefaultDuration seeds this class's own default (CacheSettings.cs:41), which is what puts it at Level 1, plus the Application layer's QueryCachePipelineSettings for the populate-lock default (CacheSettings.cs:2, :84) and System.ComponentModel.DataAnnotations.RangeAttribute from the BCL. Consumed by both ICacheService implementations (HybridCacheService, MemoryCacheService).

  • Concept introduced, fail-open configuration. [Rubric §29, Resilience & Business Continuity] assesses whether a degraded dependency degrades the answer. The class doc states the invariant for the whole section: the cache is an optimization, never the system of record, so no value here can turn a cache outage or a slow populate into an error. A miss, an unreachable cache, or an expired PopulateLockTimeout all degrade the request to an uncached read that still runs the real handler and still answers correctly (CacheSettings.cs:14-17). [Rubric §12, Performance & Scalability]: the populate lock is stampede protection, and giving it a finite timeout trades that protection for a latency bound, which is exactly the tradeoff the remarks spell out (:78-82). The same category asks whether growth is bounded: MemoryEntryLimit caps the in-process store so a high-cardinality key set, or the entries a prefix invalidation leaves unreachable until their TTL, cannot grow the process without bound (CacheSettings.cs:43-49).

    [Rubric §15, Best Practices & Code Quality]: the defaults are not re-typed literals. DefaultDuration initializes from CacheOptions.DefaultDuration (CacheSettings.cs:41, defined as 30 seconds at CacheOptions.cs:17), and PopulateLockTimeout from QueryCachePipelineSettings.DefaultPopulateLockTimeout, five seconds (MMCA.Common/Source/Core/MMCA.Common.Application/Settings/QueryCachePipelineSettings.cs:30), so the configured path and the hard-coded path cannot drift apart, and a host that configures nothing behaves as the documented defaults say (CacheSettings.cs:6-11).

  • Concept, one configuration section read by two layers. The Cache section is shared three ways: this class, CacheKeyPrefixOptions for the key namespaces, and the Application layer's QueryCachePipelineSettings, which reads the same Cache:PopulateLockTimeout key from a layer that cannot reference this assembly (CacheSettings.cs:19-23; the Application type declares SectionName = "Cache" at QueryCachePipelineSettings.cs:23 and its own PopulateLockTimeout at :43). [Rubric §3, Clean Architecture]: the dependency rule lets Infrastructure reference Application but not the reverse, so the default lives once on the Application side and this class points at it, while each layer keeps its own bound view of the one operator-facing key.

  • Walkthrough: one constant, one static field and four init properties.

    • DefaultMemoryEntryLimit = 100_000 (CacheSettings.cs:28), the public default for MemoryEntryLimit.
    • SectionName = "Cache" (CacheSettings.cs:31).
    • DefaultDuration (:41), the absolute TTL applied when a caller supplies no expiration. HybridCacheService uses it as the fallback TTL (HybridCacheService.cs:410) and MemoryCacheService does the same (MemoryCacheService.cs:138). It carries a [Range] of one second up to TimeSpan.MaxValue (:40), validated at startup, because a zero or negative TTL would make every write without its own expiration throw (:37-38).
    • MemoryEntryLimit (:55), [Range(1, int.MaxValue)] (:54), defaulting to DefaultMemoryEntryLimit: the most entries the in-process cache of a host with no distributed L2 holds at once. Past it a new entry is not stored and the oldest entries are compacted away (:43-49). It applies only to the cache instance MemoryCacheService owns (read by CreateOwned at MemoryCacheService.cs:94); the host's shared IMemoryCache stays unlimited for the framework's other writers (CacheSettings.cs:50-53), and the two-level cache ignores it because the HybridCache library bounds its own L1 (:48).
    • LocalCacheDuration (:68), nullable, the ceiling on the L1 copy of a two-level entry so a replica that never sees an invalidation still re-reads L2 within the window. Null keeps the built-in 30-second ceiling (HybridCacheService.cs:69), and the effective L1 lifetime is the shorter of the ceiling and the entry's own TTL (HybridCacheService.cs:416). It carries a [Range] of one second up to TimeSpan.MaxValue (:67), validated at startup, because the same value bounds how long a prefix-invalidation generation token is reused without a Redis read (HybridCacheService.cs:166): zero would turn every cache call into a Redis read (CacheSettings.cs:63-65). The doc calls it ignored by the single-level stores (CacheSettings.cs:62-63); MemoryCacheService has no L1, but it does pass the value as the remembering window of its process-local generation tokens (MemoryCacheService.cs:82).
    • PopulateLockTimeout (:84), defaulting to QueryCachePipelineSettings.DefaultPopulateLockTimeout (five seconds): within it, waiters block until the one request holding the lock has populated the entry (:70-76). Once it elapses the waiter proceeds uncached and runs the handler itself, so a pathologically slow populate cannot hold a queue of requests behind it, at the cost that several requests can then run the same query at once; zero or a negative value means no bound, waiters block until the populate finishes (:78-82).
    • Both cache services take the options as an OPTIONAL constructor parameter and fall back to a fresh instance (HybridCacheService.cs:162; MemoryCacheService.cs:74), so a service constructed outside the container still gets the framework defaults.
  • Why it's built this way: registration guarantees IOptions<CacheSettings> always resolves. When configuration is available the section is bound and validated (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:53-56, ValidateDataAnnotations plus fail-fast ValidateOnStart, see ADR-070); when the parameterless overload is used, AddOptions<CacheSettings>() is still called so the defaults materialize instead of failing the host (DependencyInjection.Caching.cs:65). The same values are then projected into HybridCache's own option type through the options pipeline rather than the AddHybridCache callback, because the callback has no service provider to read the bound section from, and the host's own hook still runs last so it can override anything the framework set (DependencyInjection.Caching.cs:201-219, the local-expiration fallback at :215, ADR-077).

  • Where it's used: MemoryCacheService and HybridCacheService receive it through IOptions<CacheSettings> from their factories (DependencyInjection.Caching.cs:104, :238), and the HybridCacheOptions projection reads it (:205-219). LoginProtectionService also reads it. Its defaults and binding are pinned by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Settings/CacheSettingsTests.cs.

InMemoryCounterStore

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/InMemoryCounterStore.cs:24 · Level 1 · class (internal sealed)

  • What it is: the process-local ICounterStore: atomic fixed-window counters for rate limits and brute-force throttles. It is the store of a host with no Redis, and the fallback RedisCounterStore counts in while Redis is unreachable (InMemoryCounterStore.cs:6-9).
  • Depends on: CounterWindow (its nested value record, which is what puts it at Level 1), ICounterStore (implemented), ConcurrentDictionary<TKey, TValue> and an optional TimeProvider (primary constructor, InMemoryCounterStore.cs:24; TimeProvider.System when omitted, :29).
  • Concept introduced, atomic counting without a lock. [Rubric §11, Security] assesses whether a security control survives concurrency. A brute-force counter that loses increments under load is a weakened control, so every change here is one compare-and-swap of an immutable window record through ConcurrentDictionary.AddOrUpdate, and concurrent increments never overwrite each other (InMemoryCounterStore.cs:12-15). [Rubric §12, Performance & Scalability]: bounded memory. Ended windows are dropped when their key is next touched and swept once per SweepInterval increments, so keys that are never touched again (one per client IP or address) cannot grow the table without bound (InMemoryCounterStore.cs:18-20).
  • Walkthrough
    • SweepInterval (InMemoryCounterStore.cs:27), internal const int = 1024.
    • Fields _timeProvider (:29), _counters, a ConcurrentDictionary<string, CounterWindow> with ordinal keys (:30), and _incrementsSinceSweep (:31); Count (:34) exposes the table size, unswept ended windows included, for tests.
    • IncrementAsync(key, window, ct) (:37-38) wraps the synchronous Increment in Task.FromResult: the store never waits on anything (:58).
    • Increment (:62-82) null-checks the key and rejects a non-positive window (:64-65), then calls AddOrUpdate with static factories and a (Now, Window) state tuple (:68-74): a new key opens a window of one, a key whose window is still open returns the same window with the count plus one, and a key whose window has ended opens a fresh one. Every SweepIntervalth increment, counted with Interlocked.Increment, triggers Sweep(now) (:76-79). It returns the post-increment count (:81).
    • GetAsync (:41-47) answers the count of an open window and 0 for a missing or ended one (:46), without writing.
    • ResetAsync (:50-56) removes the key outright (:54).
    • Sweep (:86-96) walks the table and drops every window that ended at or before now, removing only the record it saw so a window reopened in between survives (:92-93).
  • Why it's built this way: the window's end is fixed by the increment that opens it and never moved by a later one (InMemoryCounterStore.cs:14-15), which is the fixed-window semantics the Redis store's script also has, so a host behaves the same whichever store it resolves. Taking TimeProvider keeps the window arithmetic testable without sleeping.
  • Where it's used: registered by the caching registration when no IConnectionMultiplexer is present (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:145), and constructed by RedisCounterStore as its fault fallback (RedisCounterStore.cs:69). Consumers reach it only through ICounterStore: LoginProtectionService, PasswordResetTokenService, EmailConfirmationTokenService and SignInLinkTokenService (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Auth/LoginProtectionService.cs:155, .../PasswordResetTokenService.cs:69, .../EmailConfirmationTokenService.cs:59, .../SignInLinks/SignInLinkTokenService.cs:61). Tested by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Caching/CounterStoreTests.cs.
  • Caveats / not-in-source: the count is per process, so with several replicas and no Redis each replica enforces limits on what it saw itself. The sweep runs inline on the increment that crosses the interval, so that one call pays an O(n) walk of the table.

RedisConfigurationOptionsPostConfigure

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/RedisConfigurationOptionsPostConfigure.cs:15 · Level 1 · class (internal sealed)

  • What it is: the options-pipeline bridge that runs every registered IRedisConfigurationOptionsConfigurator on each ConfigurationOptions instance the options system builds, for every name, after the instance has been parsed and bound (RedisConfigurationOptionsPostConfigure.cs:5-12).
  • Depends on: IRedisConfigurationOptionsConfigurator (an IEnumerable of them), IPostConfigureOptions<T> (BCL) and ConfigurationOptions (StackExchange.Redis).
  • Concept introduced, reaching a package without referencing it. [Rubric §3, Clean Architecture] assesses whether dependencies point the right way. MMCA.Common.Aspire must not reference this package, yet its Redis client and output-cache options have to run the configurators. Both sides name only a StackExchange.Redis type and the options abstractions, so this class is the meeting point: Aspire's Redis client reads its options from the pipeline, and RedisConfigurationOptionsPipeline applies the same post-configure steps to the options it parses itself.
  • Walkthrough: primary constructor taking the configurators; _configurators (RedisConfigurationOptionsPostConfigure.cs:18) snapshots them into an array once. PostConfigure (:21-29) ignores the name, null-checks the options and calls Configure on each configurator in registration order.
  • Why it's built this way: IPostConfigureOptions runs after binding, so a configurator always sees the values parsed from the connection string and can override them; the name is ignored because a credential applies to every connection, not to one named client.
  • Where it's used: registered by AddRedisConfigurationOptionsConfigurator through TryAddEnumerable (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:295-296), so registering several configurators adds the bridge once.

CachePrefixGenerations

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/CachePrefixGenerations.cs:70 · Level 2 · class (internal sealed partial)

  • What it is: prefix invalidation for HybridCacheService without walking the keyspace. Every invalidation boundary of a key (the empty root, then each prefix ending at :) carries a generation token, and the tokens in force are folded into the key the entry is stored under. Invalidating a prefix replaces its token, so every entry written under the old token stops being addressed and expires on its own TTL (CachePrefixGenerations.cs:8-14).

  • Depends on: CacheKeyNamespace (the generation keys share the entries' namespace) and RememberedToken (nested). Externals: StackExchange.Redis.IConnectionMultiplexer (optional), ConcurrentDictionary, RandomNumberGenerator, ILogger (BCL/NuGet).

  • Concept introduced, generation tokens as O(1) invalidation. [Rubric §12, Performance & Scalability] assesses whether cost stays flat as data grows. A SCAN-and-delete invalidation costs time proportional to the keyspace; here an invalidation is one Redis write whatever the keyspace size (HybridCacheService.cs:26-32). The remarks record three design choices:

    • Why not HybridCache.RemoveByTagAsync (CachePrefixGenerations.cs:17-24): in Microsoft.Extensions.Caching.Hybrid 10.11.0 each process reads a tag's invalidation timestamp once and keeps it for its lifetime, so another replica that already saw the tag never learns of a later invalidation. HybridCacheCrossInstanceInvalidationTests pins the property this class provides instead.
    • Tokens, not counters (:26-34): a fresh random value rather than an INCR, so concurrent invalidations need no atomicity and a lost generation key can never come back at an older non-baseline token. It can come back at the baseline: a lost hcg: key re-addresses entries written before that prefix's first invalidation until their TTL.
    • Staleness bound (:36-46): a token is reused without a read for one local cache duration (Cache:LocalCacheDuration, 30 seconds by default), then served while one background read refreshes it, so another replica's invalidation is seen within one local duration plus one round trip.

    [Rubric §29, Resilience & Business Continuity]: a failed token read never fails the cache call. It answers with the last token this process knew or, for a boundary it never saw, the empty baseline (CachePrefixGenerations.cs:52-66). The baseline is chosen deliberately over a random token: the lockout flag, failure counters and registration throttles live under boundaries nobody invalidates, so the baseline keeps them in the keyspace every replica shares and rate limits keep working on a cold replica during an outage, where a random fallback would fail open. The remarks state the cost plainly: in a partial outage a cold replica can address pre-invalidation entries of a prefix that was invalidated, until their TTL.

  • Walkthrough

    • Constants: KeyspaceSegment = "hcg:" (CachePrefixGenerations.cs:77), disjoint from the entries' hc:; SuffixSeparator = '|' (:79); RetentionMultiplier = 10 (:86, a remembered token is kept ten local durations past expiry, five minutes at the default); TokenSeparator = '.' (:89); SweepInterval = 1024 (:92).
    • State: _remembered (:105, boundary to RememberedToken), _inFlight (:108, one shared read per boundary), _processLocal (:111, the authoritative tokens when there is no Redis), and _version (:114), the monotonic stamp that stops an older read overwriting a newer invalidation.
    • Constructor (:124-138): null-checks keys and logger, clamps the local duration at zero and derives _retentionMs from it.
    • SuffixAsync(key, ct) (:149-202): computes the key's Boundaries, then without Redis reads _processLocal directly (:157-165). With Redis it snapshots _version before deciding what to read (:169), serves a remembered token at once and, if it is past ExpiresAt but within retention, fires one background refresh (:175-184); unknown boundaries are read and awaited, and only the caller's own cancellation ends that wait (:195-198). Compose (:264-272) folds the non-empty tokens into |tok1.tok2, or returns an empty string so an untouched key keeps its plain shape.
    • InvalidateAsync(prefix, ct) (:217-238): mints a token (NewToken, 64 random bits, :276). Without Redis it writes _processLocal and warns once that invalidation is process-local (:224-232). With Redis it adopts the token locally first (:236), so this process stops serving the prefix even if the write fails, then StringSetAsync on GenerationKey(prefix) (:237, key built at :281), whose failure propagates to the caller.
    • Boundaries(key) (:246-259): "", then every prefix ending at :; for A:B:C that is "", A: and A:B:.
    • ReadShared / ReadIntoAsync / ReadAndRememberAsync / ReadFailed (:291-361): one read per boundary is published before it starts (:291-297), always completes with a token (the fallback if anything escapes, :308-323), and any read failure, including a cancellation raised inside the Redis client, is logged and answered with FallbackToken (:333-361, :369-370).
    • Remember (:382-404): stores a RememberedToken for one local duration, but an AddOrUpdate merge keeps an existing token this process stored by invalidating the prefix when its version is newer than the read's snapshot (:389-392); every 1024th insert sweeps entries past retention (:394-401).
  • Why it's built this way: random tokens remove the need for atomic Redis operations, the local-first adoption means an invalidation is never lost for the invalidating process, and the shared in-flight read keeps a burst of concurrent callers on one round trip. ADR-026 records the switch from SCAN to the generation-token write (026-caching-strategy.md:1140-1141), and ADR-077 its scope, that tokens fold only into hc: keys (077-hybridcache-substrate.md:68-69).

  • Where it's used: constructed once per HybridCacheService in its constructor with the multiplexer, the host namespace and LocalCacheDuration ?? LocalCacheDefault (HybridCacheService.cs:163-167), and called from HybridKeyAsync (HybridCacheService.cs:397) and RemoveByPrefixAsync (HybridCacheService.cs:332). Unit-tested by CachePrefixGenerationsTests.

  • Caveats / not-in-source: generation keys carry no TTL, so Redis holds one short string per distinct invalidated prefix (CachePrefixGenerations.cs:44-46); the remarks recommend a volatile-* eviction policy so they are not evicted (:32-34). Whether a given deployment's Redis is configured that way is not determinable from source.

RedisCounterStore

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/RedisCounterStore.cs:36 · Level 2 · class (internal sealed partial)

  • What it is: the Redis-backed ICounterStore: one plain Redis string per counter, incremented and given its TTL by the same Lua script the distributed rate limiter runs, so the increment is atomic across replicas and only the creating increment sets the expiry (RedisCounterStore.cs:9-14).
  • Depends on: CacheKeyNamespace (optional, qualifies every key) and InMemoryCounterStore (the fault fallback), the two Level 1 types that put it at Level 2; RedisCounterScript and RedisOutageCircuit from MMCA.Common.Redis (RedisCounterStore.cs:4); StackExchange.Redis.IConnectionMultiplexer, ILogger<T> and an optional TimeProvider.
  • Concept introduced, a disjoint keyspace per writer. [Rubric §8, Data Architecture] assesses whether stored data has one owner and one shape. Counter keys live under their own ctr: segment inside the cache namespace, {prefix}ctr:{key}, disjoint from the cache entries (hc:), the generation tokens (hcg:), the locks (lock:) and the rate-limit windows (rl:), and they are plain strings, never IDistributedCache hashes, which is what lets INCRBY work on them (RedisCounterStore.cs:17-21). Second concept, fail to a weaker local answer, not to zero. [Rubric §29, Resilience & Business Continuity]: a Redis fault never fails the caller, but answering a count of zero would switch every limit off for the outage, so the call is served by the process-local store instead and each replica keeps enforcing limits on what it saw itself (RedisCounterStore.cs:24-28). [Rubric §11, Security] is why the fallback is a counter and not a pass. A fault also opens the connection's RedisOutageCircuit: for its window every call goes straight to the fallback instead of waiting out the client timeout again, and one call probes Redis once the window has passed (RedisCounterStore.cs:30-34). The window is ten seconds (MMCA.Common/Source/Build/Redis/RedisOutageCircuit.cs:30), and the circuit is one per connection, shared with nothing outside this package's copy of the linked source (RedisOutageCircuit.cs:22-24).
  • Walkthrough
    • KeyspaceSegment (RedisCounterStore.cs:39), internal const string = "ctr:".
    • _lastLoggedFaultMinute (:42), a static long shared across the process, so an outage logs once a minute however many instances exist.
    • _circuit (:49), the connection's outage circuit.
    • Constructor (:56-71): null-checks the multiplexer and logger, falls back to CacheKeyNamespace.None and TimeProvider.System (:67-68), builds its own InMemoryCounterStore over the same clock (:69), and takes the connection's circuit through RedisOutageCircuit.For(connection) (:70).
    • IncrementAsync (:74-101): rejects a non-positive window (:77), rounds the window up to whole seconds with a floor of one because EXPIRE takes seconds (:80-81), and counts in the fallback without touching Redis while the circuit says not to attempt (:83-86). Otherwise it evaluates RedisCounterScript.Increment with the qualified key and [1, ttlSeconds] (:90-92) and records a success on the circuit (:93). On a fault it logs and counts in the fallback (:96-100).
    • GetAsync (:104-125): the same circuit check reads the fallback (:109-112); otherwise StringGetAsync, a circuit success, then 0 on a missing key or an invariant-culture long.Parse (:116-118); faults read the fallback (:120-124).
    • ResetAsync (:128-150): resets the fallback copy first, so a count taken during an outage cannot outlive a reset (:133-134), returns there while the circuit is open (:136-139), then deletes the Redis key and records a success (:143-144), logging rather than throwing on a fault (:146-149).
    • IsFault (:159-160): every exception counts as a Redis fault except the caller's own cancellation; a cancellation the caller did not request (a client-side timeout) is a fault (:153-154).
    • RedisKeyOf (:165) builds {prefix}ctr:{key} through CacheKeyNamespace.Qualify.
    • LogFault (:169-177) first opens the circuit with RecordFault (:171), then swaps the current minute into _lastLoggedFaultMinute with Interlocked.Exchange and logs only when the minute changed (:173); the source-generated warning is at :179-180.
  • Why it's built this way: sharing the rate limiter's script means one atomic primitive for every counted thing in the framework, and the ctr: segment keeps the counters away from the hash-shaped cache entries an INCR would otherwise collide with. The fallback mirrors the distributed rate limiter's fault behavior (RedisCounterStore.cs:24-25), so the two degrade the same way; the circuit is the same mechanism the limiter uses (RedisOutageCircuit.cs:7-9), because without it every call during an outage still waited for the client to give up before falling back (RedisOutageCircuit.cs:13-16).
  • Where it's used: registered as the ICounterStore singleton whenever an IConnectionMultiplexer is registered, with CacheKeyNamespace.From(sp) and the container's TimeProvider (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:134-143), chosen exactly as the distributed lock above it (:131-133). Consumers are the auth services listed on InMemoryCounterStore. Tested by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Caching/CounterStoreTests.cs and against a real Redis by MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Redis.Tests/RedisCounterStoreRedisTests.cs.
  • Caveats / not-in-source: during an outage the counts split per replica, and they do not merge back: increments taken in the fallback are not replayed to Redis when it recovers. GetAsync parses whatever string sits at the key, so a non-numeric value written there by another writer would throw and fall back; the disjoint ctr: segment is what keeps that from happening. A ResetAsync that lands while the circuit is open clears only the fallback copy and skips the Redis delete (RedisCounterStore.cs:136-139), so the Redis count survives that reset until its own TTL.

HybridCacheService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/HybridCacheService.cs:53 · Level 3 · class (internal sealed partial)

  • What it is: the two-level implementation of ICacheService, backed by Microsoft.Extensions.Caching.Hybrid.HybridCache: an in-process L1 in front of the host's registered IDistributedCache L2, with serialization, L1 promotion and stampede protection supplied by the platform. It is the one cache a host with a distributed L2 runs; a host without one keeps MemoryCacheService (HybridCacheService.cs:13-16).
  • Depends on: ICacheService (implemented), CacheKeyNamespace (two optional constructor parameters), CacheSettings (optional, the TTL and L1 ceiling), CacheOptions (the value those settings default to), CachePrefixGenerations (prefix invalidation, the Level 2 type that puts it at Level 3), CachePrefixContract (the prefix guard) and CrossServiceCacheKeys. Externals: HybridCache / HybridCacheEntryOptions / HybridCacheEntryFlags (NuGet), ILogger<T> and StackExchange.Redis.IConnectionMultiplexer (optional).
  • Concept introduced, a disjoint keyspace for one serialization format. [Rubric §8, Data Architecture] assesses whether stored data has one owner and one shape. Every entry this service writes carries an hc: segment inside the configured prefix, {prefix}hc:{key} (HybridCacheService.cs:59), so an entry can never meet a value another writer put in the same server (a host's own IDistributedCache use, or the hcg: generation keys) in a format it cannot parse (HybridCacheService.cs:20-23). ADR-077 records the origin, a since-removed sibling adapter whose payload layout differed and a rolling deploy where both served one Redis, and why the rule still holds without it (077-hybridcache-substrate.md:54-57), plus the rejected alternative, a payload discriminator in one keyspace (077-hybridcache-substrate.md:60-62). [Rubric §12, Performance & Scalability]: the point of L1 is removing a network hop and a deserialize from every read of a small hot value, and prefix invalidation costs one Redis write via CachePrefixGenerations rather than a keyspace walk (HybridCacheService.cs:26-32). Second concept, knowing which reads must skip the fast tier. [Rubric §11, Security]: an L1 copy is only safe for a value that tolerates being stale on one replica for the local expiration. A single-use record (an OAuth exchange code, a password-reset or email-confirmation token, the last accepted second-factor time step) does not, so it is read from L2 alone, as are the reads that must see a removal at once (the login lockout flag and the soft-deleted-user marker) (HybridCacheService.cs:35-41). Counters are not kept in this cache at all: they live in the ICounterStore, whose Redis store (RedisCounterStore) increments atomically (HybridCacheService.cs:41-42). Third concept, cross-service keys. A record one service writes and another reads (the soft-deleted-user marker) is qualified with the cross-service namespace every service of a deployment shares, and carries no generation token, so a record Identity writes is the record every other service reads (HybridCacheService.cs:47-50).
  • Walkthrough
    • KeyspaceSegment (HybridCacheService.cs:59), internal const string = "hc:", applied inside the configured namespace.
    • MissMarker (HybridCacheService.cs:62), the Exception.Data key that tags the presence probe's miss.
    • LocalCacheDefault (HybridCacheService.cs:69), internal static readonly TimeSpan = 30 seconds. It is the default L1 lifetime, the ceiling applied to every entry, and the default lifetime of a remembered generation token. AddCommonHybridCache seeds HybridCacheOptions from the same field when the host configured no Cache:LocalCacheDuration (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:215), and MemoryCacheService uses it as its token lifetime default (MemoryCacheService.cs:82).
    • ReadOnlyOptions (HybridCacheService.cs:77-80) and SharedStoreReadOptions (HybridCacheService.cs:88-93), two static option objects. The first sets HybridCacheEntryFlags.DisableUnderlyingData, which tells HybridCache not to invoke the factory and not to write anything, so a miss stays a miss while an L2 hit is still promoted into L1. The second adds DisableLocalCacheRead | DisableLocalCacheWrite, a read answered by L2 alone with no L1 promotion, used by GetFromSharedStoreAsync (HybridCacheService.cs:82-87). A third object, PresenceProbeOptions (HybridCacheService.cs:102-105), carries only DisableDistributedCacheWrite and exists for TryGetAsync, below.
    • Fields _hybrid, _logger (HybridCacheService.cs:107-108), _keys (:115), _crossServiceKeys (:123), _settings (:130) and _generations (:133).
    • Constructor (HybridCacheService.cs:147-168): null-checks hybrid and logger; _keys falls back to CacheKeyNamespace.None, _crossServiceKeys to _keys, _settings to new CacheSettings() (:160-162); then builds CachePrefixGenerations over the optional multiplexer, _keys and LocalCacheDuration ?? LocalCacheDefault (:163-167). A null multiplexer keeps the generation tokens in this process.
    • HybridKeyAsync (HybridCacheService.cs:390-399), the key builder every member goes through. A cross-service key (CrossServiceCacheKeys.IsCrossService) is qualified with _crossServiceKeys and no suffix (:392-395); every other key gets the generation suffix and _keys, producing {prefix}hc:{key} plus the token suffix (:397-398). The remarks (:385-388) say why cross-service keys skip the suffix: generation tokens are per namespace, so a prefix wipe in one service would otherwise move its copy away from the others'.
    • GetAsync<T> (HybridCacheService.cs:179-198), calls _hybrid.GetOrCreateAsync with a static no-op factory and ReadOnlyOptions, which is how you perform a plain read through an API whose primary shape is get-or-create. It is fail-soft (HybridCacheService.cs:171-178): any exception that is not OperationCanceledException is logged at warning and answered as a miss (HybridCacheService.cs:192-197), and the offending entry is dropped best-effort through SelfHealAsync so the next write repopulates it.
    • TryGetAsync<T> (HybridCacheService.cs:220-245). HybridCache has no presence-reporting read, so presence is read from whether it had to call the factory. The factory is static _ => throw CacheMiss(): a hit never calls it, and a miss throws a KeyNotFoundException that catch ... when (ex.Data.Contains(MissMarker)) turns into (false, default) (HybridCacheService.cs:235-238). CacheMiss() (HybridCacheService.cs:370-375) builds the tagged exception, so a KeyNotFoundException raised anywhere else cannot be mistaken for a miss. A thrown sentinel rather than a flag the factory sets, because a concurrent read of the same key joins the first caller's in-flight lookup and never runs its own factory, while the exception reaches every joined caller (HybridCacheService.cs:209-211). PresenceProbeOptions makes this read's flags unique, and HybridCache only joins callers with identical flags, so a GetOrCreateAsync in flight on the same key can never be handed that miss (HybridCacheService.cs:214-217). Other faults are fail-soft like GetAsync (HybridCacheService.cs:239-244).
    • GetFromSharedStoreAsync<T> (HybridCacheService.cs:262-281): the same no-op-factory read as GetAsync, but with SharedStoreReadOptions (HybridCacheService.cs:271), so the answer always comes from L2 and nothing is promoted into this replica's memory. A removal on another replica is seen immediately, which is what keeps a single-use record single-use (HybridCacheService.cs:250-253). It is fail-soft exactly like GetAsync (HybridCacheService.cs:275-280); for a single-use record a miss is a refusal, which is the safe direction (HybridCacheService.cs:256-259).
    • SetAsync<T> (HybridCacheService.cs:291-299), one call to _hybrid.SetAsync with the options WriteOptions(expiration) builds.
    • RemoveAsync (HybridCacheService.cs:308-312), _hybrid.RemoveAsync, which clears this process's L1 copy along with the L2 entry. Other replicas' L1 copies are not reached and keep serving the removed value until they expire, up to Cache:LocalCacheDuration (30 seconds by default); a read that must see the removal everywhere goes through GetFromSharedStoreAsync (HybridCacheService.cs:303-306).
    • RemoveByPrefixAsync (HybridCacheService.cs:329-333), a non-async method: it runs CachePrefixContract.EnsureBoundary (:331) and returns _generations.InvalidateAsync(prefix, ...) directly (:332). Nothing is scanned or deleted: the replaced token stops every entry under the prefix being addressed, here at once and on other replicas within Cache:LocalCacheDuration, and the orphaned entries expire on their own TTL (HybridCacheService.cs:317-321). Without a multiplexer the invalidation reaches this process only, warned once (:324-325).
    • GetOrCreateAsync<T> (HybridCacheService.cs:344-363) hands the work to HybridCache's own primitive, which folds the double-check and stampede protection MemoryCacheService spells out into one call and additionally deduplicates concurrent callers before they reach L2 (HybridCacheService.cs:337-342). The factory is passed as state rather than captured (HybridCacheService.cs:354-359), so the delegate stays static and no closure is allocated per call.
    • WriteOptions (HybridCacheService.cs:408-419) and SelfHealAsync (HybridCacheService.cs:429-439), the private helpers. WriteOptions is where both dials meet: ttl = expiration ?? _settings.DefaultDuration (:410), localCeiling = _settings.LocalCacheDuration ?? LocalCacheDefault (:411), and LocalCacheExpiration = ttl < localCeiling ? ttl : localCeiling (:416), so a long-lived entry does not sit in another replica's memory for its whole TTL after an invalidation that process never saw.
  • Why it's built this way: ADR-077 is the record. It is the only cache service over a shared store: AddCaching's fallback factory throws, naming the call, when a non-memory IDistributedCache is registered without AddCommonHybridCache, because silently falling back to the in-process cache would make single-use records and the lockout flag per-replica (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:84-105, the throw at :94-97). The registration deliberately uses RemoveAll + Add rather than TryAdd so it wins in either call order (DependencyInjection.Caching.cs:221-223), with the honest warning that RemoveAll does not distinguish the framework's registration from a host's own custom ICacheService (DependencyInjection.Caching.cs:182). Generation tokens replace HybridCache.RemoveByTagAsync for the cross-replica reason recorded on CachePrefixGenerations. [Rubric §29, Resilience] shows up in the fail-soft read: the cache is an optimization, never the system of record, so an unreadable entry costs a database round trip rather than a failed request.
  • Where it's used: registered only by AddCommonHybridCache, which constructs it with the host namespace and CacheKeyNamespace.CrossServiceFrom(sp) (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:233-239). AddCommonHybridCacheWhenRedisConfigured calls it only when the redis connection string is configured (DependencyInjection.Caching.cs:267), and the composed service-host start-up calls that guard (MMCA.Common/Source/Hosting/MMCA.Common.ServiceHost/ServiceHostBuilderExtensions.cs). Everything downstream still talks to ICacheService and is unaware. Covered by HybridCacheServiceTests, the registration semantics by AddCommonHybridCacheTests, and against a real Redis by HybridCacheServiceRedisTests and HybridCacheCrossInstanceInvalidationTests (cross-replica invalidation).
  • Caveats / not-in-source: replica staleness after a removal or an invalidation is bounded by the local expiration (30 seconds by default, Cache:LocalCacheDuration to change it), not by the call itself, because only the calling process's L1 and remembered tokens change at once (HybridCacheService.cs:28-32). That is the same order as the delayed re-invalidation CachingCommandDecorator<TCommand, TResult> already performs. It does not apply to reads made through GetFromSharedStoreAsync, which never touch L1; a caller that reads a single-use record through plain GetAsync instead still gets the L1 window, so the protection depends on the call site choosing the right member. The keys read through GetFromSharedStoreAsync still carry generation tokens, so invalidating a prefix that covers them converges across replicas within the local expiration like any other entry; nothing in the framework invalidates such a prefix (HybridCacheService.cs:42-44). TryGetAsync reports a miss through a caught KeyNotFoundException, so it is the correctness path for value types, not the hot path. Because the keyspace is disjoint, a host that switches substrate starts cold: entries another writer put in the server are invisible here and age out on their own TTL, which ADR-077 records as a cost rather than a correctness problem (077-hybridcache-substrate.md:65-68).

MemoryCacheService

MMCA.Common.Infrastructure · MMCA.Common.Infrastructure.Caching · MMCA.Common/Source/Core/MMCA.Common.Infrastructure/Caching/MemoryCacheService.cs:38 · Level 4 · class (internal sealed, IDisposable)

  • What it is: the in-process implementation of ICacheService, the cache of a host with no distributed L2, backed by IMemoryCache. IMemoryCache exposes no way to enumerate its keys, so this service honors RemoveByPrefixAsync the same way the two-level store does: it folds process-local generation tokens into every stored key, and invalidating a prefix replaces one token so every entry under it becomes a miss (MemoryCacheService.cs:13-20).
  • Depends on: IMemoryCache / MemoryCache / MemoryCacheOptions / MemoryCacheEntryOptions (Microsoft.Extensions.Caching.Memory), CacheSettings (optional, the default TTL, the entry limit and the token lifetime), CachePrefixGenerations built with no Redis over CacheKeyNamespace.None, CachePrefixContract for the prefix guard, KeyedSemaphoreStripe for GetOrCreateAsync's stampede protection, and HybridCacheService.LocalCacheDefault as the token-lifetime fallback (MemoryCacheService.cs:79-83), the Level 3 reference that puts it at Level 4. Implements every ICacheService member itself.
  • Concept introduced, one invalidation mechanism behind two backends. [Rubric §12, Performance & Scalability] assesses cheap reads, sound invalidation and bounded growth; an in-process cache is the lowest-latency option available but is not shared across instances, so it is correct for a single-process monolith or for genuinely per-instance data and wrong for anything else. The teachable mechanic is reuse: instead of maintaining a shadow index of live keys to back-fill the missing enumeration API, the service reuses CachePrefixGenerations with no multiplexer, where the tokens are authoritative in this process (MemoryCacheService.cs:76-83). It presents the identical ICacheService surface as HybridCacheService, including the same prefix boundary rule and the same key shape (caller key plus generation suffix, MemoryCacheService.cs:199-203), so swapping backends changes nothing for callers. Second concept, a bounded cache the store owns. Because a prefix invalidation leaves orphaned entries behind until their TTL, the container builds this store over a MemoryCache of its own whose SizeLimit is CacheSettings.MemoryEntryLimit, and every entry is written with a size of one, so the limit counts entries (MemoryCacheService.cs:22-28, :92-97, :134-139). The host's shared IMemoryCache is left unlimited, because the framework's other writers to it set no entry size and would throw under a limit (:26-28). Third concept, real presence for value types. [Rubric §15, Best Practices & Code Quality]: TryGetAsync matches on the stored object rather than using the generic TryGetValue<T>, which performs an unchecked cast and throws when a key is reused under a different T, so a type mismatch (or a stored null) is a clean miss (MemoryCacheService.cs:110-114), and a cached 0 or false is still a hit.
  • Walkthrough: two constructors and a factory, then the ICacheService members.
    • _cache (MemoryCacheService.cs:40) and _ownedCache (:43), the MemoryCache this store created and must dispose, or null when it was given one (:42).
    • _settings (:49), the bound Cache section or new CacheSettings() when a host built the service without one (:74). It supplies the expiration of an entry written without one, as every other store does (:45-48).
    • _generations (:52), built in the private constructor with redis: null, CacheKeyNamespace.None, LocalCacheDuration ?? HybridCacheService.LocalCacheDefault and NullLogger.Instance (:79-83). The comment explains the discarded logger: the only thing it would receive is the "invalidation is process-local" warning, which states this store's design rather than a misconfiguration (:76-78).
    • _createLocks (:58), a KeyedSemaphoreStripe for GetOrCreateAsync. It is per instance rather than static: the service is a singleton, and two instances share no entries to protect (:54-57).
    • The public constructor (:63-66) takes a required IMemoryCache and an optional IOptions<CacheSettings>?, and chains to the private one with no owned cache. The private constructor (:68-84) null-checks the cache (:70) and assigns the fields.
    • CreateOwned(IOptions<CacheSettings>? settings) (:92-97), internal static: reads MemoryEntryLimit (or CacheSettings.DefaultMemoryEntryLimit with no settings, :94), creates a MemoryCache with that SizeLimit (:95), and passes it as both the cache and the owned cache (:96).
    • Dispose (:100) disposes the owned cache, a no-op for a store that was handed its cache.
    • GetAsync<T> (:103-107) delegates to TryGetAsync and returns the value only when found.
    • TryGetAsync<T> (:115-119) resolves the stored key, then _cache.TryGetValue(storedKey, out var stored) && stored is T typed (:118).
    • GetFromSharedStoreAsync<T> (:123-124) is GetAsync: this store has no tier other than the process, so it is the shared store (:122).
    • SetAsync<T> (:127-141) resolves the stored key (:133) and calls _cache.Set with AbsoluteExpirationRelativeToNow = expiration ?? _settings.DefaultDuration and Size = 1 (:136-140), so an entry written without a TTL expires on the configured default exactly as on the two-level path, and an owned cache's size limit counts entries while a cache with no limit ignores the size (:134-135).
    • RemoveAsync (:144-148) removes the stored key for the current generation.
    • RemoveByPrefixAsync (:157-161), a non-async method: it runs CachePrefixContract.EnsureBoundary (:159), so a prefix that does not end at : throws here exactly as it would on the two-level cache, then returns _generations.InvalidateAsync(prefix, ...) (:160).
    • GetOrCreateAsync<T> (:168-193): null-guards the factory (:174), takes a lock-free fast path on a hit (:176-179), and only on a miss acquires the key's stripe (:181), re-reads under it (:183-187, the double-check that lets waiters see the value the winner just wrote), then runs the factory and stores its result (:189-191). Both reads go through TryGetAsync, so a cached default(T) of a value type counts as a hit (:164-167).
    • StoredKeyAsync (:199-203), the caller's key plus the generation suffix from _generations.SuffixAsync.
  • Why it's built this way: generation tokens give IMemoryCache a prefix-removal capability without replacing it and without a second structure that has to agree with the cache, so there is no tracking table to drift and no eviction callback to race. Owning a size-limited instance rather than putting a limit on the shared IMemoryCache bounds this store without breaking the other writers, and the store disposes what it created. Striping rather than a semaphore per key is a bounded-memory choice made once in KeyedSemaphoreStripe and reused here. Taking CacheSettings gives both stores one TTL policy, so a caller's omitted expiration means the same thing whichever adapter the host resolved. The class is internal sealed because it is only ever resolved through the ICacheService registration.
  • Where it's used: the factory registered by AddCaching() via TryAddSingleton (MMCA.Common/Source/Core/MMCA.Common.Infrastructure/DependencyInjection.Caching.cs:84), which builds it through MemoryCacheService.CreateOwned (DependencyInjection.Caching.cs:104); the comment there notes that the container disposes the store and the store its instance (:100-103). AddCaching() still calls AddMemoryCache() first (DependencyInjection.Caching.cs:31) for the framework's other writers. The factory only returns this service when no distributed cache, or only the in-memory MemoryDistributedCache, is registered; a real distributed cache without AddCommonHybridCache makes it throw instead (DependencyInjection.Caching.cs:92-97). A host with no Redis therefore behaves as a single-instance cached monolith with the full interface intact. Consumed through the interface by both CQRS caching decorators, LoginProtectionService, PasswordResetTokenService, SoftDeletedUserCache and IdempotencyFilter. Unit-tested by MemoryCacheServiceTests and MMCA.Common/Tests/Core/MMCA.Common.Infrastructure.Tests/Caching/MemoryCacheServiceGetOrCreateTests.cs.
  • Caveats / not-in-source: the cache is per-process, so two replicas hold independent and potentially divergent copies until each entry's TTL or an explicit eviction reconciles them. That is why HybridCacheService exists for scaled-out deployments, and why ADR-026 treats per-replica memory mode as a trade-off rather than a supported multi-replica posture. A prefix invalidation deletes nothing: the orphaned entries stay in the owned cache, unaddressable, until their own expiration or until the entry limit compacts them away. Reads return the stored instance, never a copy: nothing is serialized, so a caller that mutates a cached value changes it for every later reader, and a value System.Text.Json cannot round-trip is never noticed here, unlike on the two-level store (MemoryCacheService.cs:30-36); treat cached values as immutable. The stripe is per service instance, so stampede protection holds for the singleton the container registers, not across two hand-constructed instances sharing one IMemoryCache.

⬅ Authentication & Authorization • Index • Notifications (Push + In-App Inbox + Email) ➡