All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog
- Fail-safe (per policy, off by default). On an
InMemoryorInMemoryRediscache, aGetOrAddwhose generator throws, or runs pastFailSafeTimeout, returns the value the node last held for the key; a late generator finishes in the background and announces the value it writes to the other nodes. A later miss does not wait for it and runs a generator of its own, so a slow source may see more calls.FailSafeEnabledturns it on,FailSafeMaxStaleAge(default 1 day) bounds the value's age,FailSafeCooldown(default 30 s) serves it without retrying after a fallback, andFailSafeTimeoutis the soft timeout.GeneratedValue<T>.SkipFailSafekeeps one value out. The value is never written to Redis and is dropped on any removal, peer event or lost event. WithSizeLimit, the one limit covers the local entries and these values: a value takes its entry's size when that entry expires, at low priority, and a full cache does not keep it. Once a cache has used fail-safe, the local tier's statistics (entry count, hits, misses) include these values and their lookups, and a customIMemoryCacheFactorycache receives keys that are not strings. BatchGetOrAdd, hash caches and the Redis-only provider ignore it. See Resilience.
GeneratedValue<T>equality andToStringincludeSkipFailSafe. Two values that differ only in it are no longer equal.
-
UiPath.Caching.MessagePack, a MessagePack value serializer.AddMessagePackSerializer()registers it asmessagepack, and a policy opts in per policy withSerializer.Write = "messagepack"; every other policy keeps writing JSON. It writes format id0x02, or0x03when the value's MessagePack bytes reachCompressionThresholdBytes(default 1024) and LZ4 compression makes them smaller, so an incompressible value stays0x02; it uses MessagePack's own LZ4 and adds no dependency. The default options are the contractless resolver withMessagePackSecurity.UntrustedData, andSerializerOptionsreplaces them.MaxDecompressedBytesdefaults to 64 MiB: deserializing can allocate several times the decompressed size, so size it to available memory. Key types MessagePack has no collision-resistant comparer for (TimeSpan,decimal, tuples, custom structs) fall back to the default comparer. Register it on every node and finish that deploy before any policy writes it, since a node that cannot read the format misses and regenerates the value. Like JSON, contractless MessagePack writes property names, so renaming or retyping a property silently loses that data for values written before the change;[MessagePackObject]with[Key]avoids that. The package accepts MessagePack[3.1.12, 4.0). See MessagePack. -
A seam for value serializers.
ICacheValueSerializerandCacheValueFormatsdefine a buffer-based serializer whose output starts with a one-byte format id,AddValueSerializerregisters one by name, andCachePolicy.Serializer(Write,Read,MigrateOnRead) names it per policy.AddValueSerializerthrows at the call for a name used twice on one builder or forjson. A policy that names an unregistered or blank serializer, has an emptyRead, or writes a format itsReadleaves out fails with anOptionsValidationException, as does a serializer whose ids are outside the consumer ranges; these are checked when the policy factory is first resolved, on first cache use rather than at host start. A customICachePolicyFactorywhose policy names an unregistered serializer fails the same way when the Redis provider builds its cache. Serializers the container created are disposed with it, throughDisposeAsyncwhen they only implementIAsyncDisposable, so a factory must return a new instance rather than one resolved from DI. A policy that setsWritemakesRedisCacheandRedisHashCachewrite their values, hash fields and hash metadata with that serializer, and every read picks the serializer by the format id, whatever the policy writes. A value in a format no registered serializer owns is a miss, counted incache.serializer.unreadableand removed only if the key still holds the bytes that were read, so a newer value written in between survives; a hash with such a field misses whole and is left in place. A value whose registered serializer throws is a logged miss and the key stays, like one that is not headered and fails to parse as JSON, because the bytes may be good for another version of the type during a rolling deploy; this departs from the design spec, which removed it, and anOutOfMemoryExceptionfrom its payload is never swallowed, while one from a value with no header (JSON) is a logged miss as it is with no serializer registered.RedisHashCache.TryDecodeFieldsnow treats any exception exceptOutOfMemoryExceptionas a refresh, since a registered serializer can throw any type, where it caught four. A node with no serializer registered logs theJsonExceptionand keeps the key. A policy passed to a single call that names an unregistered serializer throwsOptionsValidationExceptionbefore anything is written. The reader only looks for a header with the default JSON serializer or under a policy whose effectiveWriteis a serializer other thanjson(Readdoes not count), sobyte[]values stored throughRawByteSerializerProxyorAddDistributedCacheare never reinterpreted. A policy that sets no serializer, or onlyRead, takes the default policy'sWrite. The default stays JSON with no header, andAddDistributedCacheignoresSerializer: its own policy always writes and reads JSON with no migration, so the caller's bytes never get a format header. A hash write that names a serializer leaves_metadata_out when the metadata is empty and nulls are not cached, and aHashReplaceone deletes the field an earlier write left. Hash system field names are compared as bytes instead of strings. See value serializers and rolling a serializer out. -
A binary event formatter for
UiPath.Caching.MessagePack.AddMessagePackEvents(write)reads JSON and binary events, told apart by the first byte (0x02for binary).write: falsestill writes JSON, byte for byte what the default formatter writes, andwrite: truewrites a MessagePack map with integer keys, a binary GUID id, an integer event type and the peer fields as raw bytes. Switch in two deploys, read both first and write binary second, and never retire the JSON decoder; every node must be on 3.2.0 or later before any writes binary, since an older one skips binary events, logging a warning for every 100th and tracking telemetry, but never treats one as a loss. It wraps the JSON formatter that would otherwise be registered,AddCloudEventsincluded in either order, so the JSON wire is unchanged. See MessagePack events.
- A policy's non-JSON
Serializer.Writeis written only while every node can read it. With the newRedisCacheOptions.FormatNegotiation(ModeAutoby default), each node advertises the formats it reads in a Redis hash stamped with the server's clock and reads the node list, with the Streams consumer groups, on a 15-second timer, off the read and write paths. A policy writes its format once every fresh advertisement lists it, no live node is unaccounted for, and that has held forUpgradeHold(an hour by default; zero switches at once); a node that cannot read it stops the writes at once, and an unreadable node list keeps the decision forMaxViewAge(two minutes), then writes JSON. A node with a serializer registered advertises what it reads in either mode, even if none of its policies writes a non-JSON format, so a reader-only orForcenode never blocks the writers (an app with no Streams transport neither advertises nor reads advertisements); inAutoit decides for every registered serializer, so a policy built at the call site is held to it too. An advertisement outlives the consumer group of a node that crashed, and a node that stops writes a departing advertisement, so a node that leaves never drops the fleet to JSON or restarts the hold, which a join or a restart does. After a Redis outage the decision is kept for two advertise intervals while peers advertise again.AssumeAllNodesCanReadcovers only nodes that advertise nothing; with no Streams transport it switches after the hold with nothing that can stop it. An advertisement older than its group's last read does not account for the group, so a restart under the same id is seen at once, and a node list that fails to read restarts the hold. The advertisement follows what a node's reads really do: on a custom proxy a policy that writes no non-JSON format advertises JSON only, which keeps writers on JSON, and a policy on such a proxy always writes its configured format, since raw bytes have no JSON to fall back to and could read back as a header. Advertise and node list reads run on their own intervals, and a topic's stream is forgotten when the topic is removed. An app with no serializer registered does nothing new. An app that cannot see its peers (BroadcastEnabledoff, or Pub/Sub only) writes JSON unlessAssumeAllNodesCanReadis set.Mode = Forcewrites exactly what each policy configures, as before. New metricscache.format.effective,cache.format.fallback,cache.format.nodesandcache.format.view.age. See choosing when a format is written. - An event in a known format that cannot be decoded is a topic loss. The Streams reader acknowledges the entry and reports a loss, and counts such an entry as one it would have acted on when it checks what a new group skipped; the Pub/Sub reader expires through the coalesced dropped-event path, off the delivery thread, so it holds for caches that keep their tier over a subscription gap. The Streams reader reports once per batch. This applies to a body whose first byte is
0x02,0x03or a consumer format id (0x10-0x1E,0x1F), such as a binary event on a node that cannot read it. Any other body that does not decode, another producer's first byte included, is still skipped as junk. - Cache event properties are read as typed values. The built-in event formatters parse
_version_, the expirations, the metadata and the peer fields straight intolong,DateTimeOffset, string dictionaries and byte arrays instead of aJsonElementthat was parsed again by the value serializer, which saves a clone, a box and a second parse per property of a peer-update event. The event bytes on the wire are unchanged. A customISerializerProxy<byte[]>no longer sees these properties inTryDeserialize(object)when the built-in formatters decode the event. - Decoded
ICacheEvent.Data.Propertieshold typed values. From the built-in formatter and the CloudEvents fast path they arelong,DateTimeOffset,Dictionary<string, string?>and byte-valued peer fields instead ofJsonElement, so a custom subscriber that casts a property toJsonElementmust handle those types. - Each rehydration does one shared-tier read before it generates. The read counts in the Redis read metrics, and
cache.rehydrate.succeededno longer counts runs that adopted a fresh shared copy (cache.rehydrate.adopteddoes); a batch that adopted some keys adds anadoptedtag with their count tosucceeded. Dashboards that countsucceededas refresh volume should addadopted.
- Rehydration adopts a fresh shared value instead of generating it again. A node that wins the per-key lock now reads the key from the shared tier first. When that copy is not yet past the rehydrate threshold (more than
1 - Thresholdof the duration left), as after another node refreshed it, the node keeps it locally and skips the generator;cache.rehydrate.adoptedis tracked instead ofcache.rehydrate.succeeded. A missing, aged or deadline-less copy, a copy that could not be kept because the key changed meanwhile, a failed read, or a read slower than a quarter of the rehydrate timeout (2 s at most, added on top of the timeout) runs the generator as before, and a failed or slow read is reported ascache.rehydrate.adopt_read_failedwith areasonoferrorortimeout. Adoption needs the built-in Redis caches, which take that read as one snapshot of value and remaining lifetime in a single transaction on the primary, so the shared copy is never an old value with a new lifetime; other inner caches generate as before. A batch does the same per key and generates only the rest; if its generator then fails, only the generated keys count as failed and keep their cooldown. The lock of each key in a batch now lasts the run timeout plus that key's own cooldown, not the worst key's.
- A code fix for the two 3.1 interpolated-key compile errors. Under C# 12 or older, a constant interpolated key (
$"fixed",$"{Const}:x") is ambiguous (CS0121): the fix makes it a plain string ("fixed",Const + ":x"). In an expression tree, such as a MoqSetuplambda, an interpolated key does not compile (CS8952): the fix wraps it inFormattableString.Invariant($"user:{id}"), which keeps the key text. Fix All applies either to a document, project or solution. It ships inUiPath.Caching.Abstractionswith the UIPCACHE001 fix. - Warning for an uncapped local tier.
InMemoryRedislogs one warning, when the provider is first created, if neitherLocalMaxExpirationnorDefaultCachePolicy.LocalExpirationis set (TimeSpan.MaxValuecounts as unset), since a local copy can then outlive what the application expects if a peer's invalidation is lost.
- Dependency floors. Unchanged from 3.1.0. Only the test pins in
Directory.Packages.propsmoved. - A Redis Streams entry and its doorbell go out in one command, and an array remove announces its keys together. While no doorbell is in flight, a publish on the stream's default channel runs the entry and its doorbell in one Lua script, so the doorbell costs no command of its own and, on a cluster, peers are woken a round trip sooner; a publish while a doorbell is in flight adds a plain entry and folds its ring into the next one. A server that refuses scripts (ACL, scripting disabled, or no PUBLISH from a script) turns the script off for that topic, which then sends the two commands as before; a busy or loading server does not turn it off, a script that adds the entry but may not publish keeps that one entry and rings with a doorbell of its own, a connection that prefixes keys or channels sends the two commands too, and a failed add sends no doorbell.
RemoveAsyncwith an array of keys now starts every key's invalidation together instead of one after another, so the batch costs one round trip and its doorbells fold into one; each key is still announced and logged on its own, and a key whose announcement fails is reported as a failed remove without keeping the others from being announced. - No read mark when
RefreshLocalOnPeerWriteis off. A local hit no longer marks the entry as read when the policy setsRefreshLocalOnPeerWriteto false, which saves a clock read and a write per hit.
- Interpolated keys format with the invariant culture.
CacheKeyHandlerformatted holes with the current culture, so nodes with different cultures built different keys for one value and missed each other's invalidations; a negative number under a culture whose minus sign is U+2212 was one case. Keys whose holes are culture-sensitive, for exampleDateTime,DateTimeOffset,DateOnly,decimal,double,float, and negative numbers under some cultures, can change once on upgrade, but only when the node's culture formats that value differently from the invariant culture (adoubleunder en-US does not change; dates under en-US and numbers under de-DE do). A 3.1.0 node and a 3.1.1 node build different keys for those values until every node runs 3.1.1, so while both run, an invalidation from one version does not reach the entries the other stored under its key; those stay stale until they expire or are removed or overwritten, and an entry with no expiry can stay stale indefinitely, which matters for caches such as permissions. Astringkey built with$"..."for an entry also read through an interpolated key must now useFormattableString.Invariantorstring.Create(CultureInfo.InvariantCulture, ...)to keep matching. - The Redis profiler no longer starts its flush timer before its dependencies are set. A constructor that stalled past the first flush interval made the flush loop fail with a
NullReferenceException, stop flushing, and rethrow onDispose. - No false stream loss on Redis 6 after a lost group create. A create at the head of an empty stream whose reply was lost may still make the group. When the next
read found that group rather than a retry, a check before the read took the stream's first entry for a trim and cleared the topic's local tier. The reader now records the empty
head when the create fails, as it already did for a create at
0-0. - A queued subscribe tick no longer retries a disposed connector. A disposed connector is no longer retried by a subscribe tick already queued on the thread pool.
- The large-value audit logs writes, as documented. With
AuditEnabled, a value overLargeValueThresholdlogged aWarningon every Redis read of it, so one large value stored by design warned on every read. Reads no longer warn. Writes now do, where the caller can shrink the value: oneWarningper oversized string value, hash field or hash metadata written byRedisCacheandRedisHashCache, so an app may see warnings it never saw before. The log names the caller's key, so a key masking policy applies as it does elsewhere. A write that only deletes an expired entry is not audited, and aLargeValueThresholdof zero or less turns the hash audit off, as it already did for strings. An app that raisedLargeValueThresholdto quiet the read warnings can lower it again.
- A peer's write drops a local copy nobody read.
RefreshLocalOnPeerWritekeeps and refreshes only a copy a local hit read since it was stored and within its local expiration; any other copy is dropped on a peer's write. TheCachePolicyXML doc and the settings reference now say so, as concepts already did. A test that stores a key, changes the distributed tier behind the cache and then expects the local copy must allow for that drop. - Mocks must set up the
GetOrAdd*members. Code moved from aGetAsyncandSetAsyncpair toGetOrAddAsynccalls a member a test mock may not have set up, and a loose mock returns the default (null) without running the generator. Set up the members listed in choosing a GetOrAdd overload, or test against the in-memory provider. RedisStreamsTopicOptions.NotifyMinInterval: keep it at zero, the default since 3.1.0, for any cache where a stale entry is wrong, such as permissions or addresses that change often. A positive value lets other nodes serve the old value for up to that long. The broadcast guide now has a doorbell spacing section, and the 3.1.0 entry no longer says 25 ms.
-
GetOrAddResultAsync. ReturnsCacheResult<T>(Value, Expiration, WasGenerated)so a caller knows whether its own generator produced the value:falsefor a hit and for a call that waited on a concurrent caller's generation.Expirationis the entry's stored expiration (null when unknown, when the entry has no expiry, or when nothing was stored). Available onICacheandICache<T>in the closure, state and owner-and-argument forms; a cache outside the library gets a default that wraps the generator, at two allocations per call for the closure form and four for the state and owner-and-argument forms, plus a boxed state machine when the call completes asynchronously; it reportsExpirationonly for theDateTimeOffsetform when its generator ran and returned a value other than null or default. -
Owner and argument for a static generator.
cache.GetOrAddAsync($"user:{id}", this, id, static (self, id, ct) => self.LoadAsync(id, ct), policy, ct)hands the generator an owner and one argument, so a call that needsthisand one value has no closure and no tuple. Extensions onICache,ICache<T>,IHashCacheandIHashCache<T>for every stateGetOrAdd*operation andGetOrAddResultAsync, withCacheKeyand interpolated keys; a hit allocates nothing. -
Interpolated keys on every
ICacheandIHashCacheoperation. Pass$"{tenantId}:{userId}"where a key goes, onICache,ICache<T>,IHashCacheandIHashCache<T>(andNullCache,NullHashCache): the text is written to a 256-character stack buffer (a longer key rents fromArrayPool), so a local hit allocates nothing. Values format in the current culture, as in any string interpolation. A string ordefaultkey binds to theCacheKeymember as before; a constant interpolated string binds to the interpolated member under C# 13 (see Changed). Implementers addISpanKeyCache,ISpanKeyCache<T>,ISpanKeyHashCacheorISpanKeyHashCache<T>to serve the key without a string; any other cache gets theCacheKeymember. -
RefreshLocalOnPeerWrite(per policy, on by default). When a peer writes a key held in the local tier and read within its policy's local expiration, the node keeps serving its copy and refreshes it from the distributed tier in the background instead of dropping it. An entry no local read has hit in that time (or since it was stored) is dropped as before, with no master read; a refreshed copy keeps the last read time of the one it replaces. Removals, topic-wide invalidations, subscription gaps and a disconnected distributed tier still drop at once. Set it tofalsefor data that must be read after a peer's write, such as revocations. Outcomes are reported as the metricscache.peer_refresh.started,.kept,.discarded,.dropped(tagreason, includingidle) and.read_ms, per drained batch; a drop with reasontimed_outorfailedalso raises an event.InMemoryRedisCacheOptions.Timeoutnow rejects zero and negative values other thanTimeout.InfiniteTimeSpanat registration, which leaves the refresh's queue wait and read unbounded. -
RefreshLocalRetryWindow(per policy, default 100 ms). For this long after the first peer write a held copy misses, a refresh that could not settle (a peer wrote the key again, a key sharing its stripe changed under the read, its read timed out or waited pastTimeout) is read again and the copy stays served, instead of being dropped so that the next call reads the distributed tier on the request path. In a multi-node load test with peers writing a hot key many times a second, about 1.7 % of requests found their copy dropped this way and paid a Redis read in the p98-p99.5 band. The copy is served stale for at most the window plus twoTimeouts, so the default leaves the documented bound of about 4 xTimeoutunchanged. Zero drops after one re-read, as before. A failed read, a key gone from the distributed tier, a peer's removal, losses and a disconnected tier still drop at once. -
cache.background_write.fill_refusedmetric (tagreason:changed,in_flightoruntracked), counted each time a local fill from a distributed read is refused because the key's stripe changed since the read began, a write of the key or stripe was in flight, or the read began before counting started. -
RedisStreamsTopicOptions.AutoAck(off by default). Reads withNOACKand sends noXACK, so the group keeps no pending list and the pending-entry recovery is skipped after the entries an earlier run left pending are read once at start. A read that fails may have been delivered, so it is reported as missed events and the local tier is cleared rather than left stale, when a failure streak starts and again when a read ends it. -
InMemoryRedisCacheOptions.PeerFieldUpdates(off by default;PeerFieldUpdateMaxFields, 16, andPeerFieldUpdateMaxBytes, 1024). A smallHashReplacewrite tells the other nodes which fields it wrote, and a node whose local copy of the hash is exactly one write behind (its own writes that the copy already holds do not count, and the copy waits for the events of the other nodes' writes that landed before them) adds them to a copy of its own instead of dropping it and reading the whole hash on its next call. A copy that is further behind, has no version, or a write that is a replacement of the key, a removal, over the limits or by a node that does not count, is dropped as before, except an event that is no newer than the copy and of the same epoch of the hash, which the copy already has and which is ignored (a late event used to drop the copy, and the read it caused was then hit by the next late event). The count's high bits name the epoch, drawn when a write makes the hash, so a hash made again after a removal, an expiry or an eviction is never taken for an earlier state of the old one. A failover that loses acknowledged writes can move the count backwards inside one epoch; the events of the writes it repeats are then ignored rather than dropped, until the reconnect clears the local tier or the TTL ends. Every write of a hash then also counts the hash's writes in a reserved_version_field (hidden from reads, rejected on writes), in the write's own transaction, so the TTL and the fields stay atomic. ARemoveFieldsAsyncthat empties a hash leaves the count behind until the key expires. Turn it on once every node that writes the hashes runs this version. -
RedisStreamsTopicOptions.NotifyMinInterval. The least time between two doorbells, zero by default and at most 1 s. Rings during the interval fold into the next doorbell, so a burst of writes wakes each consumer at most once per interval instead of once per write; the first ring after a quiet period still goes out at once. -
RemoveFieldsAsynconIHashCacheandIHashCache<T>. Removes the named fields withHDEL(in commands ofRedisCacheOptions.HashFieldBatchSizefields, 1000 by default, all in flight together), drops the hash from the local tier of the writing node, and announces the key as removed, so every node, an older one too, drops its whole local copy of the hash: an entry is replaced whole, never patched, which keeps a read that races the removal from bringing a removed field back. A hash left without fields is gone. A reserved_word_field name is rejected, as on a write. TheCacheKeyoverload is asealedmember served byISpanKeyHashCacheand its<T>sibling, on the library's hash caches andHashCache<T>; any other hash cache throwsNotSupportedException, as does anISpanKeyHashCachethat does not override it. -
RemoveManyAsyncandSetManyAsynconICache,ICache<T>,IHashCacheandIHashCache<T>(sealedmembers served byISpanKeyCache,ISpanKeyCache<T>,ISpanKeyHashCacheandISpanKeyHashCache<T>on the library's caches,Cache<T>andHashCache<T>, which gain them with default bodies so an existing implementation still loads; any other cache gets the same calls through its single-key members). They take anIEnumerableand return the keys that failed, empty when all succeeded. One command per key, so noCROSSSLOTon a cluster, with the commands of a chunk all in flight before any is awaited and then the chunk's events likewise: about two round trips of wall time per chunk, whatever the key count or slots. The input is read in chunks (InMemoryRedisCacheOptions.BatchChunkSize, 500;BatchConcurrentChunks, 2), so memory stays with the chunk and a million keys is fine; only the failures are kept. A failure never stops the rest. The call is awaited underBackgroundDistributedWritetoo, and waits for the pending background writes of its keys, and only those. A removal drops L1 first and is announced even when its delete failed, asRemoveAsyncdoes; a set whose write failed gets no event. The caller's cancellation throws, between chunks and within one; what ran stays done. A key named twice in a chunk ends as its writes in order would leave it; across chunks, which run two at a time, their order is not set.InMemoryRedisCacheOptions.BatchTopicInvalidationThreshold(off by default) replaces the per-key events of an input of known size above it by oneTopicInvalidatedevent after the writes, which makes every node drop its local tier of the topic, for every cache sharing it, and is counted as thecache.batch.topic_invalidationevent. A node that does not know the event ignores it: turn the threshold on once all nodes run this version. If that event fails, every key of the call is returned. The hashSetManyAsynctakes oneHashCacheEntryOptionsfor all its hashes; the overload without one replaces each key.RemoveAsync(CacheKey[])and the batchSetAsyncare separate calls, and on a cluster they too run one command per slot (see the slot entry under Fixed). -
CachePolicy.BackgroundDistributedWrite. Opt-in per policy (Caching:Policies, or the default policy for the whole cache): single-keySetAsyncand the write after aGetOrAddAsyncmiss, on the cache and on the hash cache, return once the value is in L1, and the L2 write, then a set's event, run detached. The value is local forLocalMaxExpirationDisconnecteduntil the L2 write succeeds, then for its normal lifetime; writes to one key keep their order;InMemoryRedisCacheOptions.MaxBackgroundWrites(default 8192) bounds them, with the foreground as the overflow;BackgroundWriteDrainTimeoutbounds the wait for them when the cache is disposed (Timeout.InfiniteTimeSpanwaits for them all; those it cancels stay local only and are counted under thedrain_cancelledstage). Batch writes,RemoveAsync,TryAddAsync, refresh, metadata writes and a fill under the distributed lock are unchanged, and wait for the background writes of their key; a background write in turn waits for every write of its key issued before it, and an awaited write that lands after a newer background one leaves that one's value local, as does an L2 read that began before a write or removal of the key; such a read is not kept locally, nor is one of a key sharing the written key's stripe (one in 1024), and the next read keeps it. The caller's token ends the wait. TheIDistributedCacheadapter always writes in the foreground, as its payload may be memory the caller reclaims on return. A failed background step is logged and counted as thecache.background_write.failedevent. -
IPolicyDefaults.ICacheFactory.PolicyFactorymoves to this interface, whichCacheFactoryimplements, andCache<T>andHashCache<T>read it from a factory that implements it.ICacheFactoryis left with no default member, sonew Cache<T>(factory)over an NSubstitute substitute no longer throwsArgumentNullExceptionon Castle.Core 5.2.1, which fails on a call to a default interface member (castleproject/Core#684). -
State overloads on the hash caches.
IHashCacheandIHashCache<T>gainGetOrAddAsyncmembers that take aTState statebefore aFunc<TState, CancellationToken, Task<IDictionary<string, T?>>>generator, for every expiration, set-option and policy variant of the closure ones (the policy-lessIHashCacheones inHashCacheExtensions). TheCacheKeyones are plain interface members, and an interpolated key goes toISpanKeyHashCache(ISpanKeyHashCache<T>), which gains the same members, or else theCacheKeystate member. Every library hash cache, Redis included, hands the state to the generator without a closure. -
A state overload of
GetOrAddWithExpirationAsynconICacheandICache<T>(the policy-lessICacheone inGeneratedExpirationExtensions), a plain member every cache implements; the library's caches, Redis included, hand the state to the generator without a closure. -
A batch
GetOrAddAsyncwith one argument for the whole call.GetOrAddAsync<T, TState, TArg>(entries, argument, generator, ...)onICache(and<TState, TArg>onICache<T>), for each expiration variant of the batch overload, hands the generatorargumentbefore the states of the keys that missed, so it can be static. The argument is not a per-entry state. It is a member every cache implements: the library's multilayer and in-memory caches andCache<T>bind a closure only for a miss or a rehydrate, and Redis andNullCachehand the argument to the generator without one.None of the new overloads takes a call written for an existing one: a generator that throws or returns
defaulthas no natural type and cannot be a state or an argument, and where both apply the closure member is the more specific (OverloadShapeTests).Cache<T>,HashCache<T>,NullCacheandNullHashCachedeclare the new overloads as public members too, so a call on a public cache class takes them (ConcreteCacheCallShapeTests). -
Analyzer
UIPCACHE001: a generator that allocates on every call.UiPath.Caching.Abstractionsnow ships an analyzer and code fix (underanalyzers/dotnet/cs; a project that referencesUiPath.Cachinggets them too). It reports, at Info severity, a generator passed toGetOrAddAsyncorGetOrAddWithExpirationAsynconICache,IHashCache,ISpanKeyCache,ISpanKeyHashCacheand their<T>forms, or a class that implements one, that capturesthis, a local or a parameter (itself or through a local function), or is an instance method group, when a state (or batch argument) overload exists for the call; and a capturing lambda passed to a state overload. The fix, Pass captured values as state, moves the call to that overload with astaticlambda: one capture is the state (thisbecomesself), two become an owner and an argument (falling back to a named tuple when no such overload binds, such as anICachecall without a policy or a batch call), three or more become a tuple with PascalCase element names ((Self: this, TenantId: tenantId, OrderId: orderId), read ass.TenantId), a captured variable assigned before the call is passed as it is, and spelled type arguments get the state's type. It is not offered when the move could change what the generator reads (a captured variable assigned in or after the call's statement, inside the lambda or another function, in a loop around the call, through arefalias, or in a method with a label or agoto case,base, a capturing local function), and only when the rewritten call compiles in place without an error. The blockingGetOrAddwrappers inCacheSyncExtensionsandHashCacheSyncExtensionsnow pass their generator as state themselves. The plain lambda stays the default, so the rule is Info; on a .NET 10 hot path, setdotnet_diagnostic.UIPCACHE001.severity = warningin.editorconfigso a new capturing lambda shows in the build. On .NET 8 keep it at Info: there the owner-and-argument and tuple forms the fix writes for two or more captures are slower on a hit than the closure. It has a category of its own,UiPath.Caching, so raising a category such asPerformanceleaves it alone. Seedocs/how-to/choosing-a-get-or-add-overload.md. -
RedisConnectionOptions.DedicatedThreads(off by default). StackExchange.Redis 3.x reads replies on thread-pool threads, where 2.x had a dedicated thread; set it totrueto have each interactive connection read and write on threads of its own, so commands keep flowing while the pool is starved, at a reader and a writer thread per connection. The pub/sub subscription connection stays on the thread pool. It sets the StackExchange.RedisDedicatedThreadsfeature flag before the cache connects; the flag is read when a socket opens, so it applies to every StackExchange.Redis socket the process opens afterwards, not only the cache's, leaves sockets already open as they are until they reconnect, and is never reset.
-
Dependency floors. What a consumer's restore has to satisfy, taken from the packed packages:
Package 3.0.0 3.1.0 StackExchange.Redis(UiPath.Caching,UiPath.Caching.Queue)3.3.1 3.4.29 Microsoft.Extensions.*on net10.0 (every package)10.0.12 10.0.13 Microsoft.Extensions.Logging.Abstractionson net8.0 (UiPath.Caching,UiPath.Caching.CloudEvents,UiPath.Caching.Polly,UiPath.Caching.Queue)10.0.12 10.0.13 Microsoft.Extensions.Optionson net8.0 (UiPath.Caching.Azure)10.0.12 10.0.13 The Polly and
Microsoft.Azure.StackExchangeRedisfloors are unchanged.StackExchange.Redis3.4.29 asks forMicrosoft.Extensions.Logging.Abstractions10.0.13 on every target, net8.0 included, so that floor holds whatever the other floors are, and only going back toStackExchange.Redis3.3.1 would lower it. A project that pins theMicrosoft.Extensionsfamily below 10.0.13, directly or through central package management, fails restore with NU1605 (detected package downgrade); raise its pins to 10.0.13 or later. -
A read on Redis below 7.0 costs one round trip, not three. Without the Redis 7.0 script, every read in use is still checked for a trim past the group's position, but the
XINFO STREAMnow goes out with theXREADGROUPbehind it on the same connection to the primary, so the state it reports is the one the read starts from and no round trip is added; theXINFO GROUPSthat asks the server for the group's position runs once aPollInterval, after a reconnect and after a full batch, as with the script, and in between the check compares against the last id this node read. A doorbell-woken read went fromXINFO,XINFO,XREADGROUPawaited in turn to one pipelined round trip. The same applies on 7.0 and later when scripts are refused, where the position is still asked of the server on every read. -
Peers see a write sooner on the Redis Streams transport. The doorbell that wakes the other nodes now goes out as soon as the previous one is answered (
NotifyMinIntervaldefaults to zero, was 25 ms), so a burst of writes no longer holds each doorbell up to 25 ms, and with a single primary it is sent behind theXADDon the same connection rather than after its reply, one round trip sooner. One doorbell is in flight per topic and node, so there are never more doorbells than writes, and a consumer reads at most once per round trip whatever the number of rings; refresh reads follow the smaller batches. SetNotifyMinIntervalto space doorbells apart again. -
A Redis Streams consumer woken while a wake-up is pending throws nothing. A doorbell or notify change that arrived while the fetch loop already had a wake-up pending released its semaphore again and caught the
SemaphoreFullException; under IP churn in a consumer app that was about 35 first-chance exceptions a second per process. It now returns before the release, and the wake-ups still collapse to one. -
A small batch allocates a chunk of its own size.
RemoveManyAsyncandSetManyAsync(cache and hash cache) size each key chunk to what is left of a counted input, up toBatchChunkSize, not always toBatchChunkSize: a 10-keyRemoveManyAsyncon the memory tier allocates 1.8 KB, not 9.6 KB. -
Cache<T>array batches copy no keys under the default key strategy. The batchGetAsync,GetOrAddAsync,SetAsyncandRemoveAsyncpass the caller's array on instead of copying it with unchanged keys: a 100-keyGetOrAddAsyncthat hits the local tier allocates 3.4 KB, not 5.8 KB. A custom strategy still composes every key. -
Memory-only read miss. A read miss on a memory-only cache returns without building entry options or a second local lookup.
-
Memory-only GetOrAdd miss. A single-key
GetOrAdd*miss on a memory-only cache generates without an inner read and keeps the value locally without a background-write turn; theGetOrAddandGetOrAddWithExpirationstate overloads also bind no closure. Concurrent callers still share one run. -
The caller that starts a
GetOrAdd*run awaits it directly. A single-key miss that starts the key's shared run awaits the generation's own task, which takes the run out of the single-flight table before it completes; the retry after a batch orTryAddgives up a key it held is left to the callers that joined it. The same goes for a Redis-onlyGetOrAdd*run, and the run locks on itself. A memory-only miss allocates two state machines less (about 400 B), a Redis-only hit about 200 B less. -
A batch
GetOrAdd*whose first key misses locally allocates no result array for it. The check for an all-local hit filled an array the size of the batch while it probed; it now probes the first key before allocating, so a cold batch no longer discards that array (1.6 KB at 100 keys, 160 KB at 10,000). A full hit costs what it did. -
Per-key read telemetry builds its tags inline. With
KeyReadTelemetryEnabled, a reported read no longer allocates two five-tag arrays and copies one into the tags of each dependency: each outcome's tags are built once, on its first key. A reported read allocates 208 B less. -
A local hit on a layered cache reads a cheaper clock. The read mark that peer refresh keeps per entry takes its second from
Environment.TickCount64when the cache runs onTimeProvider.System, not from a timestamp and a 64-bit division; an injectedTimeProvideris still read as before. The clock read went from about 35 ns to 2 ns of each local hit onInMemoryRedis. -
Breaking at C# 12 and older: a constant interpolated key is ambiguous. With C# 12 or older (the default of net8.0),
$"fixed"and$"{Const}:x"report CS0121 between theCacheKeyand the interpolated-key members. Use a plain string ("fixed",Const + ":x"), or C# 13 (.NET 9 SDK, or<LangVersion>13</LangVersion>), where they bind to the interpolated member. A non-constant$"{s}:{id}", a string and a variable bind the same at every language version. A baredefaultbehaves as on 3.0: it binds to theCacheKeymember at C# 13, and at C# 12 it is ambiguous with the batch overload onICacheandICache<T>, as before. -
Breaking: an interpolated key no longer compiles inside an expression tree, such as a Moq
SetuporVerifylambda. On 3.0,mock.Setup(c => c.GetAsync<string>($"user:{id}", null, default))converted the string toCacheKey; it now binds to the interpolated-key member, which an expression tree cannot hold (CS8952). Inside the lambda, pass a string ("user:" + id, or astring key = $"user:{id}"built before it), orIt.IsAny<CacheKey>(). -
A peer's write refreshes the local copy by default (was a drop). This changes the read-after-peer-write contract: after another node writes a key it has read, this node serves its old copy until the background refresh lands (typically one round trip, at most about 4 x
Timeoutwith the one re-read) instead of reading the new value on its next call. SetRefreshLocalOnPeerWrite: falseon a policy to keep the drop for that data. -
InMemoryRedisCacheOptions.Timeoutof zero or negative now fails at registration.Timeout.InfiniteTimeSpanis still accepted and leaves the peer refresh's queue wait and read unbounded. -
Reads go to the master by default (was
PreferReplica). This is a default behavior change: unless you opt in, every Redis read (values, hashes, sets, TTLs, read scripts) is sent to the master. On an Azure Redis 6 cluster a replica round trip measured about 3 times the master's (1.6 ms against 0.55 ms), and a replica that still holds a key the master has removed could refill an entry with stale data right after an invalidation. SetRedisCacheOptions.ReadFromtoReplicato read from replicas as before; it isMasterby default. WithReplica, a read of a key this node wrote or removed withinRedisCacheOptions.MasterReadWindow(1 second by default; set it above the expected replica lag), or heard an invalidation for through a live local entry, still goes to the master. A fire-and-forget TTL write (AwaitRefreshoff) starts the window when it is queued. A key with no local entry is not guarded against another node's write, and neither is a lost-events clear on a node holding no local entries. -
Breaking for implementers of
IHashCache,IHashCache<T>,ISpanKeyHashCacheandISpanKeyHashCache<T>. The stateGetOrAddAsyncoverloads are now members to implement, notsealeddefaults over the closure ones. A mock ofIHashCacheorIHashCache<T>must set up the state member itself: a state call (and theHashCacheSyncExtensionsGetOrAddonIHashCache<T>, which calls it) no longer falls back to the closure overload's setup.RedisHashCachenow throwsArgumentNullExceptionfor anullgenerator from theGetOrAddAsynccall itself, as the other caches do, instead of from the task it returns. -
Breaking for implementers and mocks of
ICacheandICache<T>:IStatefulCacheandIGeneratedExpirationCacheare folded into them.IStatefulCache,IStatefulCache<T>,IGeneratedExpirationCacheandIGeneratedExpirationCache<T>, which shipped in 3.0, are removed. Their members, theCacheKeystateGetOrAddAsyncoverloads andGetOrAddWithExpirationAsyncwith and without state, are now members ofICacheandICache<T>to implement, notsealeddefaults; an interpolated key stays asealedmember that callsISpanKeyCache(ISpanKeyCache<T>), whose implementers already provide the span forms, or else theCacheKeymember. A cache outside the library implements the new members; one that implemented the removed interfaces drops them from its base list and keeps its methods. A mock ofICacheorICache<T>must set up the member it is called through: a state call (and theCacheSyncExtensionsGetOrAdd, which calls the stateGetOrAddAsync) no longer falls back to the closure overload's setup, andGetOrAddWithExpirationAsyncno longer reads throughGetCacheEntryAsync(GetAsyncandContainsAsynconICache<T>) and writes throughSetAsync.GeneratedExpirationExtensionsandStatefulCacheExtensionskeep their policy-less overloads, which call the members. Code that testedcache is IStatefulCacheorcache is IGeneratedExpirationCachedrops the test: everyICachehas the members. The batchGetOrAddAsyncwith an argument is folded the same way: its three members onICacheandICache<T>are to implement, and a mock must set them up, since a call (and the multi-keyCacheSyncExtensions.GetOrAdd, which calls it) no longer falls back to the batch closure overload's setup. -
StackExchange.Redis 3.4.29 (was 3.3.1). It fixes a corrupted reply stream: a connection that reused a read-buffer segment another connection had released (3.3.1 and 3.4.20) kept that segment's old offset, so it read replies at the wrong position. It also fixes transactions on an idle connection being torn down as a dead socket when the replies are slower than one heartbeat (the hash writes are
MULTI/EXEC), andIBatchcommands that never completed after a connection drop. Commands that a dropped connection fails now throwRedisConnectionExceptioninstead of a raw transport or cancellation exception. Under RESP3 (the Azure Entra default) pub/sub now uses its own connection, opened at the first subscribe, so a server sees one more client per node.Microsoft.Extensions.Logging.Abstractionsrises to 10.0.13, the floor StackExchange.Redis 3.4.29 declares. -
RedisStreamsTopicOptions.PollBatchSizedefaults to 1024 instead of 4096. It is theCOUNTof eachXREADGROUP, and the reply shares the cache's connection: the commands behind it wait for it, and with a shortsyncTimeouton a small server a 4096-entry reply of a node catching up could take most of the timeout by itself. A full batch is read again at once, so catching up costs a round trip per 1024 entries. APollBatchSizeset in configuration is kept. The documentation no longer saysLimitcaps a read: neither the reader nor the publisher uses it. -
The Redis Streams consumer polls every 5 s while its notify doorbell is live, unless
PollIntervalis set.RedisStreamsTopicOptions.NotifiedPollInterval(TimeSpan?, bound from the same section and per topic) is the cadence while the doorbell subscription is confirmed live. Unset, it is 5 s whenPollIntervalwas not set, andPollIntervalwhen it was, so an app that configuredPollIntervalkeeps its cadence. APollIntervalkey in configuration counts as set even at its 250 ms default, and a global one counts as set for every topic. OnlyAddRedisStreams(sectionName)and theTopics[]entries keep an absent key unset: an app that binds the options itself (AddRedisStreams(o => section.Bind(o)),services.Configure<RedisStreamsTopicOptions>(section),ConfigureRedisStreamsTopic(name, o => section.Bind(o))) counts as having set it, so setNotifiedPollIntervalexplicitly there for the long cadence. A reader takes the long interval from its own subscription, so entries from a writer that does not ring the doorbell (NotifyEnabled: false, another app sharing the stream, a version from before the doorbell) reach it up toNotifiedPollIntervallate; where some writers do not ring, setNotifiedPollIntervaltoPollInterval, or keepPollIntervalset. A restore of the subscription connection reads once, since a ring sent before the subscription is taken again is lost.PollIntervalstays the cadence before the first subscribe, after a forced reconnect until the topic subscribes again, while a subscription connection is down, when the server refuses the subscription, and withNotifyEnabled: false. A set value must be positive and at leastPollInterval(OptionsValidationExceptionfromAddRedisStreams, and when a topic with an override is made). A subscription connection failing ends a wait in progress at the long interval; a failed command connection does not. Failure retries and theXINFO GROUPSposition check stay onPollInterval. Idle cost per process with 3 topics against a local Redis: 44.4 server-executed commands a second at 250 ms, 12.0 at 1 s, 6.0 at 2 s, 2.4 at 5 s, 1.2 at 10 s; invalidation visibility with the doorbell is the same at each (median 14 ms, 90th percentile under 19 ms). What the long interval costs is the window left by a doorbell lost while its subscription still looks live (a droppedPUBLISH): up to oneNotifiedPollIntervalinstead of onePollInterval. 5 s is where the saving levels off. SetNotifiedPollIntervaltoPollIntervalfor the old cadence. -
A hash of many fields no longer goes to Redis in one command. On
RedisHashCache, withRedisCacheOptions.HashFieldBatchSize(1000) fields per command: a write of more fields is split intoHSETcommands in flight together. AKeyReplacewrite fills a staging key on the slot of the key and renames it over the key, so it still takes the old hash's place at once and expires as before (theMULTI/EXECit replaces held every field in one command); aHashReplacemerge goes straight into the hash and is not atomic across its chunks. A staging key left by a crash expires on its own, and one whose slot cannot be matched to the key's (a prefix with a key that has no hash tag, on a cluster) falls back to the single transaction.GetAsync(key, fields)splits a long field list intoHMGETs likewise. A read of the whole hash (GetAsync(key),GetCacheEntryAsync, the read ofGetOrAddAsync) where read scripts run takes a hash of more than ten batches of fields byHSCANpages instead of oneHGETALL; its pages are not one snapshot. Smaller hashes cost what they did. -
A single-key
SetAsyncwrites the value before it publishes the event, as the batch one does; so do the hash cache'sSetAsyncand the single-key and batch rehydrate writes. It published first, so a node the event woke could re-read the old value from L2 and keep it for its whole local lifetime. A single-key write the inner tier refuses sends no event; one it takes whose event fails returnsfalsewith the value in place. A batch rehydration announces every key of a group even when its write reports a failure, as the batchSetAsyncdoes, since a write over several slots may have landed in part. -
More members on the
ISpanKey*capability interfaces.ISpanKeyCacheandISpanKeyCache<T>gainSpan<char>forms ofGetOrAddWithExpirationAsync(with and without state),SetAsync,TimeToLiveAsyncandExpireTimeAsync;ISpanKeyHashCacheandISpanKeyHashCache<T>gainSetAsync,TimeToLiveAsync,ExpireTimeAsync, the field-subsetGetAsyncandGetMetadataAsync. The library's multilayer and in-memory caches, the Redis hash cache,Cache<T>,HashCache<T>,NullCacheandNullHashCacheimplement them; an interpolated key onICacheorIHashCachereaches them, and any other cache is called through itsCacheKeymember. Breaking for an implementation of those interfaces outside the library, which must add the new members. -
The script-free read is now a non-atomic
GETandPTTLpair. A single or batchRedisCacheread sends a pipelinedGETandPTTL, and aRedisHashCacheentry read anHGETALLand aPTTL(one round trip, no MULTI/EXEC), on every Redis version. The pair is not atomic, so a key that expires between them reads as a value without a TTL.ReadScriptsEnabledstaysfalseby default, because theEVAL_ROread cost the server 4 to 15 times the time of a plain read on Azure Managed Redis with no gain in client latency. Set it totrueto read with one script on Redis 7 and later. -
The Redis Streams notify doorbell is on by default, with a cheap wake.
RedisStreamsTopicOptions.NotifyEnablednow defaults totrue: the publisher rings a Pub/Sub channel after everyXADD, so the other nodes read the stream at once instead of at their nextPollIntervaltick. Measured between two hosts on one machine against a local Redis (benchmarksdoorbellmode), aSetAsyncbecame visible to the other host's local tier in 2.7 ms at the median and 3.3 ms at the 99th percentile, against 112 ms at the median and 218 ms at the worst with the poll alone. The poll stays as the safety net. What a broadcast now costs on the server: theXADD, one fire-and-forgetPUBLISH, and on every other node one script (XINFO STREAMandXREADGROUPin one round trip) and oneXACK. The doorbell carries the publisher's consumer name, so a node does not wake for its own ring. Every read is still checked for entries trimmed past the group's position, but a woken node checks against the position it knows, and the check that also asks the server for it (XINFO GROUPS, which grows with the number of nodes) keeps the poll's cadence (once a poll interval, after a reconnect and after a full batch); doorbells that arrive during a read collapse into one more read; and a read that drained the stream waits for the next ring or poll instead of reading again. A node's own entries, which nothing rings for, are read everyMaxLength / 2of its own publishes as well as at the poll, so a burst of them cannot be trimmed unread and reported as a loss. The per-node subscription is one Pub/Sub channel per topic; where the server refuses it (NOPERM, orSUBSCRIBEdisabled) the topic logs one warning and polls only, and a connection error is retried atNotifySubscriberTimeoutwith one warning per streak. SetNotifyEnabled: falseto poll only. On a Redis Cluster a plainPUBLISHis forwarded over the cluster bus to every node;NotifyShardedPubSubkeeps it on the stream's shard where Redis 7.0 and a hash-tagged stream key allow it, and stays off by default because neither can be assumed. -
The state
GetOrAddAsyncandGetOrAddWithExpirationAsyncare interface members. TheCacheKeyones are plain members ofICache,ICache<T>,IHashCacheandIHashCache<T>(see the breaking entry above), and each interface has asealedinterpolated-key sibling: a cache that implements the capability interface (ISpanKeyCache,ISpanKeyHashCacheand their siblings) takes its allocation-free path; any other cache, including a Moq or NSubstitute proxy, is called through itsCacheKeymembers, so a test'sCacheKeysetups answer it. The policy-less state andGetOrAddWithExpirationAsyncoverloads ofICachestay extensions, as the other policy-less overloads do. A class does not inherit an interface's members, soNullCacheadds the policy-bearing stateGetOrAddAsyncoverloads andGetOrAddWithExpirationAsync, and the public caches declare the shapes the removed extensions served. A baredefaultkey binds to theCacheKeymember. -
A Redis write of up to 16 KB allocates one exact-size array. With the built-in JSON serializer, a payload of up to 16 KB is copied into its own array and the writer keeps its pooled buffer for the next write, instead of holding a buffer rented from
ArrayPool<byte>.Shareduntil the write completes. A larger payload still keeps its rented buffer until then. -
DistributedLockSkipReread: a local miss under the distributed lock can read Redis once when the lock is free. Single-keyGetOrAddAsyncreads L2, takes the lock, and reads L2 again. With the option on (IMultilayerCacheOptionsorLockProfile), when the Redis lock is taken at its first attempt, the caller's miss stands for the second read. It is off by default because a peer that stores and releases within that round trip (longer withPreferReplica) is then not seen, and both nodes generate, which the lock is there to prevent. After a wait, a timeout, or with a customIDistributedLock, the read under the lock stays. AnIMultilayerCacheOptionsimplementation outside the library that does not declare it keeps it off. -
A node's own Redis Streams entries are dropped before they are decoded. Every node's consumer group reads every entry, its own included, and an own entry was decoded in full (about 2.2-2.6 KB of JSON,
Uriand dictionary allocations each, about 4.5 MB per periodic backlog read in the load test) only to be dropped as this node's. The writer now puts the event's source in asrcfield after the payload, and a reader that finds its own source there acknowledges the entry and moves the group on without decoding it; the gap check, loss reporting and ordering are unchanged. Nodes on 3.0 and 3.1 share a stream during a rolling deploy: a 3.0 reader takes the payload by its field name and ignores the extra field, and a 3.1 reader decodes an entry without it and compares the source as before. WithEmitStreamReceivedEventon, own entries are still decoded so the receipt carries the event id. The read metric's topic name is built once per topic, not per entry. -
A node's own Redis Pub/Sub messages are dropped before they are decoded. A subscriber also receives what its node publishes, and decoded each such message in full (about 1.75 KB) only to drop it as its own. The default
CacheEventFormatterand the CloudEvents formatter now implementIEventSourceMatcherProvider: the subscriber reads only the payload's top-level source and drops the message unread when it is this node's exactly as written, with no allocation. The wire format is unchanged; any other source, a case-only difference, a missing or repeated source and malformed JSON are decoded and compared as before, as is every message while the subscriber's debug or trace log is on. A custom formatter can implement the interface to opt in.
-
ICacheFactory.PolicyFactory. It is onIPolicyDefaultsnow. A factory that returned its own policy factory implementsIPolicyDefaultsas well; one that relied on thenulldefault drops nothing. APolicyFactoryproperty on a class that does not implementIPolicyDefaultsstill compiles and is no longer read. Code that readfactory.PolicyFactoryreads(factory as IPolicyDefaults)?.PolicyFactory, or takesICachePolicyFactoryfrom DI. A test that set it up on a substitute creates it withSubstitute.For<ICacheFactory, IPolicyDefaults>()(Moq:.As<IPolicyDefaults>()). -
The 3.0 extensions the interface members replace.
SpanKeyExtensionsis gone, with all 36 of its methods (theSpan<char>GetAsync,ContainsAsync,GetOrAddAsync,GetCacheEntryAsync,GetItemAsyncandRemoveAsyncoverICache,ICache<T>,IHashCacheandIHashCache<T>), andICache,ICache<T>,IHashCacheandIHashCache<T>take noSpan<char>key. A 3.0 call with a span moves to an interpolated key, which allocates nothing up to 256 characters (cache.GetAsync<string>(span, null)becomescache.GetAsync<string>($"{tenant}:{id}", null)), tonew CacheKey(span), or, in code that is about the span capability, to a cast toISpanKeyCache,ISpanKeyHashCacheor their<T>siblings.Cache<T>,HashCache<T>,NullCache,NullHashCacheand the library's caches keep the span members that implement those interfaces, but notRemoveAsync(Span<char>).StatefulCacheExtensionsloses itsGetOrAddAsync<T, TState>overloads that take aCachePolicy?onICacheand all three overICache<T>;GeneratedExpirationExtensionsloses theGetOrAddWithExpirationAsync<T>that takes aCachePolicy?onICacheand the one overICache<T>. The policy-lessICacheoverloads of both classes stay. Recompiled, a state or generated-expiration call binds to the interface member (or the class member, on a public cache class) with no change, except a call onICache<T>,IHashCache<T>,Cache<T>orHashCache<T>that spells the value type as a type argument. The extensions were generic in it; the members take it from the cache, so drop it:typed.GetOrAddWithExpirationAsync<string>(key, generator)becomestyped.GetOrAddWithExpirationAsync(key, generator), andtyped.GetOrAddAsync<string, int>(key, state, generator)becomestyped.GetOrAddAsync(key, state, generator)ortyped.GetOrAddAsync<int>(...). A call written as a static method (SpanKeyExtensions.GetAsync<T>(cache, ...)) becomes an instance call on the cache. An assembly compiled against 3.0 that calls a removed method and is not recompiled fails when the JIT first compiles the method holding the call, withTypeLoadExceptionfor aSpanKeyExtensionscall andMissingMethodExceptionfor the others; rebuild it against 3.1.
-
Background writes of one key coalesce. A hot key's queued background write is replaced by a newer write of the same key, so the key no longer fills the background-write cap and pushes other writes to the foreground. Hash-cache field writes are not coalesced: each one still reaches the inner tier. A write that sends no event (a fill) never replaces a queued one that does, and each replacement is counted in the
cache.background_write.coalescedmetric. A write let in past the cap because it could replace a queued one goes to the foreground if that queued write started before it ran, so the cap holds. Awaited writes interleaved on a hot key still each take a place, so the cap can still fill in that case. -
Disposing the cache host disposes its broadcast topics, and the notify subscription stops retrying. A disposed host left its topics running, and each topic's doorbell subscribe retried against the disposed connection every period, throwing each time.
-
A Redis Pub/Sub subscribe that fails, or completes after the topic is disposed, no longer leaves its handler registered. A subscribe that completed after the topic was disposed stayed registered on the shared connection, holding the topic's writer, and a timer tick queued before disposal could subscribe again; such a subscribe now unsubscribes at once, and a tick after disposal does nothing. A subscribe that fails, for example on a timeout, now also removes its handler, which the connection had kept and resubscribed on reconnect, so the retry no longer adds a second one.
-
The Streams transport reads without the Lua script on Redis below 7.0. The
XREADGROUPinside Lua cost the server several times a plain read on every batch. The gap check still runs, using the oldest entry past the group's position, but as separateXINFO STREAMandXINFO GROUPScommands before the read, so it is no longer atomic with it and each read takes more round trips. -
A local hit is cheaper. A key's casing is checked with vector instructions rather than character by character, and a read by span under the default key strategy composes the key once instead of twice. Keys are unchanged.
-
A local miss whose distributed read began before a peer's write of the key no longer keeps the older value. A node that did not hold the key had no change token to hear the peer's event, so the value its read found before the write was kept locally until it expired. Each cache with a shared distributed tier and broadcast now hears every peer
CacheSet,CacheRemovedand metadata change on its topics, before the keys' own tokens, and refuses such a fill; a topic-wide invalidation, a loss, a subscription gap or a topic that ends refuses every fill begun before it. From its first distributed read the cache counts changes, and writes in flight, per stripe of keys, which costs an awaited write a stripe lock or two; the write order is still kept only from the first background write. A fill is refused for two causes: a change since the read began, such as a peer's event, which also refuses the fill of a key sharing the stripe (1 in 8192 keys, up from 1 in 1024 as the stripes grew to 8192, about 147 KB per cache with a shared tier and broadcast, from about 61 KB), and a write of the key or its stripe still in flight. A subscription gap refuses every fill in flight, even for a cache that keeps its entries over gaps. Each refusal costs that key one more read and is counted incache.background_write.fill_refused. -
A peer refresh keeps no superseded copy alive. The refresher recorded each copy it kept against the entry it replaced, in a weak table whose handles the collector scans once per link, so a key peers write often chained its copies old to new: one superseded copy still reachable kept every later one alive, and an ephemeral collection that met the chain spent tens of milliseconds on it. A replaced entry and its copy now carry the refresh's number instead, and neither references the other; a late event on the replaced entry's token still drops the copy, and only it. An entry from a custom
EntryFactorycannot carry the number, so a peer's write drops it, as beforeRefreshLocalOnPeerWrite. -
A stream deleted and made anew under a node no longer loses the entries whose ids do not pass the last one read. A read that found its group gone made it again at the last id read, which is right when only the group was removed, but a stream made anew by the next
XADDstarts its ids over (a clock stepped back widens this), so entries at or below that id, including writes after the loss was reported, were never delivered. The node now reads that one entry back (XRANGE, one round trip on this recovery path only) and resumes there only if the stream still holds it byte for byte; otherwise the group is made at0-0and the stream is read from its start, a replay that at worst drops local copies. The loss is reported as before. -
A group this node made on an empty stream no longer reports its first entry as lost on Redis 6. Without
max-deleted-entry-id, an entry added after a group made at0-0looked trimmed, so the node logged "entries were removed before they were read" and cleared its whole local tier. The node now remembers it made the group on a stream that had never held an entry, and reports no gap for it unless the stream has reachedMaxLength, where a trim may really have happened. A group that was found, or made on a stream that had held entries, is checked as before. -
A topic name that selects a disabled or unregistered provider now fails host start.
CacheOptions.DefaultTopic, or theTopicof anInMemoryCacheOptionsorInMemoryRedisCacheOptionswith broadcast on, naming a provider that is off (Broadcast:RedisPubSub:Enabledis false by default) or not registered used to resolve to the null topic provider, so broadcast was off with no signal. Start now throws anOptionsValidationExceptionthat names the provider and the setting to enable it; an emptyDefaultTopicis rejected too. Nothing is checked whileBroadcastEnabledis false. Upgrade check: an app that setsBroadcast:RedisStreams:Enabledto false and has a cache with noTopicresolves to the defaultRedisStreamsand now fails start. SetCaching:BroadcastEnabledto false if it wants no broadcast, or pointDefaultTopicat an enabled provider. -
A Redis Streams read that times out no longer loses its invalidations. Redis hands the entries of a read to the consumer and moves the group past them even when the answer never reaches the client, and the reader only ever asked for new entries, so those stayed pending and their invalidations were never applied: the node kept the old values until they expired. The reader now reads its own pending entries when it starts and after every failed read, before going back to new ones. A pending entry deleted from the stream before it was read is acknowledged and reported as missed, which clears the local tier for the topic, since its invalidation is lost. A read timeout is logged as a Warning once per 100, and at Debug otherwise, rather than as an Error every time. An entry that cannot be decoded is acknowledged and dropped, not reported as a missed message: a bad payload is not a lost invalidation, and reporting it would let one bad writer clear the local tier of every node. Each one is tracked as the
Caching.RedisStreamSubjectWriter.DispatchEventsAsync.UndecodableEventtelemetry event and logged as a Warning once per 100. -
The stream maintainer no longer deletes the consumer group of a live subscriber on a quiet stream. A group with consumers counted as stale once its last delivery was older than
MaintainerTrimInterval, even when nothing newer had been written, so on a stream with no traffic every live group was quarantined and then deleted afterMaintainerQuarantineInterval, and its reader recreated it on the nextNOGROUP. A group whose last delivery is the stream's last entry is now healthy, and a quarantine it was under is cleared. -
Multi-key calls over keys of several Redis Cluster slots run, one command per slot, instead of throwing
CrossSlotKeysException.GetAsync(CacheKey[]),GetCacheEntriesAsync, the batchSetAsyncandRemoveAsync(CacheKey[])refused such a batch, and with them the batchGetOrAddAsync, which reads its keys withGetCacheEntriesAsyncand stores its misses with the batchSetAsync; on a cluster endpoint, keys without a shared hash tag made every such call throw. The keys are now grouped by slot (with the connector's key prefix, as before) and each group is sent as its ownMGET, read transaction, write transaction orDEL, all in flight together, up to 1000 at a time; keys of one slot, and every batch on a server that is not a cluster, are still one command. The batchSetAsyncis atomic per slot, not across slots: when one slot's transaction does not commit it returnsfalseand the other slots may be written. A read whose slot fails reads that slot's keys as misses and keeps the others; a remove reportsfalsewhen any slot fails. The multi-layer cache announces every key of a batch set it could not confirm, since some may be written, and drops its own copies of them.CrossSlotKeysExceptionstays in the API and is no longer thrown. -
A profiled Redis command's dependency names the configured server, not the cluster node. The target was the endpoint that served the command, so on a cluster each shard's IP and port showed as its own dependency target. It is now the endpoints of
RedisConnectionOptions.ConnectionString(host:port, with the default port filled in), and the node moves to the newRedisNodeproperty (ProfiledCommandProcessor.NodeField). Without a connection string, as with aConnectionFactory, or with a SentinelserviceName, whose endpoints are not the servers that answer, the node stays the target. Queries and alerts on the dependency target need the new value. -
A named caching stack's telemetry carries its name. Everything a stack from
AddNamedCachingreports through the application'sICachingTelemetryProvider(Redis dependencies,Caching.Stats.*metrics, events, exceptions) has aCachingStackproperty set to the stack's name, so stream and topic metrics of two connections no longer mix. The application's own stack adds none. A provider thatconfigureServicesregisters is the stack's own and is left as it is. -
A named caching stack's profiled commands keep the request's profiling session. The stack has its own
IRedisProfiler, and a session opened on the application's one did not reach it, so the stack's commands went to its default session without the request's session id. Each session the application's profiler opens is now opened on the stack's as well, and processed by it when closed. An application that forwards its profiler to the stack throughconfigureServicesgets the stack's commands with its own connection as their target and withoutCachingStack; it can drop that forwarding now. -
PollIntervalmust be positive. Zero or negative failed later, when the poll loop waited on it; it is now refused by the options validator with the other Redis Streams options. -
IHashCache.GetCacheEntryAsyncon Redis is one round trip, as documented. It asked the server whether the key exists before reading it; the read of an absent key already answers a miss, so the first trip is gone. -
A
HashReplacewrite left the hash cache's local tier with only the fields it wrote. The store merges the fields into the hash, but L1 kept the partial dictionary, so a read on the writing node lost every other field until the entry expired. The write now merges into the hash L1 holds, keeping its metadata, and leaves nothing in L1 when it holds none, so the next read fetches the whole hash. AKeyReplacewrite is unchanged, and so is an emptyHashReplacewrite withCacheNullValueson: it replaces the hash with an empty one in both tiers, as the store always wrote it. -
The notify doorbell of a Redis Streams topic is one
PUBLISHat a time. It was one per event, so a burst of many thousand events overflowed the subscriber connection's output buffer (client-output-buffer-limit pubsub) and Redis closed it, failing the commands queued on it. The rings that arrive while one is in flight are sent as one more, and a ring stalled on Redis holds them for at most one second. -
A subscribe to a Redis Streams topic no longer blocks the caller. A subscribe that found no consumer group created it synchronously while holding a lock the reader also takes. Every cache write subscribes a change token, so under a burst on a fresh process the request threads queued on that lock while the holder waited on a Redis reply that needed a thread-pool thread, and the pool starved: a load test of a fresh process served 0 of 1,500 requests. A subscribe now neither waits nor sends a command; with no group known it marks the topic in use and wakes the reader, which makes the group. Before making it at the head, the reader reads the server's clock and the stream's newest entry in one script; the subscribers that joined first are told of a loss only if an entry another node would act on was added since the first of them joined, which it checks by reading back what the group skipped (up to 256 entries) and ignoring its own and invalid ones. A fresh process on a quiet stream, or one whose own writes raced its group, reports nothing. The same check runs for a group found after a create that seemed to fail, such as one that timed out after the server ran it. Below Redis 7.0 the group is made at the newest entry the script read rather than at
$, so what is added between the two is delivered. With scripts orXINFOrefused, or the skipped entries unreadable, the subscribers are told; a cold start on such a server now expires the entries they cached before the group existed.Subscribeno longer throws when Redis cannot create the group; the reader retries, as it already did for a group lost while in use. -
The connector key prefix, three edge cases. An
ECHOanswered with no prefix no longer overrides a non-emptyRedisCacheOptions.KeyPrefix: the configured value is used, with a warning, since a decorator may sendECHOpast its own prefixing. Running out of probe attempts is now warned about, naming theKeyPrefixfallback used until the process restarts; it was silent, and with an emptyKeyPrefixthe maintainer again found nothing. A prefix skipped for its SCAN glob characters is skipped for stream discovery only: the cluster slot check hashes with it, since it is what the server receives. -
Stream discovery reaches every shard through a connector of the application's own. The maintainer asked
IRedisConnector.GetPrimaries()for the servers toSCAN, and an implementation outside this library inherits its empty default, so each pass warnedNo primary could be enumerated for stream discoveryand scanned only the routed server. On a cluster that is one shard: streams on the others went untrimmed and their abandoned consumer groups were never reaped. An empty answer now falls back to the connected primaries ofDatabase.Multiplexer. A non-clustered Redis was unaffected beyond the warning. -
Each primary is scanned in the connector's database. The per-primary
SCANran in the configured default database rather thanDatabase.Database, so a connector onGetDatabase(n)with anotherndiscovered no streams through it. -
The first subscribe of a Redis Streams topic no longer risks a spurious loss. A read issued before the subscribe created the consumer group, and answered
NOGROUPafter it, was reported as entries lost, so the local tier could be expired for nothing right after a process started. Such an answer now reports a loss only when the group was known to exist, and a loss already reported is not reported again when the recreate had to be retried. -
A failed multi-key
RemoveAsyncstill clears this node's local entries and sends every invalidation. TheCacheKey[]overload on the multilayer cache returned as soon as the inner delete failed, before it cleared the local entries, so after a transient Redis failure the removed values stayed in this node's memory until they expired; and it stopped at the first invalidation that failed, so the other nodes kept the rest of the keys. It now does what one single-key remove per key does: the local entries go first, every key's invalidation is sent even when another fails, and the call still returnsfalsewhen the delete or any invalidation failed. -
A Redis restart no longer leaves the Streams reader waiting out its back-off when the connection monitor is off. The fetch loop's error back-off (three retries at
PollInterval, then doubling up to 30 s) was ended only by the connection monitor's recovery events, so withConnectionMonitorEnabled: falsethe reads that failed while Redis was down went on pacing the ones after it came back, and the doorbell could not wake the loop: the first invalidation after a restart waited out the remaining back-off. The reader now listens to the connection's own restored and reconnected events, which end the back-off and its failure streak with or without the monitor, so the group lost with the server is recreated and read at the poll's pace, and the next ring is answered at once. A recovery that lands between a read's failure and its back-off ends that back-off too, and that failure is not counted against the reads after it. -
A hash
SetManyAsynckeeps the version each of its writes took, withPeerFieldUpdateson. The batch dropped the count its writes returned, so a write of the same key that returned after a later batch write laid its older fields over the batch's local copy, and a batch write that returned after a later single write replaced that write's copy, while the distributed tier held the newer value: the node served the stale hash until the next peer event or its expiry. The batch now records each write's version as a single write does, so the write that returns out of order leaves the newer copy alone, or drops its own. -
Cache<T>andHashCache<T>batch writes report the caller key whose write failed when a key strategy maps two keys to one. The failed stored key was given back as the first caller key that mapped to it, or every one, even when that key's write, in an earlier chunk, had landed. Each chunk's failures now go back to the caller keys of that chunk. -
A background write's local copy is refreshed, not evicted, when a peer writes the same key before the background write finishes. The copy kept while a
BackgroundDistributedWritewrite was in flight carried no policy, so a peer's write dropped it and the next read went to Redis. Applies to the plain and the hash cache.
-
broadcast.mdsays an explicitMaintainerSearchPatternmust carry the connector'sWithKeyPrefixprefix, and its broken em dashes are restored.second-redis-connection.mdno longer suggestsKeyPrefixfor separate keyspaces: it prepends nothing itself. -
docs/reference/interfaces.mdsays how the capability calls behave over a mock (the interpolated-key and stateful calls go to the proxy'sCacheKeymember,GetOrAddWithExpirationAsyncreads, generates and sets; none coalesces) and how to test what the library does instead: over the in-memory cache, named explicitly, since an unnamedCreateCache()resolvesCacheOptions.DefaultCache(InMemoryRedis) and falls back toNullCachewhen onlyAddMemory()is registered. -
Which
GetOrAddAsyncshape to call.docs/how-to/choosing-a-get-or-add-overload.mdmakes the plain lambda the documented default and measures the alternatives: a lambda costs 64 to 96 bytes per call; a delegate built once and the state overloads make a local hit allocate nothing. On a miss the lambda still costs its bytes, small next to the generator and the write. It says when the state and interpolated-key overloads pay (a hot path a profiler has shown), how to write each shape, which one a wrapper should wrap, what runs behind the extension classes, and what a Moq or NSubstitute proxy sees. The README and quickstart point to it, and the XML docs of the capability interfaces name the classes that implement them.GeneratorShapeBenchmarkinbenchmarks/UiPath.Caching.Benchmarksis the measurement.
-
Reads by
Span<char>.SpanKeyExtensionsaddsGetAsync,ContainsAsyncandGetOrAddAsyncoverICache,ICache<T>,IHashCacheandIHashCache<T>,GetCacheEntryAsyncoverICache,IHashCacheandIHashCache<T>, andGetItemAsyncover the hash surfaces, reading by the key's text without building aCacheKey.GetOrAddAsyncbuilds the key only on a miss, or when the policy rehydrates, since rehydration keeps the key; the generator then runs exactly as it would on theCacheKeypath.NullCacheandNullHashCacheimplement the capability interfaces explicitly, so their public surface keeps only theCacheKeyoverloads; a span read reaches them through the extensions. The text is normalized asnew CacheKey(text)normalizes it. A cache that implementsISpanKeyCache,ISpanKeyCache<T>,ISpanKeyHashCacheorISpanKeyHashCache<T>serves the read itself, as the library's caches do: over the in-memory tier on .NET 9 and later, under a key strategy that composes by span, as both built-ins do, a local hit allocates nothing. Any other cache, an outside implementation or a Moq or NSubstitute proxy, is read through itsCacheKeyoverload, so a test that sets that overload up answers the span read too. The reads are extensions rather than interface members because a proxy generator emits invalid IL for a method that takes aSpan<char>. The parameter isSpan<char>rather thanReadOnlySpan<char>: a read-only span overload on the capability interfaces would make a call with a string ambiguous against theCacheKeyoverload. Through a library class, a baredefaultkey, as incache.GetAsync<T>(default, policy), still binds to theCacheKeyoverload under a C# 13 compiler (.NET 9 SDK or later). Under an older compiler it is ambiguous (CS0121); cast it toCacheKey. On a cache of a nullable value type, such asICache<Guid?>, a generator that returns the non-nullable type fails to infer (CS1503); pass the type argument,GetOrAddAsync<Guid?>(...), or return(Guid?)from the generator. -
GetOrAddAsyncwith generator state.GetOrAddAsync<T, TState>(key, state, (state, ct) => ..., ...)overICacheandICache<T>, byCacheKeyorSpan<char>, with the same expiration variants as the closure overloads. A static lambda and its state replace a capturing lambda, so a call that hits the local tier allocates no closure and no delegate. The built-in caches implement the newIStatefulCacheandIStatefulCache<T>, andISpanKeyCacheandISpanKeyCache<T>gain the span forms;StatefulCacheExtensionsandSpanKeyExtensionsprefer them and otherwise close over the state and call the existing overload, so a mock or an outsideICachekeeps working. The Redis provider builds the factory-timeout wrapper only on a miss. -
RemoveAsyncbySpan<char>.SpanKeyExtensions.RemoveAsyncoverICache,ICache<T>,IHashCacheandIHashCache<T>removes by the key's text, normalized asnew CacheKey(text)normalizes it, so a caller that formats its key on the stack need not build theCacheKeyitself. Every tier needs the key as a string, so the extension builds it and calls theCacheKeyoverload; there is no capability interface to implement. -
A generator that returns its value's expiration.
GetOrAddWithExpirationAsynctakes aFunc<CancellationToken, Task<GeneratedValue<T>>>;GeneratedValue<T>(Value, Expiration)carries the instant the value stops being valid, for a token whose lifetime is in the token. The entry is stored until that instant; a nullExpirationtakes the policy's lifetime, and one that has already passed returns the value without storing it. Single-flight, the locks andFactoryTimeoutapply as they do toGetOrAddAsync; rehydration does not, since there is no configured lifetime to measure a threshold against. It is a separate method name becauseGetOrAddAsync<T>onICachewould bind first and cache theGeneratedValue<T>itself. The built-in caches implementIGeneratedExpirationCacheandIGeneratedExpirationCache<T>. On a cache that does not (a mock, an outside implementation) the extension reads, and on a miss runs the generator and sets its value with the returned expiration, or with the policy's lifetime when there is none; it does not coalesce. A cached default value (0,false, a cachednull) is a hit onICache; the typedICache<T>has no entry read, so it asksContainsAsyncwhen the value reads as the default. It has no clock to tell that an expiration has passed, so a set that rejects it withArgumentOutOfRangeExceptionleaves the value returned and not stored, as the capable caches do. Moq and NSubstitute proxies take this path. -
CacheKey(ReadOnlySpan<char>)andCacheKey(ReadOnlySpan<char>, CacheKeyCasing)build a key from text that is not yet a string, normalizing while copying, so a key formatted on the stack costs one string rather than two. -
IResiliencePipeline.ExecuteAsync<TResult, TState>. Hands a state value to a static callback, so a Redis command no longer allocates a closure and a delegate. The Polly pipeline boxes the state once instead, since Polly copies its state into each strategy's state machine. Its default implementation forwards to the existing overload, so a custom pipeline keeps compiling; implement it to drop the closure there too. -
RedisCacheBase.RunAsync,KeyTimeToLiveAsync,KeyExpireTimeAsyncandSupportsExpireTime. The one-command shape the Redis caches repeat, in one place: a pipeline call timed by a telemetry operation, tracked as a hit by a predicate, and on failure logged and answered with a fallback. The thirteen single-command members ofRedisCache,RedisHashCacheandRedisSetCacheforward to it; the TTL and expiration reads, with the pre-Redis-7 fallback from TTL to expiration, live in the base once instead of in each cache; andRedisHashCachereads a hash's fields in one method instead of two copies of the loop. Protected, for a subclass that adds a command of its own.SupportsExpireTimeresolves the server version on first use, so constructing a cache that never reads an expiration, such asRedisSetCache, does not connect.
-
Dependency floors. What a consumer's restore has to satisfy, taken from
Directory.Packages.props:Package 2.1.0 3.0.0 StackExchange.Redis(UiPath.Caching,UiPath.Caching.Queue)3.3.0 3.3.1 AsyncKeyedLock(UiPath.Caching)8.1.2 no longer referenced The
Microsoft.Extensions.*, Polly andMicrosoft.Azure.StackExchangeRedisfloors are unchanged. -
RedisCacheOptions.ReadScriptsEnabledreads with one read-only script. Opt-in, off by default. On Redis 7 or later,RedisCacheandRedisHashCachethen read a value (or all hash fields) and its expiration with oneEVAL_ROscript instead of a MULTI/EXEC transaction, still atomically and still from a replica when one is preferred; a batch read runs one script for all its keys. A miss through the in-memory and Redis tiers allocates about 2.5 KB less (8.7 KB to 6.2 KB on net10), a miss under the distributed lock about 5 KB less and a hash hit about 1.9 KB less; round trips are unchanged. The connection's user needs@scripting. Before Redis 7, if the first script fails for any reason, or once the server refuses one as unknown or not permitted, reads use the transaction; the switch is logged as a warning. After a script has worked, timeouts and connection errors do not switch it. -
The first Redis connect no longer blocks a thread.
RedisConnector.Databasewaits for the first connect synchronously, so on a new instance every concurrent first call held a thread-pool thread until it finished. The Redis caches, the distributed lock and the health check now wait for the connector withConnectAsyncbefore they readDatabase; the cache commands do it inside the resilience pipeline, so the wait is cancellable and bounded by the request timeout, like the command.RedisConnector.ConnectAsynccosts nothing once connected. The synchronousDatabaseandSubscriberaccessors are unchanged for other callers.WarmUpOnStartstaysfalse: it opens a connection, and runs any authentication configurator, at every host start, which a consumer that never reaches Redis should not pay; with the wait asynchronous, the first call no longer needs it to stay off the thread pool. -
The Redis provider's
GetOrAddAsyncreads Redis once and runs one generator per key at a time. Concurrent misses on one key in a process each ran the generator, since the Redis provider has no lock, and every caller read the key first. Every caller now goes straight to one run per key: the run reads Redis once, returns what it finds (concurrent hits share that one read), and on a miss generates and writes once. Callers that arrive meanwhile join the run and take its result or its failure. The run is on its own token, cancelled once every caller has cancelled, andFactoryTimeoutapplies to it. The first caller's generator and expiration are the ones used. N concurrent callers on a key send oneGET(and oneSETon a miss) instead of N, and a read that failed counts as a miss for all of them, as before. The hit and miss counts record the reads sent, one per run, not one per caller. This also holds while Redis is unreachable, when every call is a miss. The Redis provider takes no distributed lock, so none is involved; the multilayer provider'sLocksettings are unchanged. -
A caller whose wait for the local lock times out joins the generator in flight.
GetOrAddAsyncon the multilayer and hash caches used to run the caller's own generator onceLocalLockTimeout(500 ms by default) expired, so a loader slower than that was run by every caller that arrived while it did. The caller now re-reads the cache as before and then joins the load running for the key, sharing its result or its failure, and starts its own only when none is running. The shared load runs on its own token: a caller that cancels stops waiting, and the load is cancelled once every caller has. Breaking in what it observes: callers that waited out the lock no longer run separate generators, so a generator that failed for one of them now fails them all, and the generator that runs is the first caller's, with its expiration and policy. WithLocalLockEnabledoff nothing is shared, as before. BatchGetOrAddAsyncdoes the same per key: a key whose generator run is in flight, from a single-key call or another batch, is joined, including by a batch that only partly overlaps it, and the generator receives only the keys no run covers. A joined key shares the run's failure; if the batch that started the run cancels, its joiners re-read the cache and take the key over together, one of them generating it for the rest. A single-key call joins a batch's run for its key the same way, and a batch and a single-key call never generate one key twice. A caller that takes a key looks it up once more in the local tier, and only there, so a key another run of this process finished since the caller's read is returned, to its joiners too, and not generated; a batch generates only the keys still missing. A run writes the local tier before it leaves the table, which is what makes that lookup enough. With the local tier disabled or the entry evicted the lookup finds nothing and the key is generated once more, after the earlier run, never beside it. The Redis-only provider has no local tier; it reads Redis once per run instead. The starting caller's locks stay held until the shared load ends, even when that caller cancels and stops waiting, in the hash cache as in the multilayer cache. A load every caller has left does not store its result, so a generator that ignores its cancellation cannot overwrite what a newer load wrote. A batch that stops early, whether it failed or was cancelled, stops counting as a waiter on the loads it joined, so they are cancelled once nobody else waits. The hash cache has no batch overload. -
A Redis outage is served from the local tier by default.
CacheOptions.ConnectionMonitorEnabledandUseLocalOnlyWhenDisconnectednow default totrue: while the inner tier is disconnected, reads are served from the local tier and writes kept there, capped atLocalMaxExpirationDisconnected(30 seconds by default). The newClearLocalOnReconnect, alsotrueby default, expires the local entries of a Redis Pub/Sub topic when its connection is restored, since the invalidations sent while it was down never arrived. The topic expires them through their change tokens, so it works on any local tier, a customIMemoryCacheFactoryone included. A forced reconnect counts too: swapping the connection can drop publications although it never read as down. A Pub/Sub topic also subscribes only after a delay, at first and after a reconnect, so once its subscription is in place it expires the entries cached before then; a cache withClearLocalOnReconnectoff keeps them. Redis Streams replay what was sent meanwhile, so their local tier is kept. The monitor setting is app-wide, so the broadcast providers' connection monitor turns on too. Breaking for an app that relied on a disconnected tier answering misses: setUseLocalOnlyWhenDisconnectedtofalse, orConnectionMonitorEnabledtofalsefor the previous behavior. Breaking too for a customIMultilayerCacheOptionsimplementation, which must addClearLocalOnReconnect. -
RedisConnector.IsConnectedisfalseonly when a connection exists and reports itself down. Before the first connect, while it is pending and after it faulted, it is nowtrue, so a command goes through and opens or retries the connection; it used to befalse, and the operations that check it first, L2 reads and everyISetCachecall, did nothing until a write had connected. Observable to code that readsIRedisConnector.IsConnecteddirectly, such as a status endpoint: useRedisHealthCheckto learn whether the server is reachable. -
Concurrent single-key reads share one inner read. On a local miss, concurrent single-key
GetAsync,GetCacheEntryAsyncand hash reads of one key, and the readGetOrAddAsyncmakes before its lock, wait for a single inner-tier read and share its result or failure. Reads share only when they read the same value type with the sameLocalExpirationandLocalExpirationDisconnected, since the shared read keeps its hit for those lifetimes; reads that differ in any of them read separately. Multi-key reads still read every missing key themselves. A caller that cancels stops waiting; the shared read is cancelled only once every caller waiting on it has cancelled. -
GetOrAddAsynckeeps a value the inner tier refused. When the inner write fails or throws, the generated value is kept in the local tier forLocalMaxExpirationDisconnected, by the batch overload too, so the callers waiting on the local lock reuse it instead of each running the generator again. -
A string key reads the local tier by its text. On .NET 9 and later,
GetAsync,GetItemAsync,ContainsAsync,GetCacheEntryAsyncandGetOrAddAsyncwith aCacheKeylook the in-memory tier up as the span reads do, andCache<T>andHashCache<T>compose their strategy's key on the stack instead of throughGetCacheKey. A local hit through a typed cache with a prefix strategy, the common shape, no longer allocates the prefixed key, its entry options or, forGetOrAddAsync, the rehydration closure, with no change at the call site. A key built with a casing other thanCacheKey.DefaultCasing, a strategy that declinesTryGetCacheKey, and .NET 8 under a custom strategy take the path they took before. UnderDefaultCacheKeyStrategythe lookup is by the key's text on every runtime and over anyIMemoryCache, so a miss costs one lookup instead of the span composition. -
A
GetOrAddAsyncmiss does less work before it generates. A call that has just missed the local tier goes straight to the inner tier instead of reading the local tier again, and a span key's miss no longer reads it a second time on the way to theCacheKeypath; the hash cache likewise. After a caller takes its key it looks the local tier up once more only when something in the process wrote that tier since the caller's first read, counted per cache, instead of on every miss. -
The caller that starts a shared run waits on the work, not on the run's published task. A miss that starts the generator used to resume through a thread-pool hop, since the shared task completes its continuations asynchronously so that a joined caller never runs another caller's code inline. The starter now resumes where the work ends, as an awaited call does, which saves the hop and the shared task: a run nobody joins builds none. Callers that join the run resume asynchronously as before. A starter that cancels still gets a
TaskCanceledException, and a failure of the work still reaches it, and every joiner, as the exception the work threw. -
The write, remove and broadcast paths allocate less. The local setter and the event publisher take the entry options as they are, unboxed; the null change token is not wired to the local entry, so a replace or remove no longer queues a thread-pool work item for its eviction callback; a factory with no timeout hands back its own task; no event is built for the null topic; a key's observers live in an array instead of a dictionary per key; and the local tier keeps the entry built for the caller. On net10, a remove then re-add on the in-memory cache drops from 1.6-2.2 us and 1416 B to 0.84 us and 616 B, a fresh in-memory miss from 1.27 KB to 688 B, and a miss on the in-memory tier over Redis from 10.45 KB to 8.5-9.2 KB. With
TrackStatisticson, the memory cache now counts one extra hit per local write, from the lookup that tells whether it kept the entry (see Fixed). -
The Redis provider shares a run by Redis key and value type, and builds less per call. The run table is keyed by the
RedisKeyitself, per value type, instead of the key's rendered text, so a prefixed key is no longer turned into a string on everyGetOrAddAsync, and the run's result is neither boxed nor cast. As before, two calls share a run only when the key strategy maps them to the same Redis key, so a strategy that reads ambient state, such as a tenant, and maps one cache key to different Redis keys keeps them apart. The two async frames wrapped around the run are gone. -
A miss takes its key before any lock when no distributed lock is held. With the local lock on, the default, and
DistributedLockEnabledoff, the default,GetOrAddAsyncon the multilayer and hash caches takes the key's run in the process first and runs the generator in the caller that took it; a caller that arrives while it runs joins it at once. The keyed local lock, the read under it, its lock key and its async frames are not used on this path, and a miss that never waits builds no async state machine, so a miss costs one read of the local tier, and of the inner tier, instead of two. BatchGetOrAddAsynctakes its keys the same way, per key, with no composite lock key and no second probe, and copies nothing when every key is its own. With a distributed lock enabled the caller that takes the run takes the lock; see the next entry. Breaking in what it observes:LocalLockTimeoutno longer bounds aGetOrAddAsyncwait on this path, since a caller that arrives while a run is in flight joins it however long it takes, and stops waiting only through its token, where it used to wait for the lock up toLocalLockTimeoutand only then join; a generator that fails now fails every caller that arrived while it ran, where the callers queued on the lock each ran their own generator in turn and only those that timed out shared the failure; andGetOrAddAsyncno longer excludesTryAddAsyncthrough the lock.TryAddAsynckeeps the exclusion in the process by taking the key's run for the length of its add: it waits up toLocalLockTimeoutfor a run that holds the key, as it waited for the lock, and loses if one still does, and aGetOrAddAsyncthat arrives during an add joins it and takes its value, or takes the key over if the add lost. A generator therefore does not store over a valueTryAddAsyncadded in the same process while the local tier still holds it; a miss whose inner read began before the add and whose local copy of the added value is gone by the time its run starts, after an eviction or a shortLocalMaxExpiration, can still generate and store over it, as the lock path's second inner read used to prevent. A failed add leaves nothing held. Across processes nothing changes: only the inner tier arbitrates there. A load every caller has left still does not store its result. -
The in-process lock is gone;
ILocalLock,AsyncKeyedLocalLockandNullLocalLockare removed. One run per key in the process, the run table, does what the local lock did, without making a caller wait.GetOrAddAsyncon the multilayer and hash caches, single key and batch, takes the key's run first and, when a distributed lock is enabled, only the caller that runs the generator takes it: after the run is reserved, it reads both tiers again under the lock, runs the generator on a miss and releases the lock when the run ends, even if that caller has stopped waiting. Callers that join the run never touch the Redis lock, so N concurrent callers take it once instead of N times, and a batch takes one lock over the keys it runs.TryAddAsyncno longer takes any lock; it keeps the run reservation described above.Lock.LocalLockEnabledandLock.LocalLockTimeoutare renamed toLock.LocalSingleFlightEnabled("callers of one process share a run per key") andLock.LocalSingleFlightTimeout("how longTryAddAsyncwaits for a run that holds its key"), with the same defaults, on the provider options,IMultilayerCacheOptionsandLockProfile. The old names stay as[Obsolete]aliases, in code and in configuration, that read and write the new ones; when both keys are configured the new one wins. A per-call profile still overrides them.LocalSingleFlightEnabled=falsewithDistributedLockEnabled=trueis still rejected: with no shared run every caller of the process competes for the Redis lock. With a distributed lock, a timeout or failure taking it now fails every caller that joined the run, where each caller used to take the lock itself and fail alone. The set and queue caches' in-memory tier serialises writers of one key with a striped monitor (128 stripes chosen by the key's hash) instead of an async lock; their critical sections never await. Breaking: removeILocalLockregistrations andAddLocalLock()calls (they are unused), theMultilayerCacheBase,InMemoryCacheProvider,InMemoryRedisCacheProvider,InMemoryQueueCacheProviderandInMemoryRedisQueueCacheProviderconstructors lose theirILocalLockparameter,CacheOptions.LocalLockPoolSizeandLocalLockPoolInitialFillare removed (delete them from configuration:AddCachingnow refuses to start while theCachingsection still sets either), and theAsyncKeyedLockpackage is no longer a dependency. A subclass ofMultilayerCacheBasethat calls the protectedRunUnderLocksAsyncgets the distributed lock only, with no pre-read when none is enabled. -
ICachingTelemetryProvidertakesTelemetryTags<T>and has no default bodies.TrackDependency,TrackEvent,TrackExceptionandTrackMetrictakeTelemetryTags<string>properties andTelemetryTags<double>metrics in place ofReadOnlySpan<KeyValuePair<…>>. The struct holds up to nine pairs inline and more in one array, so the call stays allocation-free for the tags the library sends; a collection expression, a span or an array builds it implicitly, and it compares by value. With a span parameter, a Moq or NSubstitute mock of the interface threwInvalidProgramExceptionon the first call and could not match the tags it received; now both work.TelemetryTags.ToDictionaryOrNulltakes the struct. Breaking for every provider outside the library: change the parameter types, and implement all four methods, since the no-op default bodies are gone. -
ISpanCacheKeyStrategy.TryGetCacheKey<T>(ReadOnlySpan<char>, Span<char>, out int). The span form of the composition, behind theSpan<char>reads: the text arrives normalized, the strategy writes whatGetCacheKeywould build, and the library normalizes the result asCacheKey.WithNamewould.DefaultCacheKeyStrategyandPrefixCacheKeyStrategyimplement it. A strategy outside the library implements it to keep a span read's local hit allocation-free; one that does not is read throughGetCacheKey, as before. It is apart fromICacheKeyStrategyso a mock of the strategy never has to proxy a span. -
The local tier is keyed by the key's text.
IMemoryCachereceivesCacheKey.Namerather than the boxed struct: no box per lookup, one object less per resident entry, andMemoryCache's string-keyed dictionary instead of its object-keyed one. Observable only through a customIMemoryCacheFactorythat shares oneIMemoryCachewith other string-keyed entries, which can now collide on equal text. A key strategy that returns an empty key is refused withInvalidOperationExceptionbefore any tier is touched; the local tier used to file every such key under one nameless entry. -
A local write fills its entry in place. The expiration, change token, eviction callback, size and value are set on the entry
CreateEntryreturns, instead of on aMemoryCacheEntryOptionsthat was copied into the entry and discarded, lists included.PrefixCacheKeyStrategyconcatenates its prefix and separator, computed once, instead of interpolating them per key. -
PrefixRedisKeyStrategycarries its prefix as the key's byte prefix.GetRedisKeyno longer concatenates a string per key: the prefix is encoded once and StackExchange.Redis writes it next to the key name. The key the server receives and its cluster slot are unchanged. Breaking: the protectedPrefixandSeparatorsetters are removed, since changing them would no longer change the keys, and a surrogateseparatorthrowsArgumentException, since encoded apart from the name it could no longer pair with a name that starts with its low half. -
The Redis caches write through a pooled buffer. With the built-in JSON serializer, a value is serialized into a buffer rented from
ArrayPool<byte>.Sharedand returned once the write has completed, instead of an array the size of the payload for every write. The bytes matchSerialize, customJsonSerializerOptionsincluded. A subclass of it, like any other serializer, keeps lending its own memory. Only writes use it: the write pipeline never abandons a command, so a buffer is never returned while the client may still be sending it. -
Implementation classes moved to
UiPath.Caching.SystemJsonByteSerializerProxy,RawByteSerializerProxy,Cache<T>,HashCache<T>,CacheFactoryExtensions,CacheExpiration,CacheKeyComparer,TelemetryTagsandBatchGetOrAdd, which is now public. The abstractions package keeps to interfaces, null implementations, DTOs and the extensions over them. Namespaces are unchanged. Breaking for code that references onlyUiPath.Caching.Abstractionsand uses one of them: add aUiPath.Cachingreference, or injectICache<T>andIHashCache<T>, whichAddCachingregisters, instead of callingCreateCache<T>. A binary compiled against the old location fails withTypeLoadException, since the abstractions package cannot forward types to a package that depends on it. -
ICache's batchGetOrAddAsync<T, TState>overloads have no default implementation. The default calledBatchGetOrAdd, which left the abstractions package with the other implementations.NullCacheimplements them with the resultBatchGetOrAddgives over a cache that never hits. Breaking for anICacheimplementation outside the library: implement the three overloads, forwarding toBatchGetOrAdd.RunAsyncfor the behavior the default had. An implementation compiled against the old interface fails to load withTypeLoadException.
ITelemetryOperation,TelemetryOperation,NullTelemetryOperationandICachingTelemetryProvider.StartOperation. The caches time each operation withTelemetryScope, a struct read from the cache'sTimeProvider, instead of allocating an operation object per call with telemetry on. It reports through the provider'sTrackMetricandTrackDependencywith the same metric names and tags, so a provider that implements those, as a provider normally does, needs no change. Breaking for code that callsStartOperation, overrides it, or references the removed types: time an operation withnew TelemetryScope(provider, timeProvider, providerName, method, type)instead.TelemetryScopeships inUiPath.Caching, since the abstractions package holds no implementations. The tag constants moved fromTelemetryOperationtoTelemetryScope, andNullTelemetryProviderlost itsStartOperationoverloads.
-
A key rewritten from many threads no longer piles up change-token subscriptions. A local write whose entry the memory cache did not keep, because a concurrent write to the key committed after it or it expired on insert, kept its change token subscribed until the cache's eviction callback ran on the thread pool, and a write that threw kept it until the topic closed. With 64 threads rewriting one key that reached hundreds of thousands of subscriptions on the key. The write now releases the token before it returns; the peak measured is 47.
-
Events dropped at a full dispatcher channel expire what the topic keeps. A Redis Pub/Sub topic whose channel was full in
Waitmode discarded the event, and the drop modes (DropOldest,DropNewest,DropWrite) discarded one silently on either transport; the invalidation it carried was lost. Each drop now expires the topic's local entries, coalesced to one expiry at a time. -
A removal after a refresh expires the local entry. A change token kept the metadata and expiration of an earlier refresh, so a later removal or loss, which carries neither, re-inserted the old value under a fresh token. It now clears them first, and a refresh delivered after the removal or loss no longer brings them back.
-
A refresh is broadcast as
CacheRefreshed.CacheEventPublisher.CacheRefreshedAsync, whichRefreshAsyncraises, sent theCacheRemovedtype. The library's own receivers treat both alike, so only a subscriber that filters by event type sees the difference. -
A Redis Streams topic that loses entries before this node reads them expires what it kept. Before each read the consumer checks whether entries past its last delivery were trimmed (
MaxLength, or the maintainer's trim) or deleted, since a trim can reach unread entries between any two polls, and a consumer group or stream removed while in use counts as a loss too. The check and the read run in one script, so a trim cannot land between them; where scripts are refused, they run apart, and whereXINFOis denied, each reconnect counts as a loss. A gap is reported once: until the group reads past it or more entries are trimmed, later checks find the same one. The local entries on that topic then expire, in every cache that uses it, whateverClearLocalOnReconnectsays. They used to be kept, so a change whose invalidation was trimmed was served stale until the entry expired. Below Redis 7.0, which does not count the entries a group read, any trim past this node's last delivery counts as a loss, even one that removed only entries this node had read. From 7.0, the consumer group is created with the count of entries before it (ENTRIESREAD), so a trim before its first read shows and entries trimmed before it existed do not count. Where Redis cannot tell the count, as after a read past a deleted entry, the count last found at the same position stands in; with none found, a trim past the last delivery counts as a loss. The topic signals the loss through the newIEventSubject<T>.Invalidate(MissedEventsReason):Lostfor a Streams loss, which every cache honors, andSubscriptionGapfor the Pub/Sub delay above. Breaking for a custom subject passed to theRedisPubSubTopicorRedisStreamsTopicconstructor: implementInvalidateto expire what its observers keep. The library's change tokens implement the new publicIMissedEventsObserver, so such a subject callsOnEventsMissed(reason)on each observer that implements it. A customIChangeTokenFactoryneeds no change: for a cache that keeps its entries over a subscription gap, it is handed a view of the topic whose observers do not hear the gap. -
Multi-key reads keep a usable local copy.
GetAsyncandGetCacheEntriesAsyncover several keys stored each inner-tier hit locally as a key-value pair rather than as the value, so no later read found it and every one went back to the inner tier. A hit is now kept as a single-key read keeps it, forLocalMaxExpirationDisconnectedwhile the inner tier is disconnected. -
The key prefix no longer depends on
RedisCacheOptions.KeyPrefixbeing set. A connector whoseIDatabaseis wrapped withWithKeyPrefixstores every key under that prefix, and two places need it: the stream maintainer, to scan for and strip it, and the cluster slot check, to hash the key the server receives. Both relied onKeyPrefixrepeating the value, so a deployment that left it empty had a maintainer that found none of its streams, since the default SCAN pattern named keys without the prefix. The prefix is now read from the connector's database: directly from StackExchange.Redis's own wrapper, or, behind a decorator, by sendingECHOwith a key argument once per connector, which the wrapper prefixes.KeyPrefixremains the fallback when neither answers, and an error is logged once when a configured value disagrees with the connector. A connector prefix that is not UTF-8 or holds a SCAN glob character (*,?,[,],\) is skipped with a warning, andKeyPrefixis used instead. AKeyPrefixholding one of those glob characters is skipped the same way, and no prefix is assumed, since*or?would widen the maintainer's SCAN to other keyspaces. An explicitMaintainerSearchPatternis still used as written.
-
ResiliencePoliciesOptions.DisruptionRequestTimeout. ReplacesRequestTimeoutwhile an announced window is open, so a cap tight enough to fall through to another tier does not cut short a window the client is deliberately relaxing its own timeouts for. Resolved per operation through Polly's timeout generator rather than read at build time, so a window opening after startup is honoured. Left unset, the tier's own suggestion applies —IDisruptionState.SuggestedTimeout, which the Redis tier offers only for an announced push window, since the Azure probe route opens no native relaxation. The Azure route does not widen the cap either: its probe run lasts ten minutes whatever the maintenance did. Neither can shortenRequestTimeout, and with noIDisruptionStateregistered one timeout applies throughout. -
IDisruptionState, the two-member seam the pipeline asks whether the tier behind it is disrupted and what it is relaxing to. Without a registration, behaviour is unchanged. -
Maintenance notifications from either source.
RedisPlannedMaintenancerecognised onlyAzureMaintenanceEvent, the pub/sub notifications Azure Cache for Redis publishes, and returned on anything else — so the RESP3 push notifications Redis Enterprise and Redis Cloud send asPushMaintenanceEventwere discarded — as will Azure Managed Redis be, once its rollout lands and the option is set for it. Both are handled now, and a source neither of them models is recorded from the base event rather than dropped, so a provider added upstream is visible rather than silent.RedisConnectionOptions.MaintenanceNotificationsopts in, defaulting to the client's own behaviour. It takesRedisMaintenanceNotifications, a neutral enum of this library's own, because the StackExchange type is marked experimental and would otherwise raiseSER010in every consumer that set the option. A value outside the enum is refused with anInvalidOperationException— it arrives from configuration, not as an argument. Notifications arrive from the connection carrying commands, through the newIRedisConnector.ServerMaintenance, and one can be delivered more than once -- Azure's is a broadcast a retiring connection still forwards alongside its replacement, and a push frame is replayed to a connection that reconnects. A copy matching one recorded in the retention window is therefore dropped, on the notification's own identity rather than on which connection ought to have had it. The retention is the maximum window plus its post-event tail, floored at 30 seconds -- see the fix below for why a fixed interval was not enough. A push notification opens a maintenance window rather than probing — the client hands the connection off itself, and probing would force a reconnect against it — for as long as the server announced, clamped to the range the client relaxes its own timeouts over (MaintenanceRelaxedTimeouttoMaintenanceRelaxedWindowMax) and held throughMaintenancePostEventRelaxedDurationafter a completion, so the two agree by construction; and tracked per operation family, so one completion cannot close another's window. The bounds are read from the connection that delivered the notification, configurators included, so a window is sized right from the first notice. The two routes report one pair ofRedis.MaintenanceStarted/Endedevents between them rather than one pair each, since they can overlap. -
IRedisConnector.ServerMaintenance, the maintenance the server announced on the connection carrying commands. Defaulted to never raising, so an existing implementer is unaffected. It exists because the connector is what rebuilds that connection, so one subscription here survives aForceReconnectwhere subscribing to the multiplexer directly would not. -
IRedisConnector.GetPrimaries(), the connected primaries a server-scoped command such asSCANhas to be sent to one by one. Defaulted to an empty sequence, so an existing implementer neither breaks nor changes behaviour.
-
Dependency floors. What a consumer's restore has to satisfy, taken from
Directory.Packages.props:Package 2.0.1 2.1.0 StackExchange.Redis(UiPath.Caching,UiPath.Caching.Queue)3.2.1 3.3.0 AsyncKeyedLock(UiPath.Caching)8.0.2 8.1.2 The
Microsoft.Extensions.*and Polly groups are unchanged. TheOpenTelemetrypackages also moved, but only tests and samples reference them, so they are pins of this repository, not floors on consumers. -
RedisConnectionOptions.ConnectionFactoryis asynchronous. It is nowFunc<ConfigurationOptions, CancellationToken, ValueTask<IConnectionMultiplexer>>and is awaited. The synchronousFunc<ConfigurationOptions, IConnectionMultiplexer>was called from inside the async connect, so a factory that needed async work, such as acquiring a token or retryingConnectAsync, had to block a thread-pool thread for the whole attempt. The token is the connector's lifetime: one connection serves every caller, so it is cancelled when the connector is disposed rather than by any one caller. Breaking: a factory assigned in code no longer compiles; use an async lambda, for exampleasync (options, token) => await ConnectionMultiplexer.ConnectAsync(options). For Entra authentication,AddAzureEntraAuthentication()needs no factory at all. -
The read pipeline now returns at
RequestTimeout. Polly's timeout is cooperative: it bounds a callback that observes the token it arms, and the Redis client takes no cancellation token, so on those pathsRequestTimeoutbounded nothing and the retry, breaker and fallback downstream never saw a failure to act on. The read pipeline now races the callback against that token, which carries the request timeout and the caller's own token alike, so control returns to the caller when either fires. This is fixed rather than configurable, and only the read pipeline does it: a write can carry memory the caller reclaims on return, and a custom pipeline can guard a destructive read such asSPOP. The abandoned call still runs underneath and its later failure is observed. A timeout is no longer retried, since the abandoned command is still in flight, and a caller's own cancellation no longer counts toward the circuit breaker. This changes caller-visible timing on reads: an operation that previously ran pastRequestTimeoutnow returns at it. -
RedisConnectionOptions.FailFastBacklogPolicynow defaults totrue. Queuing while disconnected makes a command wait out the connection's timeout with nothing to wait for. Setfalseto restoreBacklogPolicy.Default. This changes behaviour for disconnected commands: they now fail fast rather than queue.nullno longer means the library default: it fails fast liketrue, and so does a JSONnull, as the shippedappsettings.all.jsonhad it, whether the binder leaves the new default or writesnull. Onlyfalserestores queuing. The Azure maintenance probe allows for this: a probe rejected while the client is reconnecting on its own no longer forces a reconnect, unless the disconnect outlasts the ten-second hanging time. That holds on a cluster where only the probe key's node is away, when the connection as a whole still reports connected, and each probe run counts the disconnect afresh. The ten-minute run is measured on the injectedTimeProvider. -
A departed cluster node is dropped in about a minute rather than six.
StaleEndpointThresholddefaults to one minute instead of five, and a reconfiguration the client reports throughConfigurationChangedruns the scan five seconds later without waiting the threshold out. Neither loosens what decides a rebuild: the node must still be absent from, or flagged failed in, the topology the client refreshes. That check is the only gate other clients use — Lettuce and ioredis close connections to nodes the refreshed topology no longer lists — and cloud guidance for them refreshes every 5 to 60 seconds. A burst of reconfigurations is judged once, and the scan's own refresh, which the client reports later on a worker, is not taken for a change. -
A maintenance handoff is no longer reported as a connection failure. When the client moves off an endpoint the server said is going away, it raises
ConnectionFailedwithConnectionFailureType.MaintenanceHandoff. That was tracked asRedis.ConnectionFailed— byRedisConnectorand again byConnectionStateMonitor— which would alert on exactly the event advance notice exists to make uneventful. Both now track it asRedis.MaintenanceHandoff. The event is still raised to subscribers — the connection did drop — and only the telemetry name distinguishes them. -
RedisHealthCheckreports "Redis maintenance in progress" rather than naming Azure Cache for Redis, now that either route can open the window. -
Bumped
StackExchange.Redisfrom 3.2.1 to 3.3.0. No public API change here, and nothing in this repository calls an API 3.2.15 or 3.3.0 altered. Three things in the range are worth knowing:SwitchPrimarynow retires the servers its rebuild drops (upstream #3225). They previously stayed in the server snapshot — connected and selectable — and the snapshot is whatIConnectionMultiplexer.GetServers()reports, so on a Sentinel-managed connectionIRedisConnector.GetPrimaries()could hand the stream maintainer a node no longer part of the service, and occasionally the same address twice.IServer.Executesupplies the configured default database rather than refusing a database-specific command (upstream #3237). The maintainer passes the database explicitly regardless, so it does not depend on this.- Server-native maintenance notifications arrive as opt-in, through
maintNotificationson the connection string orConfigurationOptions.MaintenanceNotifications. Surfacing them is a behavioural decision rather than part of a version bump, and is covered by theMaintenanceNotificationsentry under Added above.
-
Dropped the
SER007suppression inRedisStreamSubjectWriterTests.RedisErrorKindis no longer marked[Experimental]in 3.3.0, so the pragma suppressed a diagnostic that is no longer raised.
RedisPlannedMaintenance's constructors. It takes(ICachingTelemetryProvider, IRedisConnector, TimeProvider)now; the configuration provider, multiplexer factory, logger, options and configurators went with the connection they built. Resolving it from the container is unaffected. Binary-breaking for code that constructs it directly.RedisConnectionOptions.PlannedMaintenanceConnectionRetryCountandPlannedMaintenanceConnectionRetryDelay, shipped in 1.1.0. They tuned the connection planned maintenance no longer opens. Configuration that still sets them binds without error and is ignored; code that sets them no longer compiles.
-
Planned maintenance kept a second Redis connection that retried departed nodes forever.
RedisPlannedMaintenanceopened a multiplexer of its own at startup to listen for Azure's maintenance broadcast. When a cluster moves a shard to another node, every connection keeps the node that left, and StackExchange.Redis retries it for the life of the process, logging each refused handshake as an error. The stale-endpoint scan rebuilds only the connector's connection, so this one went on retrying each departed node every twenty seconds until the process restarted. Notices now come only throughIRedisConnector.ServerMaintenance, from the connection carrying commands, which already delivered Azure's broadcast as well as push frames, so the rebuild covers everything the service listens on. It opens no connection, so withWarmUpOnStartoff the first connection, and any Entra token, waits for the first cache use again. A customIRedisConnectorthat leavesServerMaintenanceat its never-raising default now delivers no notices at all. -
No task the library lets go of can surface as an unobserved exception. Commands queued on a transaction, background loops, fire-and-forget work and probes abandoned at their timeout were discarded without anything observing a later failure, which
TaskScheduler.UnobservedTaskExceptionthen reported. Each now observes its own. -
A refused
Redis.Maintenancerecord no longer releases the notification's deduplication claim. Recording a notification also opens and closes health windows, so releasing the claim when the record failed let a replayed frame apply the same state change twice — a second operation no single completion closes, or a close while maintenance is still running. The record is guarded instead: a refused one is reported and dropped, and the claim stands. Losing an event is the lesser harm. -
MaintenanceRelaxedWindowMaxcaps a largerMaintenanceRelaxedTimeout. The floor was applied after the maximum, so an announcement below the floor returned the floor even when it exceeded the documented cap, and health suppression outlived the window the client actually relaxes over. -
A replayed push frame could open a second operation or close someone else's. The deduplication claim was retained for a fixed 30 seconds while an announced window can run far longer, so a frame replayed to a reconnecting connection after the claim lapsed was taken as new: a starter appended an operation the one real completion could not close, and a completion removed another operation still running. The retention now covers
MaintenanceRelaxedWindowMaxplusMaintenancePostEventRelaxedDuration, the full span over which a window can still be holding the state, whenever that exceeds the 30-second floor. -
An explicit
maintRelaxedTimeoutin the connection string is no longer derived over. With the typed option unset, the derived value replaced whatever the string supplied — whilemaintRelaxedWindowMaxin the same string was preserved. A value from either input now counts as configured, detected by the key's presence rather than its value — an explicit setting that happens to equal the client's default is still a setting. -
A throwing subscriber cost the remaining ones their notification.
RedisConnectorandConnectionStateMonitorraised their connection events with a plain multicast invoke, which stops at the first handler that throws;ForceReconnectcaught the exception, but around the whole invocation list rather than around each handler, so the outcome was the same. Reconnection is how the pub/sub writer, the stream notify channel and the stream subject writer re-subscribe, and the pub/sub writer's handler can throwObjectDisposedExceptionwhen a dispose races the notification — one such throw left every subscriber after it in the list detached until the next reconnect. Handlers are now invoked one at a time with per-handler tracking, on every event of both types. This also covers the newServerMaintenance, which the client raises on its own dispatch thread and which had no guard at all, andConnectionStateMonitor, whose own re-multicast toIConnectionStatesubscribers sits inside the connector's — so a throw from one of those aborted the connector's list as well. Reporting the caught failure is itself guarded, since a sink that cannot take the report would otherwise put the exception back on the path the boundary exists to keep clear. -
A notification whose recording threw was suppressed for the next 30 seconds.
RedisPlannedMaintenanceclaimed a notification's identity in its deduplication set before handling it, so a handler that threw -- starting the Azure probe loop, or emitting theRedis.Maintenanceevent -- recorded nothing while every matching copy was collapsed into a record that did not exist. The claim is still taken up front, so a concurrent copy from another connection still collapses, but it is committed to the retention queue only once the recording succeeded and released otherwise. It is timestamped on commit rather than on claim, so the queue stays ordered by expiry when two copies record concurrently. Cancelling the service is guarded the same way:CancellationTokenSource.Cancelruns its registrations inline, so it raises what a caller's callback threw, and that leftStopReactingbefore its open windows had been closed. A probe run now marks itself started only onceRedis.MaintenanceStartedhas been emitted, so a run that could not announce its start no longer emitsRedis.MaintenanceEndedagainst nothing, and clearsInProgressahead of the rest of its cleanup, since leaving it set would make the guard refuse every later run. Reporting a failed probe no longer precedes theForceReconnectit must not cost, and neither interval announcement can end the run: a sink that refusedRedis.MaintenanceStartedused to kill the worker before it reached the probe loop, so the Azure route stopped recovering at all. -
A rejected connection candidate stayed the newest multiplexer.
RedisConnectormarks each candidate as the incoming generation before its handlers go on, so aMOVINGarriving before the swap is still taken. A candidate the swap then rejected — a disposal or a newer reconnect won the race — was disposed without clearing that marker, leaving a disposed multiplexer referenced until the next reconnect replaced it. The marker is now compare-and-cleared as that instance is disposed, before its handlers come off. The maintenance handler also closes over the connection it was attached to rather than reading the event's sender, since a composite multiplexer can attach it to its children and raise with a child, which belongs to no generation the connector knows about — aMOVINGfor the connection carrying commands would have been dropped. The raiser is still used, for the opposite question: a group attaches the handler to every member, so aMOVINGis taken only when it came from the member currently carrying commands.IConnectionGroup.ActiveMemberis public butConnectionGroupMember.Multiplexeris not, so that link is read reflectively and the check is skipped whenever it cannot be made — a spare notice costs a record, a lost one costs the handoff. -
A refused telemetry report could defeat the catch that made it. Every
catchinRedisConnectorandRedisPlannedMaintenanceexists so the surrounding work carries on, and each reported through the sink directly — so a sink that threw took the recovery with it. They report through the guarded helper now. The worst of them wasGetVersion, the factory behind aLazy<Version>: aLazycaches what its factory threw, soIRedisConnector.Versionwould have thrown for the life of the process instead of falling back once. The same holds for recording an event where recovery follows it: a refusedRedis.ForcedReconnectskipped both theOnReconnectedmulticast and disposal of the retired connection, and a refusedRedis.StaleEndpointDetectedorRedis.HangDetectedskipped theForceReconnectit exists to announce. Every record raised on StackExchange.Redis's own dispatch thread is guarded for the same reason, andConnectionStateMonitorguards its records in one place, since each precedes both a state reset and a multicast to its own subscribers. -
Azure notifications the client could not parse shared one identity. Such a payload leaves every field at its default,
RawMessageincluded, so the deduplication key was the same for all of them and two unrelated ones arriving within the retention window collapsed into one record. They are recorded individually now, the way a push frame whose sequence could not be read already was. A notification whose type is unrecognised but whose other fields parsed still has an identity and still collapses.Redis.Maintenancealso recordsReceivedTimeUtcandStartTimeUtcin the round-trip format on every route, rather than the general invariant pattern on two of the three, so a query over the field does not have to guess which route wrote it. -
A consumer group with a stale last-delivered-id skipped its quarantine. The maintainer quarantines such a group by recording the instant in a hash field and deleting it once
MaintainerQuarantineIntervalhas passed — which is whatCheckEmptyStreamGroupAsyncdoes for a group with no consumers. The stale-last-delivered-id path wrote the same timestamp but never read it back, deleting on the field's mere presence. Two maintenance passes that overlap — which the distributed lock permits, since it expires onMaintainerCheckIntervalrather than when the pass finishes — therefore collapsed the wait to nothing: one pass wrote the record, the other deleted the group on it in the same cycle. Even without an overlap the wait wasMaintainerCheckInterval(30 min by default) rather than the documentedMaintainerQuarantineInterval(1 h). Both paths now read the recorded instant through one helper, so a group is deleted only once it has actually served the interval. The timestamp is read from the primary, like every other command this maintainer issues: a replica that had not caught up could report one the primary had already deleted, and the group would be reaped without serving any wait at all. -
Stream maintenance reached only one shard.
RedisStreamHealthMaintainerdiscovered streams with a keylessSCANsent onIDatabase. A keyless command carries no slot for the client to route by, so it reaches whichever single server the multiplexer picks, and its cursor walks that server's keyspace alone. On a cluster every broadcast stream whose slot lived on another primary was never discovered, and so never trimmed toMaintainerTrimInterval, never group-reaped and never deleted — held only by theMAXLENeachXADDcarries, which leaves the lastMaxLengthentries (32,768 by default) in place of the intended window, on a key that has no TTL and so is not reclaimable under avolatile-*eviction policy. The maintainer now scans every connected primary, each with its own cursor, each scan carrying the configured database so it reaches the same keyspace the routed one did. The scans run concurrently, so a pass costs the slowest shard rather than the sum of them, and their results are merged as a set, so a slot caught mid-migration on both its source and its target primary is still maintained once. A connector that reports no primary keeps the previous single-server scan, and a primary that cannot be reached costs only its own shard that cycle instead of aborting the pass. Present since the maintainer was first added and invisible on a single-shard server, which is why it went unnoticed — and because the slot-to-shard mapping moves when a cluster is resized, which streams went unmaintained moved with it.
-
Dependency floors. What a consumer's restore has to satisfy, taken from
Directory.Packages.props:Package 2.0.0 2.0.1 StackExchange.Redis(UiPath.Caching,UiPath.Caching.Queue)3.1.31 3.2.1 Polly.Core,Polly.Extensions(UiPath.Caching.Polly)8.7.0 8.8.0 The
Microsoft.Extensions.*groups are unchanged.Aspire.Hosting.Redis,Microsoft.Testing.Extensions.CodeCoverageandOpenTelemetry.Instrumentation.StackExchangeRedisalso moved, but only tests and samples reference them, so they are pins of this repository, not floors on consumers.
- The cluster slot check honors
RedisCacheOptions.KeyPrefix. AnIRedisConnectorwhoseIDatabaseis wrapped withWithKeyPrefixprepends that prefix to every command, so the key the server hashes is the prefixed one — but the check hashed the composed key without it. An application whose prefix carries the hash tag, which is how a deployment keeps its whole keyspace on one slot, had every multi-key batch refused withCrossSlotKeysExceptionalthough Redis would have run it: found on an Azure Managed Redis (OSS cluster policy) where a{tag}:prefix turnedGetCacheEntriesAsyncinto a 500. The check now hashes the key as it is sent. Nothing changes when the prefix is empty, and a batch that genuinely spans slots is still refused.
-
Named caching stacks: a second Redis connection.
services.AddNamedCaching(name, configuration, chain)registers a complete second caching stack on its own Redis server:ICache,IHashCache,ICache<T>,IHashCache<T>,IDistributedLock,ILocalLock, broadcast topics, warm-up and planned maintenance, all again, reached through keyed services under the stack's name ([FromKeyedServices(name)]), the stack'sICacheKeyStrategyandICachePolicyFactoryincluded, so its typed caches address the same keys as its unkeyed ones. The stack reads the sameCachingsection as the primary, so every cache option is shared, and its connection isConnections:{name}laid overConnections:Redis, so a connection key it leaves unset is inherited. It has its own L1 memory caches, locks and hosted services; logging, telemetry, the clock and key masking are shared with the application.INamedCaching.Expose<T>()reaches anything else the chain registers; the Queue package'sExposeQueueCaches()addsISetCache,ISetCache<T>andIQueueCacheFactory. Registration refuses a stack with noConnectionStringof its own unlessconfigureConnectionsupplies one, the nameRedis, and a duplicate name; first resolution refuses a chain that adds its own connection, a connection that resolves to nothing or to the application's primary one, and aKeyCasingthat differs from the application's, wherever it was set. Recipe: docs/recipes/second-redis-connection.md. The sample app runs two stacks against two Redis containers provisioned by the Aspire host. -
Key masking in logs (#129). A cache key is the caller's, so it can be a secret; the library names keys in log lines throughout.
builder.AddKeyMasking(prefixes)turns masking on, andAddKeyMasking<TPolicy>()takes anIKeyMaskingPolicyof your own, which is asked whether one key is secret and is given the key, what the cache holds when the site knows it, and which provider is logging. A masked key keeps its first three characters, so two lines about one entry still correlate; a key of three characters or fewer keeps none. Whatever the key strategy composed around the key stays readable, and a key that is plainly an identifier, a number or a GUID, is left alone. Off by default: the container resolvesNullKeyMaskingPolicyand nothing changes. Nothing is rendered, masked, or even converted to text unless the line is actually written, so a disabled level costs nothing. It reaches every component that names a key, including the multilayer local setter, the rehydration coordinator, the broadcast change token and the event publisher, not only the caches.AddDistributedCacheis not subject to the application's policy:IDistributedCachekeys belong to the consumer, so the adapter and the private tiers it configures always mask. -
IDistributedCacheadapter.builder.AddDistributedCache(providerName)registers aMicrosoft.Extensions.Caching.Distributed.IDistributedCachebacked by this library's pipeline — shared Redis connection, resilience, telemetry — so consumers that require it (ASP.NET Core session state, OpenIddict, DataProtection, rate limiters, andHybridCacheas an L2) stop running a second, parallel Redis stack. The backing tier is a required argument (Redisrecommended,InMemoryRedis, orInMemory); full absolute + sliding expiration andRefreshsemantics are supported. Keys are always case-sensitive, independent ofCacheOptions.KeyCasing, becauseIDistributedCachekeys are opaque and case-significant. Entries are stored as a Redis hash (data,absexp,sldexp— the conventional layout for this contract) in a keyspace disjoint from the application's own caches, soRefreshreads only the expiration metadata rather than transferring the payload. Keyspace separation is configurable at both levels:CacheKeyStrategyprefixes theCacheKeyitself (d:by default) so a distributed entry cannot be reached through the application's ownICache/IHashCachewith the bare caller key, andRedisKeyDifferentiatorplusRedisKeyStrategyFactoryseparate the physical Redis keyspace (dhby default, inheriting the application's factory). A differentiator matching one of the application's own reserved keyspaces is rejected at registration, and because a differentiator only separates anything if the factory honors it, resolving the cache also proves the composed key differs from what the application's caches would produce. Configurable viaUiPathDistributedCacheOptions:PolicyName,DefaultEntryExpiration, andAllowUnboundedEntries. Writes with no caller expiration take a bounded default rather than living forever in shared storage; an unset default resolves toCachePolicy.DefaultDistributedExpiration, and onlyAllowUnboundedEntriesreaches "until removed". -
IBufferDistributedCache(net9.0+). The adapter registered byAddDistributedCachealso implements the buffer-based half of theIDistributedCachecontract, so a caller reads into anIBufferWriter<byte>and writes from aReadOnlySequence<byte>instead of trading a fresh array per operation —HybridCacheas an L2, output caching and session state all take that path once they find it. Discovery is the framework's own: a type check on the resolvedIDistributedCache, so nothing extra is registered and no consumer code changes. Both halves share one read and write path — same keyspace, expiration, sliding and stored fields — so an entry written through either is readable through the other and by any other client on the conventional layout.TryGetreports hit and payload separately, the one thing the array half cannot express: an entry stored empty is a hit that writes no bytes, whereGetreturns an empty array for that and for a miss alike. What happens to the caller's buffer on a write depends on the tier: onRedisa single-segment sequence is handed to the connection as the caller's own memory — no array in between — and a segmented one is flattened into a rented buffer that is returned once the write has been awaited; the memory tiers keep what they are handed, so there the sequence is copied into an owned array. Either way a pooled buffer is safe to reuse the moment the call returns. The adapter's values travel asReadOnlyMemory<byte>throughout, and its expiration fields are parsed and formatted straight from UTF-8 with no intermediate string.NullDistributedCacheimplements it too, so switching caching off does not change which half a consumer discovers. Not present onnet8.0: that floor pinsMicrosoft.Extensions.Caching.Abstractionsto 8.0.0, which predates the interface, and the type check simply comes up empty there. -
IMemorySerializerProxy, an optional refinement ofISerializerProxy<byte[]>for a serializer that can hand back memory without materializing an array:ReadOnlyMemory<byte> SerializeToMemory<T>(T? value).SystemJsonByteSerializerProxyimplements it as its array output wrapped — a byte payload is still base64 inside JSON, so the wire format is one thing whichever member a tier calls — andRawByteSerializerProxypasses aReadOnlyMemory<byte>orMemory<byte>through untouched.RedisCacheandRedisHashCacheask for memory when the configured serializer offers it. The memory is borrowed: it may alias the value it came from and is valid only until the operation completes, which the Redis tier honors by copying it into the connection's buffer as the command is written and awaiting the write to completion. That last part is a contract onIResiliencePipelinetoo — itsExecuteAsyncmust not complete before the callback has — and the Polly pipeline this library ships awaits throughout. -
ReadOnlyMemory<byte>is a cacheable value type.NotCacheableExceptionadmits it alongside classes and nullable structs: its default is empty memory, which the storage tiers already read as absent, so a miss has something to return. The raw serializer had special-cased the type in both directions without any cache being able to reach it. Like a zero-length payload, an emptyReadOnlyMemory<byte>value is indistinguishable from absent.Memory<byte>stays out — a cache must not hand back a window it can be written through. -
Topic keys are computed once per type.
DefaultTopicKeyStrategymemoizes the key it derives from a value type. It runs on every operation of the memory-backed tiers, and for a generic value type — aList<T>, and now the distributed adapter'sReadOnlyMemory<byte>— the friendly name was rebuilt with aStringBuildereach time, about 260 bytes per call; a non-generic type's name was a cached lookup, so the cost went unnoticed. The keys themselves are unchanged. -
Benchmarks.
DistributedCacheBenchmarkcovers both halves of the contract per tier and payload size with allocation columns; the harness now finds the sample'sappsettings.jsonundersamples/, which had moved from under it. -
CacheOptions.KeyCasingselects how keys built without an explicit mode are normalized —Insensitive(trim + lowercase, the historical behavior and the default) orSensitive(preserve the caller's casing).CacheKeygained a(string?, CacheKeyCasing)constructor, aCasingproperty, andWithNameso key transformations preserve the mode. Changing the app-wide setting relocates every cache key, so existing entries are rewritten under the new spelling. -
CacheKeyComparerexposes cachedSensitive/Insensitiveequality comparers overCacheKey, in theStringComparershape. -
ISerializerProxy<byte[]>is now the library's only serialization seam, replacingISerializerProxy<RedisValue>everywhere — see Removed below. The serialization contract no longer names a Redis type, so a custom serializer needs no dependency on StackExchange.Redis, and one registration coversICache,IHashCacheandISetCache. Swapping in a binary serializer such as MessagePack is one class and one registration — see how-to/extending.md. Two implementations ship:SystemJsonByteSerializerProxy(the default) is UTF-8 JSON for every value, which is byte-for-byte the formatSystemJsonSerializerProxywrote — no cache entry needs migrating, byte payloads and nulls included.RawByteSerializerProxystores byte payloads verbatim — no base64, no JSON, no encoding layer — and JSON for every other type.AddDistributedCacheconstructs this for the provider it builds rather than resolving one from DI, because anIDistributedCachepayload is caller bytes the caller has already serialized and re-encoding them would be both wasteful and wrong; that also means replacing the app-wide serializer does not change what the adapter stores. Registering it app-wide is available as an opt-in, and is a wire-format change: it returns stored bytes as-is rather than base64-decoding them, so relocate the keyspace (a version segment inAppShortNameor the cache-key strategy) when switching an existing deployment over.
-
RedisCacheOptions.AwaitRefresh(defaultfalse) waits for the server to apply a refresh instead of sendingKEYEXPIRE/PERSISTfire-and-forget. Off by default, which keeps the round trip off the sliding-expiration path — it runs on every read of a sliding entry — and preserves existing behavior.AddDistributedCacheenables it on the private provider it builds, because a silently dropped refresh shortens a session and fire-and-forget cannot report one. Honored by bothRedisCacheandRedisHashCache. -
Conditional add:
ICache.TryAddAsync/ICache<T>.TryAddAsync(+ blockingICache<T>.TryAdd). Writes a key only if it does not already exist, returningtrueonly to the caller that created it. On Redis-backed caches this is StackExchange.RedisWhen.NotExists—SET key value EX … NX— a single atomic round-trip with the TTL applied by the same command, so exactly one caller across all nodes wins a given key and a won key is never briefly immortal. Intended for at-most-once semantics keyed by something: idempotency keys, dedup markers whose TTL is the dedup window, electing which replica runs a job.falsedeliberately conflates "the key already existed" with "the write could not be completed" (disconnected, threw, or anull/defaultvalue the cache cannot represent) — fail-closed, so a caller treatingtrueas "I own this key" is never wrongly told it won; the same conflationIDistributedLock.TryAcquireAsyncalready documents. UnlikeSetAsync, it never deletes: whereSetAsyncremoves the key when handed anullwithCacheNullValuesoff,TryAddAsyncreportsfalseand leaves the key untouched. Per tier:RedisCacheissues theNXwrite;MultilayerCacheruns one sequence for every provider — take the local lock, probe the local tier, ask the L2, populate L1 (plus an invalidation broadcast) on a win, best-effort. A broadcast or L1 failure never downgrades a real win tofalse, since that would strand the entry with no owner; with the L2 disconnected the call returnsfalserather than granting a local-only claim every node would also be granted (SetAsyncdegrades to a local write there). The probe is what bounds exclusion at one winner per process, and the only thing doing so on theInMemoryprovider, whoseNullCacheL2 tells every caller it added the key; it also reports a local hit as a loss without asking the L2, which is fail-closed but costs a win the L2 would have granted when the local copy outlived the shared one. The local lock is what makes that probe-then-write atomic, so a conditional add takes it regardless ofLock.LocalLockEnabled(which trades single-flight for throughput onGetOrAddAsyncand must not be able to hand one key to two callers), and a caller that cannot acquire it withinLock.LocalLockTimeoutis told it lost rather than proceeding unserialized. The L2 itself is only ever asked, never classified by type or provider name, so a provider a consumer registers participates on the same terms — with the corollary that an L2 arbitrating in-process only is trusted as though it arbitrated for every sharer. On theInMemoryprovider no invalidation broadcast is published:ChangeTokenFactoryaccepts onlyCacheRemovedandCacheRefreshedthere, so peers ignoreCacheSet— deliberately, since each node's memory is the store rather than a copy of a shared one. An expiration that is not in the future reportsfalseon every tier: the entry would be evicted on arrival, so atruewould be handed to every later caller as well.NullCachereturnsfalse— the one member where it does not degrade to "caching is off, carry on", because it cannot complete the write (which is exactly what a fail-closedfalsemeans) and becausetruethere would hand every caller a claim of exclusive ownership; it is reached by accident, being whatICacheFactory.CreateCacheresolves to when the requested provider is absent or hasEnabled=false. Added to both interfaces as default interface methods, so required members rather than default interface methods: a probe followed by a write is not atomic, and no fallback body could stand in for one without either voiding the guarantee or hiding which stores can arbitrate, so an implementation states what its own store can do. This is source-breaking for hand-writtenICache/ICache<T>implementations, which must add the three overloads.NullCachereturnstrue, as itsSetAsyncdoes — the null store retains nothing, so no key pre-exists and no caller loses; note that it provides no exclusion at all and is whatICacheFactory.CreateCacheresolves to for an absent or disabled provider, so assert the provider you expect at startup when thetruebranch runs a side effect that must not repeat.CacheExtensionscarries the token-positional overloads (TryAddAsync(key, value, token)and theTimeSpan?/DateTimeOffset?pairs), matchingSetAsync. No multi-key overload: Redis has no atomic multi-keyNX, and all-or-nothing versus per-key semantics would be a guess. This is a cache primitive, not a lock — no ownership token, no early release, and a laterSetAsync/RemoveAsyncignores the claim; for a fencing token and explicit release useIDistributedLock. No conditional-add member was added to the hash surface, whereNXis per-field (HSETNX) and a different shape. -
A cancellation raised while the
SET … NXwrite is in flight now propagates instead of being reported asfalse, which would have claimed the key belongs to someone else — a fact the cancelled call never established. The write itself stays on the sharedWriteresilience pipeline: retries fire on exceptions only, and re-issuingNXis harmless, since an attempt whose reply was lost is refused by the key it just wrote and reports the samefalsethe exception would have, while an attempt that never reached Redis is recovered as thetrueit should have been. -
Stale cluster endpoint detection.
RedisConnectornow rebuilds the multiplexer when a cluster node it discovered has left the cluster but is still being retried. StackExchange.Redis never forgets a server it has seen, so when a node is replaced — an Azure Managed Redis patch swaps the node VMs and retires their endpoints — the old address is retried and logged as an error every few seconds for the life of the process; only a fresh multiplexer re-reads the topology. EveryStaleEndpointScanInterval(default 30 s) the connector notes which topology-discovered servers are disconnected; one that stays down forStaleEndpointThreshold(default 5 min) is checked againstCLUSTER NODESon a connected server, and if it is no longer a member the connector emitsRedis.StaleEndpointDetectedand callsForceReconnect(). Configured endpoints are never judged stale, a node that is down but still in the cluster is left to StackExchange.Redis, and a non-cluster server is ignored. Opt out withEnableStaleEndpointDetection = false.RedisConnectorgains a constructor overload that takes aTimeProvider; the existing one keeps usingTimeProvider.System.RedisHealthCheckreports the disconnected endpoints underConnectionMultiplexer.DisconnectedEndPoints.
-
A cache key that cannot carry a hash tag is refused rather than wrapped.
ShardPrefixRedisKeyStrategyused to wrap any key without a valid tag, but wrapping one that already holds a brace pairs the added{with it: the tag Redis reads is then only a prefix of the key, so unrelated keys quietly collapse onto one slot —bla{}blawrapped to{bla{}bla}hashes asbla{. Such a key now throwsInvalidOperationExceptionnaming the strategy, which is the ruleStreamSuffixShardedChannelStrategyalready applied to stream keys; both go through one helper now.bla{blapreviously wrapped to a correct tag by accident and now throws as well, as does an empty key, which wrapped to{}— a brace pair Redis reads as no tag at all. Non-empty keys with no braces, and keys with a valid tag, are unaffected. -
BREAKING:
RedisTypePrefixesis nowRedisKeyspaces. The library called the same thing two names — the short segment betweenAppShortNameand the cache key was a "type prefix" in the core and a "keyspace" in the reservation API that packages register against. It is a keyspace everywhere now: the class, the error messages, and the docs. Only the type rename is a break;IReservedRedisKeyspaceships for the first time in this release, so itsKeyspacemember had no earlier spelling to migrate from. The constant values are untouched ("s","h","ps","st"), so no Redis key changes and no data moves; only the identifiers do. ReplaceRedisTypePrefixeswithRedisKeyspacesat the call site. "Prefix" now means only what it says:UiPathDistributedCacheOptions.CacheKeyStrategy's key prefix,PrefixStrategy, and StackExchange's ownKeyPrefix. -
BREAKING: an unset expiration no longer means "keep this forever".
CachePolicygainedDefaultDistributedExpiration(1 hour), applied as the floor underCachePolicy.DistributedExpirationand the providers'DefaultExpirationon every write that carries no caller expiration. Previously the whole chain was nullable with nothing underneath it, so a provider whoseDefaultExpirationwas set tonull— in code or bound from configuration — wrote entries with no TTL into shared storage. The 1 hour that four options classes each declared as a property initializer now comes from that one constant, so the value is stated once. Unbounded entries are still available and now have to be asked for: configure a lifetime ofTimeSpan.MaxValue, which is what the providers already read as "no TTL" (SETwith no TTL,PERSISTon refresh).TimeProvider.ToDateTimeOffsetis the single place a duration becomes a deadline, and it saturates atDateTimeOffset.MaxValuerather than overflowing, soTimeSpan.MaxValuereaches the providers as the sentinel they read as "no TTL". The memory-only set tier and the rehydrate write each did that conversion themselves with a bareAddand threw on it; both go through the clock now. Jitter leaves that sentinel alone: jitter spreads an expiry that is coming, and clamping an unbounded lifetime would put the key back on theEXPIREpath.The floor is on the write paths only —
MultilayerCacheBase.ResolveWriteDuration,RedisCacheBase.PolicyDuration/GetExpiration— deliberately not in the resolved default policy, so "nothing configured" stays observable asnulland a read never consults a default: a key that genuinely has no TTL in Redis reportsDateTimeOffset.MaxValuerather than a fabricatednow + default.MultilayerCacheBase.ResolveWriteDurationreturnsTimeSpanrather thanTimeSpan?as a result. -
BREAKING:
CacheClockis gone (see Removed); the clock isSystem.TimeProvider. No default expiration is carried anywhere near the clock any more. Previously a configuredDefaultExpirationwas also filled in on reads —GetCacheEntryAsyncon a key with no TTL in Redis reportednow + DefaultExpiration, whileExpireTimeAsyncon the same key returnednull— and the fabricated deadline doubled as a hidden L1 cap: the L1 copy of a no-TTL key turned over everyDefaultExpiration. Reads now reportDateTimeOffset.MaxValuefor such a key, and the L1 copy lives until a broadcast invalidation orLocalMaxExpirationevicts it, which is what that knob is for. Write paths are unaffected: every one resolves its lifetime before asking the clock.GetOrAddAsyncresolves the lifetime once and uses it for both the write deadline and the rehydrate threshold. These were two separate chains, and the floor would otherwise have applied to only one of them: entries written under the default would expire after an hour while proactive rehydration, still bottoming out atnull, never fired. Only the write is jittered: the rehydrate threshold and timeout are measured against the configured, unjittered lifetime, so a hit crosses the soft-TTL threshold at the same point on every read rather than against a fresh random draw. Rehydration is skipped for an unbounded lifetime, which has no deadline to pre-empt. -
BREAKING: every conversion from a duration to a deadline goes through the
TimeProvider, so a per-callTimeSpan.MaxValuemeans "no TTL" on every surface. It already did onRedisCache.SetAsync(the driver maps it) and on the set caches, butMultilayerCache.SetAsync,RefreshAsyncandGetOrAddAsync,RedisCache.RefreshAsync, andRedisHashCache.GetOrAddAsync/RefreshAsync/SetAsynceach added the duration to the clock themselves and threwArgumentOutOfRangeExceptionfromDateTimeOffset.Addinstead; aLocalMaxExpirationofTimeSpan.MaxValuethrew on every L1 write. The sentinel now survives the other direction too: a per-call deadline ofDateTimeOffset.MaxValuebecomes a duration ofTimeSpan.MaxValuerather than a finite eight thousand years, so the rehydrate guard recognizes it. With the downstream add saturating, the two pre-clamps that protected it are gone —MultilayerCacheBase.ApplyJitterno longer trims the jittered lifetime to the clock's remaining range (and takes one clock reading per write fewer), and theIDistributedCacheadapter handsTimeSpan.MaxValueto the backing cache untouched.ApplyJitteris now(TimeSpan, TimeSpan?) -> TimeSpan;RedisCacheBase.GetExpiration(TimeSpan)is added. -
BREAKING: one clock.
System.TimeProvideris the single source of "now".AddCachingregistersTimeProvider.Systemunless the container already has aTimeProvider, and every provider, cache base class, helper, the profiler and the stream maintainer take it from DI. No library clock type remains: the BCL's own seam is the one, and anyTimeProvidersubclass drives it in tests. The per-optionsClockproperties are gone (see Removed): they let each cache carry its own clock while theIMemoryCachejudging its deadlines ran on the DI-wide one, so a configured clock made L1 entries expire early or late against the ambient clock, and the memory-only set tier readDateTimeOffset.UtcNowdirectly and ignored a clock altogether. The conversion from a lifetime to an expiration isTimeProviderExtensions.ToDateTimeOffset(...)in the abstractions package, so a fake converts exactly like the real clock. To control time, register aTimeProviderbeforeAddCaching; anISystemClockregistration is no longer consulted. -
IMultilayerSetCacheOptionsis whatMultilayerSetCachereads its settings from — the memory tier's knobs throughIMemoryCacheOptions, plusDefaultExpiration,LocalMaxExpiration,ConnectionMonitorEnabled,ConnectionMonitorPeriod,UseLocalOnlyWhenDisconnectedandLocalMaxExpirationDisconnected— instead of each setting as a constructor argument. Both queue options types implement it:InMemoryRedisQueueCacheOptionsgainsDefaultExpiration, which — likeInMemoryRedisCacheOptions.DefaultExpiration— outranks the Redis tier's own default for sets written through the provider (null, the default, inherits as before), andInMemoryQueueCacheOptionsgains the connection and local-cap settings for parity, which have nothing to observe on a provider with no backing tier and default to off. -
BREAKING:
AddDistributedCacheno longer fails at registration when no bounded default resolves, because that state no longer exists — an unset default now resolves to the floor. The"would store entries without an expiration"throw is removed; the non-positive check stays, since a value someone configured as zero or negative is still a real misconfiguration.UiPathDistributedCacheOptions.AllowUnboundedEntrieskeeps its meaning and is now the only way to reach an unbounded entry through that adapter without naming a lifetime. -
BREAKING: the per-call
expirationis no longer nullable. Every write onICache,ICache<T>,IHashCache,IHashCache<T>,ISetCache,ISetCache<T>and their extension surfaces takesTimeSpan/DateTimeOffsetinstead ofTimeSpan?/DateTimeOffset?. The nullable was a redundant third state: each of these members already has a sibling overload with noexpirationparameter, and passingnullmeant exactly the same thing as not passing it — fall back toCachePolicy.DistributedExpiration, then the provider'sDefaultExpiration. It also madecache.SetAsync(key, value, null)ambiguous (CS0121) between theTimeSpan?andDateTimeOffset?overloads, which is why the forwarders had to spell out(CachePolicy?)null. Callers passing a real value are unaffected; a caller forwarding its ownTimeSpan?now branches on it and calls the overload without an expiration for the null case. Nullability stays where it means inherit —CachePolicy.LocalExpiration/DistributedExpiration, the providers'DefaultExpiration,HashCacheEntryOptions.ExpireTime/TimeToLive— and on reads, whereTimeToLiveAsync/ExpireTimeAsyncstill returnnullfor a key with no TTL. -
BREAKING: a per-call
expirationthat cannot be honored is now rejected instead of silently absorbed. ATimeSpanthat is not strictly positive, or aDateTimeOffsetat or before the cache's current time, raisesArgumentOutOfRangeException(ParamName"expiration") and nothing is written. Previously such a value was quietly treated as "no expiration" and, onTryAddAsync, answeredfalse— the same answer as "somebody else holds the key". With the nullable gone there is no third state left to carry that meaning, so the argument is refused at the boundary. The new publicCacheExpirationhelper (ThrowIfNotPositive,ThrowIfNotFuture,ToDuration) holds the guard for out-of-tree implementations.TimeSpan.MaxValueandDateTimeOffset.MaxValueremain valid — they are how the providers spell "no TTL".NullCache,NullHashCacheandNullSetCacheread no argument at all and so enforce nothing, keeping "caching is off, carry on". -
BREAKING:
ICache.Compat.cs,IHashCache.Compat.csandISetCache.Compat.csare gone. The pre-CachePolicyconvenience overloads they carried as default interface methods —GetAsync<T>(key, token),SetAsync<T>(key, value, expiration, token),TryAddAsync<T>(key, value, token),AddAsync<T>(key, item, token),PopAsync<T>(key, token)and the rest — now live as extension methods on the newCacheExtensions,HashCacheExtensionsandSetCacheExtensionsstatic classes in the sameUiPath.Cachingnamespace (SetCacheExtensionsships inUiPath.Caching.Queue, alongsideISetCache). Production call sites are unchanged and need no edit; the interfaces shrink to just the policy-bearing members, so an implementation now has one member to write per operation instead of one plus an inherited forwarder it could accidentally override. Moq tests that mock the short forms do break, and not at compile time: Moq reads theSetup/Verifyexpression and refuses a call to a static method, soGetAsync<T>(key, token)orSetAsync(key, value, expiration, token)inside one throwsNotSupportedExceptionwhen the test runs. Re-target the setup at the member the extension forwards to, withIt.IsAny<CachePolicy>()in the new slot, since the extension passesnullthere. NSubstitute is unaffected: it records the call the extension actually makes on the substitute, soReturnsandReceived()on the short form keep working. See Upgrading to 2.0. -
BREAKING:
ICacheOfT.Sync.cs,IHashCacheOfT.Sync.csandISetCacheOfT.Sync.csare gone the same way. The 59 blocking forwarders they carried as default interface methods —Get,GetOrAdd,Set,TryAdd,Refresh,Remove,Contains,TimeToLive,ExpireTime, the hash surface'sGetItem,GetCacheEntry,GetMetadataandSetMetadata, and the set surface'sAdd,Pop,Members,ContainsItem,Count,RemoveItemandRemoveItems— now live on the newCacheSyncExtensions,HashCacheSyncExtensionsandSetCacheSyncExtensionsstatic classes (SetCacheSyncExtensionsships inUiPath.Caching.Queue). Each still blocks on the async member via.AsTask().GetAwaiter().GetResult(); nothing about the blocking behavior changed.Tbecomes a method type parameter inferred from the receiver, so call sites are unchanged, and they stay reachable through the concreteCache<T>/HashCache<T>/SetCache<T>classes as well as the interfaces.partialcomes offICache<T>,IHashCache<T>andISetCache<T>, which nothing else extends now, leaving all three as pure async contracts: an implementation writes only the members it actually implements, rather than inheriting blocking forwarders it could accidentally override. -
BREAKING:
CachePolicy? policyis now a required parameter on everyICache,IHashCacheandISetCachemember that takes one, along with theexpiration/setOptionparameters that precede it — the= nulldefaults are removed.CacheExtensions/HashCacheExtensions/SetCacheExtensionssupply the short forms, socache.GetAsync<T>(key, token)andcache.SetAsync(key, value, expiration)still compile; what no longer compiles is an interface call that relied on the defaults to skip the policy slot positionally. This is also what makes the extensions load-bearing rather than decorative: while the interface still declaredpolicy = null, an applicable interface overload existed for every short call and instance members always beat extension members, socache.GetAsync<T>(key, token)kept binding to the interface and the extension was never reached. Withpolicyrequired, no interface overload is applicable to the short forms and there is exactly one way to spell "no policy". Implementations (MultilayerCache,RedisCache, their hash counterparts,NullCache,NullHashCache,MultilayerSetCache,RedisSetCache,NullSetCache) drop the defaults too, so behavior is identical whether the call goes through the interface or the concrete type. The typedICache<T>/IHashCache<T>/ISetCache<T>façades are unchanged — they never had apolicyparameter, since they resolve one at construction. -
BREAKING:
CacheKey.EqualsandGetHashCodeare now ordinal rather thanInvariantCultureIgnoreCase. Insensitive keys are still lowercased at construction, so the stored key and every comparison between insensitive keys are unchanged; what changes is that equality is now consistent withGetHashCode(the previous pairing could report two keys equal while hashing them into different buckets) and that keys built withCacheKeyCasing.Sensitivecompare case-sensitively. -
Dependency floors. What a consumer's restore has to satisfy, taken from
Directory.Packages.propsrather than from memory — an earlier draft of this entry said 10.0.11 and left StackExchange.Redis out:Package 1.3.0 2.0.0 StackExchange.Redis3.1.13 3.1.31 Microsoft.Extensions.*(net10.0group)10.0.10 10.0.12 Microsoft.Extensions.Logging.Abstractions(both TFMs)10.0.11 10.0.12 The
net8.0group is unchanged at 8.0.x.UiPath.Caching.OpenTelemetryreferences no OpenTelemetry package, so the 1.18.0 family this repository's samples moved to is a pin of the samples, not a floor on consumers;OpenTelemetry.Instrumentation.StackExchangeRedisonly needs to be a version without an upper bound on StackExchange.Redis 3.x. -
BREAKING (source, not data): every cache now serializes through
ISerializerProxy<byte[]>.RedisCache,RedisHashCache,RedisSetCache, the memory set tier and all four providers takeISerializerProxy<byte[]>in place ofISerializerProxy<RedisValue>, and the broadcast change token is built asChangeTokenFactory<byte[]>. No stored entry changes format and nothing needs migrating — the default serializer emits exactly whatSystemJsonSerializerProxyemitted. Consumers who pass these constructors a serializer directly, or who register a custom one, need a one-line type change;AddCachingnow throws at startup if a leftoverISerializerProxy<RedisValue>registration is present, rather than ignoring it and silently falling back to JSON. The check runs whether or notCacheOptions.Enabledis set, so a disabled test profile reports the same leftover the production profile would. -
Multi-key commands are checked against the Redis Cluster slot map before they run.
GetAsync(CacheKey[]),GetCacheEntriesAsync, the multi-keySetAsyncandRemoveAsync(CacheKey[])each reach Redis as one command on one node, so a batch whose keys span slots is answered with an error, which the caches log and report as a miss: migrating an app onto a cluster turned a working batch read into a cache that never hits, with nothing thrown to say so. Each of those paths now compares the slots first and throwsCrossSlotKeysException, naming the two keys that disagree and how to fix it. A non-clustered server maps every key to the same slot, so nothing changes off a cluster, and a disconnected cache skips the check and keeps answering from its own disconnected branch. -
ShardKeyEnabledleaves a key that already carries a hash tag alone. The shard strategy used to wrap every key in braces, so a caller who had placed its own{tag}in the key ended up withapp:s:{authz_{orgid}_groups_1}— Redis hashes from the first{to the next}, so the tag was the accidentalauthz_{orgidrather than the org the caller asked for. A key with a valid hash tag (non-empty content between the first{and the next}) is now prefixed and left as-is, so the caller's tag picks the slot and multi-key commands land where the caller intended, given a brace-free prefix. Non-empty keys with no braces are wrapped exactly as before; keys whose braces form no valid tag were wrapped by this change too, and are refused outright by A cache key that cannot carry a hash tag is refused rather than wrapped later in this release. This relocates existing entries only for apps that runShardKeyEnabled: trueand put braces in their keys.
CacheOptions.ShardKeyEnabled. It wraps a brace-free cache key in a{...}hash tag so the slot follows the key rather thanAppShortNameand the differentiator. That changes which keys share a slot, not how evenly they spread: the tag becomes the whole key, unique per key just as the untagged key was, so it spreads no better, and it cannot make a multi-key batch land on one node. A key that already carries a valid{tag}is rendered identically on either setting, so the flag makes no difference to batching in either direction; a key whose braces form no valid tag is refused outright when it is set. What it does do is co-locate one key across every cache that renders throughDefaultRedisKeyStrategyFactory, and across apps with a differentAppShortName— neither of which anyone asked for. What does matter on a cluster is unconditional: a caller's own tag survives, and a cross-slot batch is refused with a message naming the two keys that disagree. The property is still read, because a deployment that set it would relocate every brace-free key if it stopped being honored; to batch across keys on a cluster, give the keys a shared hash tag yourself. All of this assumesAppShortName,Separatorand the differentiator are brace-free, since braces there change which span Redis hashes.
- BREAKING:
SystemJsonSerializerProxyand theISerializerProxy<RedisValue>registration.SystemJsonByteSerializerProxy(inUiPath.Caching.Abstractions) is the single default and writes the same bytes. The genericISerializerProxy<T>interface itself is unchanged. - BREAKING:
IEventFormatterProxy<T>.Decode(string)andEncodeAsString(T), both obsolete since the broadcast path moved toReadOnlyMemory<byte>and both unused — nothing in the library called them and no implementation overrode the default bodies. UseDecode(ReadOnlyMemory<byte>)andEncode(T). - BREAKING:
CacheClock.DefaultDateTimeOffset(),CacheClock.ToTimeSpan(DateTimeOffset?)andCacheClock.ToTimeSpan(TimeSpan?). Nothing called them, and the firstToTimeSpanwas another place a configuredTimeSpan.MaxValueoverflowed.ToDateTimeOffsetis the conversion that remains, now as aTimeProviderextension. - BREAKING:
CacheClockitself.System.TimeProvideris the clock; nothing wrappedMicrosoft.Extensions.Internal.ISystemClockany more, so the type had no job left. - BREAKING: the per-options
Clockproperties:ICacheOptions.Clockand its implementations onInMemoryCacheOptions,InMemoryRedisCacheOptionsandRedisCacheOptions, andRedisConnectionOptions.Clock. Time comes from the oneTimeProviderin DI — see Changed.MemoryCacheFactory,UiPathDistributedCache, the provider constructors,MultilayerCacheBase,RedisCacheBase,RedisProfilerandRedisStreamHealthMaintainertake anTimeProviderinstead of anISystemClock?or nothing. - BREAKING: the
[Obsolete]options properties. The rename aliasesPrimaryMaxExpiration,PrimaryMaxExpirationDisconnectedandUsePrimaryOnlyWhenDisconnectedonIMultilayerCacheOptions,InMemoryCacheOptionsandInMemoryRedisCacheOptions— useLocalMaxExpiration,LocalMaxExpirationDisconnectedandUseLocalOnlyWhenDisconnected, which they forwarded to — andRedisConnectionOptions.ThreadPoolSocketManager, a no-op since StackExchange.Redis 3.0. The binder skips a key it cannot place without a word, so aPrimaryMaxExpirationleft inappsettings.jsonwould not fail the build, startup or a log line — the L1 cap would simply be gone. The section-bound overloads (AddMemory(sectionName),AddInMemoryRedis(sectionName),AddRedisConnection(sectionName)and the(sectionName, configure)form) therefore throwInvalidOperationExceptionat registration when one of the four removed keys is present under the section, naming the section, every offending key and its replacement. The check runs whether or not the provider is enabled, since a disabled profile is usually the non-production copy of one that is on elsewhere. The code-only overloads are not checked: the property no longer exists to assign.
-
The streams maintainer no longer depends on its quarantine hash sharing a Redis Cluster slot with the stream. Two faults, one cause. The maintainer built its quarantine key by rendering a prefix through
IRedisKeyStrategy.GetRedisKeyand concatenating the stream key onto it, but that method renders a complete key: withShardKeyEnabledthe rendered prefix carried its own{...}, so every quarantine hash inherited one constant tag and all of them landed on a single slot. AndCheckEmptyStreamAsyncdeleted the stream and its quarantine hash in one multi-keyKeyDelete, which Redis Cluster answers withCROSSSLOTunless both keys hash to the same slot — so the empty-stream cleanup never completed on a cluster. The key is built in one call now, so it spreads with the stream key that names it, and the pair is deleted one command at a time. Co-locating them instead would not have been sound: the configuredIRedisKeyStrategyand any connection key prefix both shape the key that reaches Redis, and either can put the two on different slots whatever the library composes. A trailing terminator keepsCacheKey's trim — which runs even under sensitive casing — from collapsing two stream keys that differ only by surrounding whitespace. Quarantine entries written under the old key are orphaned. Most carry the TTL the maintainer attaches,MaintainerQuarantineInterval× 10, and expire on their own; one created after its stream's last expiry-attaching pass carries none — the transaction's emptyHashSetcreates no key for the adjacentKeyExpireto land on, and the per-groupHashSetthat does create the hash sets no expiry — and has to be deleted by hand. -
Multi-key
RemoveAsynchonors its cancellation token again. TheCacheKey[]overload built each entry's options without the token, so an already-cancelled call did the work anyway and only noticed at the removal itself. It now forwards the token, matching the single-key overload. The rest of this change is build-warning cleanup with no behavior change: the periodic-timer loops inCacheMemoryMonitorand the stream health maintainer, and the planned-maintenance probe task, now say explicitly that they opt out of token propagation, each with the reason — disposal is what stops the loops, and the probe delegate must always run so itsfinallyclears the in-progress flag. Test fakes moved off the obsoleteRedisServerException(string)constructor. -
Reserved Redis keyspaces are extensible across packages (#130).
AddDistributedCacheused to compareRedisKeyDifferentiatoragainst a hardcoded list of the core's Redis keyspaces, so a package layered on top —UiPath.Caching.Queue's set cache on"se"— was invisible to it and a differentiator landing on those keys was accepted. Packages now declare the keyspaces they occupy throughIServiceCollection.ReserveRedisKeyspace(IReservedRedisKeyspace); the core reserves its four andAddQueueRedis/AddQueueInMemoryRedisreserve"se", whether or not that backing is enabled.AddDistributedCachereserves its own differentiator the same way, so one registry answers every case: the second party to claim a keyspace is rejected whichever it is, in either order, across separateAddCachingcalls, and even whenCacheOptions.Enabledis false — a collision is a configuration error rather than a runtime condition. Two packages claiming one keyspace is rejected too, where before the later reservation was silently dropped; a repeat by the same owner is still ignored. A keyspace,RedisKeyDifferentiatorincluded, must be one segment of letters and digits, so none can span segments under a punctuation separator;CacheOptions.Separatormay itself be alphanumeric, so one keyspace nesting inside another under the configured separator is rejected when the options resolve. The resolution-time probe that guards a customIRedisKeyStrategyFactoryenumerates the same reservations, skipping any the factory refuses to build a key for, and the default differentiator is checked too in case a package reserves it. -
Stale endpoint detection works under the default
allowAdmin=false. The membership check issuedCLUSTER NODES, which StackExchange.Redis refuses client-side unless admin mode is on, so on a default connection every scan recorded aRedisCommandExceptionand never reconnected. The scan now refreshes the client's own cluster topology (IConnectionMultiplexer.ConfigureAsync, whoseCLUSTER NODESis an internal call) and reads theClusterConfigurationit records on the configured endpoints, judging only once the refresh has replaced it. When a refreshed node has none on three consecutive refreshes — a non-cluster server, or a Redis user that may not runCLUSTER NODES— the scan emits oneRedis.StaleEndpointScanDisabledevent and stops, instead of reporting the same failure every interval. A down node the topology still lists is re-checked only once per threshold and reported once throughRedis.StaleEndpointStillAMember; a refresh that keeps throwing backs off exponentially, up to an hour between attempts. -
RefreshAsyncon Redis reported nothing. Both Redis caches sent their standaloneKEYEXPIRE/PERSISTfire-and-forget, so the call returnedfalsewhether the refresh succeeded, failed or the key did not exist, the server's reply was never seen — a rejected command was neither logged nor retried by the resilience pipeline — and telemetry recorded every refresh as unsuccessful. SettingRedisCacheOptions.AwaitRefreshmakes the result meaningful; the default is unchanged, so existing callers see the previous behavior until they opt in. The fire-and-forget flags inside the write transactions are untouched: those replies are discarded, but the transaction itself is awaited. -
AddCaching(IConfigurationSection)never boundCacheOptions. The overload passed its options binder positionally, so it landed on theconfigureparameter and type-checked asAction<ICachingBuilder>— leavingconfigureOptionsnull, the section unread, and the config bound onto the builder object instead. EveryCacheOptionsvalue supplied through that entry point was silently ignored;Enabled,AppShortName,KeyCasingand the rest now take effect, which changes behavior for anyone who was unknowingly running on the defaults.
- New recipe
conditional-add.md— claiming a key exactly once withTryAddAsync, why check-then-set is not equivalent, and when to reach forIDistributedLockinstead.interfaces.mddocuments the member on both cache surfaces with a per-provider table of who arbitrates and how far exclusion reaches;concepts.mdplaces it next to the two lock abstractions, whose goal is reducing redundant work rather than a decision the caller can branch on. The recipe's worked example is a daily digest rather than a payment capture, and says why: a claim marker records that someone started, never that anyone finished, so an operation that must eventually happen needs a recorded outcome instead. Both documents also state plainly that the ambiguity infalseis not recoverable — a serialization or command failure returnsfalsewith the connection snapshot still healthy — rather than pointing atIConnectionStateas an escape hatch, and both explain why theNXwrite is safe to retry whereSPOPis not. - New
IConnectionStatesection ininterfaces.md, a public type that was documented nowhere (and that theTryAddAsyncguidance linked to through an anchor resolving toIDistributedLock). It is described as what it is — a cache-health snapshot for probes, metrics and backoff — not as a way to explain a negative result. - Corrected
interfaces.md, which described theIHashCache<T>.SetAsync(…, HashCacheEntryOptions, …)overload as offering "conditional set, individual field TTL".HashCacheEntryOptionscarries neither:HashCacheSetOptionselects write scope (HashReplacemerges fields,KeyReplacedrops the key first), and there is no per-field TTL.
- Batch
GetOrAddAsyncwith caller state.ICache,ICache<T>andCache<T>gained multi-keyGetOrAddAsyncoverloads that pair each key with an opaque caller state (TState) — a database id, a request object, whatever identifies the entry in the caller's own vocabulary. The generator is invoked at most once on the calling path, receiving only the states of the entries that missed every cache layer, never the keys; results come back keyed by state, one entry per distinct requested state, in first-occurrence order. Cache operations de-duplicate byCacheKey(one probe, one write per distinct key); results de-duplicate by state — when two states share a key the generator is asked once, about the first state seen for that key, and the value is reported under both. A state the generator omits is returned asdefault(T)and left uncached, so the next call retries the source. A caller whose keys are their own identity pairs each key with itself (TState = CacheKey); the blockingGetOrAddfacade onICache<T>acceptsCacheKey[]directly and does that pairing for you. OnMultilayerCachethe generator call is guarded by a single composite lock derived from the missing key set, and proactive rehydration of hit keys is coalesced into one background call that locks per key, so overlapping aging sets on different nodes refresh each shared key once. Added toICacheas default interface methods, so existingICacheimplementations keep compiling; theICache<T>overloads are abstract — see the breaking note under Changed. InMemoryRedisCacheOptions.BroadcastEnable(defaulttrue) turns cross-node L1 invalidation off for theInMemoryRedisprovider alone, so L1+L2 tiering can be used without broadcast traffic. Intended for single-node deployments, where cross-node invalidation buys nothing, and for Redis-compatible backends whose Streams support does not coverXREADGROUP. Whenfalsethe provider getsNullTopicFactory/NullChangeTokenFactory/NullCacheEventFactory, mirroring whatInMemoryCacheProvideralready did forInMemoryCacheOptions.BroadcastEnable. The flag can only narrowCacheOptions.BroadcastEnabled, never widen it; note its default is the opposite of theInMemoryequivalent, which is opt-in. (#103)
- BREAKING:
ICache<T>gains three abstract multi-keyGetOrAddAsyncmembers. They could not ship as default interface methods:ICache<T>has noGetCacheEntriesAsync, so a default body could not tell a miss from a cached null. This is source- and binary-breaking for any hand-writtenICache<T>implementation (test fakes, typically) — source-breaking because such a type no longer compiles until the members are added, and binary-breaking because an already-compiled assembly implementingICache<T>throwsTypeLoadExceptionwhen loaded against the newUiPath.Caching.Abstractions, with no recompile involved. Consumers that pick the new abstractions up transitively must rebuild, not just restore. TheICacheoverloads are default interface methods, soICacheimplementations are unaffected.
- The Redis Streams fetch loop no longer hammers a server that does not implement
XREADGROUP. It previously re-issued the command and loggedFetch events loop erroronce perPollInterval(250 ms by default) forever. The unsupported-command case is now reported once atCriticalwith the available remedies, then retried every 30 s; a successful fetch lifts the quarantine and logs recovery, and a connection-restored/reconnected event wakes the loop early so recovery does not wait out the backoff. Recovery does not depend on those events: with the connection monitor off (the default) the timed retry still gets there. Other consecutive fetch failures now back off exponentially fromPollIntervalup to 30 s instead of retrying at the poll rate. (#103) CacheOptions.BroadcastEnablednow actually disables broadcast. It was read only byRedisStreamHealthMaintainer, so setting it through theAddCachingoptions lambda stopped the maintainer while the Streams fetch loop kept running, despite sharing a name with the configuration key that does perform the real opt-out.TopicFactorynow resolves every topic toNullTopicProviderand reports no provider names when the flag isfalse. (#103)
concepts.mdnow states thatAddInMemoryRedis()wires broadcast internally and that a code-onlyAddBroadcast(enabled: false)does not stick, and links to the broadcast how-to. The how-to gains a section on disabling broadcast forInMemoryRedisalone and a troubleshooting entry forERR unknown commandagainst Redis-compatible backends. (#103)
- Set caches in the
UiPath.Caching.Queuepackage gainedInMemoryandInMemoryRedisbackings alongside Redis, via a provider model that mirrors the core cache. New per-backing registrationsAddQueueMemory/AddQueueRedis/AddQueueInMemoryRedisonICachingBuilder(each with a config-section overload binding the sameKnownCacheProviderNamessections the core providers use); a newIQueueCacheProvider(one per backing —InMemoryQueueCacheProvider/RedisQueueCacheProvider/InMemoryRedisQueueCacheProvider); andQueueCacheFactorynow selects a provider by name viaCacheOptions.DefaultCache(or an explicit name, falling back to the default thenNullSetCache), and isIDisposablewithAddProvider— exactly likeICacheFactory. TheInMemoryRedisbacking is a multilayer set cache: a local in-process snapshot (L1) over the Redis set cache (L2), with the same connection-monitor / local-only-when-disconnected behavior as the coreInMemoryRediscache. New optionsInMemoryQueueCacheOptions/InMemoryRedisQueueCacheOptions(shared by all collection kinds of a backing, likeInMemoryCacheOptions) andRedisSetCacheOptions.Enabled.
- Bumped the OpenTelemetry package family from 1.16.0 to 1.17.0 (
OpenTelemetry,OpenTelemetry.Exporter.OpenTelemetryProtocol,OpenTelemetry.Exporter.Console,OpenTelemetry.Extensions.Hosting,OpenTelemetry.Instrumentation.AspNetCore,OpenTelemetry.Instrumentation.Http,OpenTelemetry.Instrumentation.Runtime, andOpenTelemetry.Instrumentation.StackExchangeRedis1.16.0-beta.1 → 1.17.0-beta.1). Bumped as one set so the family stays version-consistent. - BREAKING:
SetCacheCollectionExtensionsand itsAddRedisSetCacheoverloads (bothIServiceCollectionandICachingBuilder) are removed. Register the Redis set cache viaAddCaching(... builder.AddQueueRedis())(sameRedisSetCacheOptions, same behavior). Registration now always goes through theICachingBuilder, which guarantees the core caching services are present and honors the builder'sEnabledflag. (AddRedisSetCacheshipped only in 1.1.0.) - BREAKING: the parameterless
IQueueCacheFactory.CreateSetCache()/QueueCacheFactory.CreateSetCache()members and the parameterlessCreateSetCache<T>(this IQueueCacheFactory)extension are removed in favor of a singleCreateSetCache(string? providerName = null), exactly likeICacheFactory.CreateCache. Source-compatible (factory.CreateSetCache()still compiles and means "default provider"), but binary-breaking — recompile against the new package. (Shipped only in 1.1.0.) - BREAKING: the
QueueCacheFactory(ISetCache)constructor is removed — the factory is provider-based only, likeCacheFactory. To pin a fixedISetCache(e.g. in tests), register it through a stubIQueueCacheProviderand pointCacheOptions.DefaultCacheat its name. (Shipped only in 1.1.0.)
RedisCollectionExtensions.AddRedisConfigurationOptionsProvider(this ICachingBuilder, Func<IServiceProvider, IRedisConfigurationOptionsProvider>)— registers a customIRedisConfigurationOptionsProvidervia a factory delegate, replacing the defaultRedisConfigurationOptionsProvider. Order-independent (usesReplace), so it can be called before or afterAddRedisConnectionand the supplied factory always wins. Previously a custom provider required manually pre-registering it so theTryAdddefault backed off.
- Bumped
StackExchange.Redisfrom 2.10.1 to 2.13.17 (latest 2.x), the first step of the staged upgrade toward 3.0. No public API or runtime behavior change. - Bumped
Microsoft.Extensions.Logging.Abstractionsonnet8.0from 8.0.3 to 10.0.10 (matching thenet10.0pin). Prerequisite forStackExchange.Redis3.0, which requires>= 10.0.5;net8.0consumers now transitively resolve the 10.x abstractions package (compatible — it targets net8.0). - Bumped
StackExchange.Redisfrom 2.13.17 to 3.0.17. 3.0 is an internal IO-core rewrite that mirrors 2.13.17's public API, so there is no public API change here. The live hang-detection and profiling reflection paths were verified against a real Redis on both target frameworks. - Obsolete:
RedisConnectionOptions.ThreadPoolSocketManagerno longer has any effect and is marked[Obsolete]. StackExchange.Redis 3.0 removedSocketManager(its IO core no longer uses one), so the setting is now a no-op; it will be removed in a future major release.
- Serialization now stays on UTF-8 bytes end-to-end instead of round-tripping through UTF-16
strings. JSON is UTF-8 on the wire, so the string hop was a pure allocation + transcode on every read/write. Measured with BenchmarkDotNet (SerializerBenchmark), this roughly halves allocations on the serialize/deserialize paths (e.g. large-payload deserialize1,385,629 B → 607,714 B, serialize778,689 B → 389,660 B) with equal-or-better throughput. No public API changes.SystemJsonSerializerProxy(the default proxy shared byRedisCache,RedisHashCache,RedisSetCache,RedisCacheProvider) serializes viaJsonSerializer.SerializeToUtf8Bytesand deserializes from theRedisValuepayload asReadOnlySpan<byte>. The benchmark also measured aReadOnlySequence<byte>/Utf8JsonReadervariant; it allocated identically to the span path but was slower for these (single-segment) payloads, so the span path was chosen.CacheEventFormatter.EncodeusesSerializeToUtf8Bytes(dropping the intermediate string +Encoding.UTF8.GetBytes); the Redis broadcast publish paths (RedisPubSubTopic,RedisStreamsTopic) publish the encoded bytes as aRedisValuedirectly instead of viaEncodeAsString; and the subscribe paths (RedisPubSubSubjectWriter,RedisStreamSubjectWriter) decode from theRedisValuebytes instead ofvalue.ToString().- Wire format is unchanged everywhere — values written by the previous string paths still deserialize.
IEventFormatterProxy<T>.Decode(string)andIEventFormatterProxy<T>.EncodeAsString(T)are marked[Obsolete]. They forced a UTF-16 transcode and are no longer used by the library; use the byte-basedDecode(ReadOnlyMemory<byte>)/Encode(T)instead.
- Repository extracted from
UiPath/ServiceCommonto the publicUiPath/dotnet-cachingrepository under the MIT license. PackageIds are renamedUiPath.Platform.Caching.*→UiPath.Caching.*at the first nuget.org release. - BREAKING:
IConnectionMultiplexerFactoryis now async-only — the synchronousCreate(ConfigurationOptions)member is removed andCreateAsync(ConfigurationOptions, CancellationToken)is the sole member. Custom factory implementors must implementCreateAsync.RedisConnectornow caches the connection asLazy<Task<IConnectionMultiplexer>>(one shared creation for async warm-up and sync first-use, with faulted-task self-heal),IsConnected/GetEndPointsare non-blocking snapshots (never block or throw), andRedisPlannedMaintenanceis anIHostedServicethat connects/subscribes off the startup critical path with bounded retry + warning logging and deterministic shutdown.
-
UiPath.Caching.Azurepackage +ICachingBuilder.AddAzureEntraAuthentication(...)— Microsoft Entra ID authentication for Azure Managed Redis. The core stays Azure-free via a new async extension pointIRedisConnectionConfigurator(inUiPath.Caching), applied to theConfigurationOptionsonce per connect (beforeIConnectionMultiplexerFactory); the Azure package implements it throughMicrosoft.Azure.StackExchangeRedis, which owns automatic token refresh. External apps implementIRedisConnectionConfiguratorfor other schemes (AWS IAM, custom tokens) with no core change. With no configurator registered, behavior is unchanged.IRedisConnectorgains aConnectAsyncwarm-up as a default-interface method (existing implementors unaffected). Entra connections default to TLS (AzureEntraOptions.RequireSsl) and RESP3 (AzureEntraOptions.RequireResp3) so pub/sub survives token rotation. Credential selection: an explicitCredential, elseManagedIdentityCredentialfromManagedIdentityOptionswhen set (itsManagedIdentityId— set onManagedIdentityCredentialOptionsat construction — chooses the identity, defaulting to system-assigned; sovereign-cloudAuthorityHostsupported here), else a user-assignedManagedIdentityCredentialfrom a non-emptyManagedIdentityClientId, elseDefaultAzureCredential.ManagedIdentityOptionstakes precedence overManagedIdentityClientId; to combine a user-assigned identity with custom options, constructManagedIdentityOptionswithManagedIdentityId.FromUserAssignedClientId(clientId). -
RedisConnectionOptions.WarmUpOnStart(defaultfalse) — opt-in hosted-service warm-up that establishes the Redis connection at host startup (running any registeredIRedisConnectionConfigurators); best-effort, never blocks or fails startup. Leftfalse, the connection is established lazily on first cache use.RedisConnectionOptions.PlannedMaintenanceConnectionRetryCount(default5) /PlannedMaintenanceConnectionRetryDelay(default5s, negative/zero clamped to1s) tune the planned-maintenance subscription's background retry. -
The hit/miss metric (
Caching.Stats.Hits/Misses) is now emitted once per read operation with aKeysdimension carrying the number of keys in the operation (a batch's outcome is hit when any key hit). A multi-keyMGETno longer fans out into one elapsed-time sample per key, which would skew the metric's latency distribution by batch size. Every hit/miss metric carries theKeysdimension (1for single-key and non-read operations such as writes/deletes/TTL, the batch size for multi-key reads and bulk set/remove) so the dimension is consistent across the metric name and group-by-Keysqueries don't bucket operations into a null dimension. -
RedisCacheOptions.KeyReadTelemetryEnabled(defaultfalse) — opt-in per-key read attribution forRedisCacheandRedisHashCache. When enabled, the read paths additionally emit a dependency per key withtype = "Redis", the Redis key indata, hit/miss carried byresultCode(Hit/Miss) plus anOutcomeproperty,Provider/Method/Typeproperties, and aBatchIdshared by all keys of one operation so the keys read together can be correlated (summarize by BatchId— aGuidminted per operation, since neither Redis nor StackExchange.Redis exposes a transaction id). The dependency'ssuccessis alwaystrue(a cache miss is not a failure, andtype = "Redis"is shared with the profiler's dependency telemetry, so misses must not skew dependency-failure dashboards). ForRedisHashCacheit is one dependency per hash key (not per field) — an HGETALL on a hash with thousands of fields must not fan out into thousands of telemetry items — sodatais the hash key and the field set is not enumerated. It lands in the samedependenciestable the Redis profiler uses, so existing key-level KQL keeps working — restoring the "which keys are being read" attribution the profiler can no longer provide once batched reads are bundled into a singleMULTI/EXECtransaction (the keys are no longer visible on the wire). It is opt-in because raw keys are high-cardinality. Surfaced through two newITelemetryOperationmembers —Track(bool hit, int keyCount)(per-operation hit/miss metric with key count) andTrackKeyReads((string Key, bool Hit)[] reads)(opt-in per-key dependencies sharing aBatchId) — implemented byTelemetryOperationand no-op'd byNullTelemetryOperation. The per-key dependency's start time is captured at operation start (not at emit time). -
IQueueCacheFactory/QueueCacheFactory(+QueueCacheFactoryExtensions.CreateSetCache<T>()) inUiPath.Platform.Caching.Queue— a dedicated set-cache factory that lets you create a typed set the same ergonomic way you create a cache:queueCacheFactory.CreateSetCache<T>(). It mirrorsCacheFactory.CreateCache/CacheFactoryExtensions.CreateCache<T>for Redis sets. It is a separate factory (not a method onICacheFactory) because the entire set implementation lives in the optionalCaching.Queuepackage, which is downstream ofICacheFactoryinCaching.Abstractions— soICacheFactorycannot referenceISetCache.QueueCacheFactoryhands out the singletonISetCacheregistered byAddRedisSetCache(sets have a single Redis backing);CreateSetCache<T>()wraps it inSetCache<T>with no policy factory, exactly likeCreateCache<T>(the underlyingRedisSetCachestill applies the global default policy). Registered automatically byAddRedisSetCache; injectIQueueCacheFactorywhere you need sets. -
NullQueueCacheFactory(inUiPath.Caching) — a no-opIQueueCacheFactorywhoseCreateSetCache()returns the singletonNullSetCache.Instance.AddRedisSetCachenow registersNullSetCache,NullQueueCacheFactory, andSetCache<>when caching is disabled (ICachingBuilder.Enabled == false), mirroring how the core cache degrades to no-ops. Previously the disabled branch registered nothing, so any service depending onISetCache/IQueueCacheFactoryfailed to resolve (andValidateOnBuildthrew) when caching was turned off; dependents now construct against the null set cache instead. -
IResiliencePipelineProvider— a name-based factory (IResiliencePipeline Get(string? name)) that replacesIResiliencePipelineHolder. It builds and caches aResiliencePipelineWrapperfor any registered name on first use, and returns a noopEmptyResiliencePipelinefor a null/empty/unregistered name, so every component resolves the pipeline it needs through DI instead of receiving a fixed holder. The default registration isEmptyResiliencePipelineProvider.Instance(all-noop);AddResilienceStrategiesregisters the realResiliencePipelineProvider. BREAKING:IResiliencePipelineHolder/ResiliencePipelineHolderare removed in favor ofIResiliencePipelineProvider; the cache and topic components now take anIResiliencePipelineProviderconstructor parameter. Consumers using the shipped DI wiring are unaffected; direct callers must pass the provider (useEmptyResiliencePipelineProvider.Instanceto opt out of resilience). -
CachingBuilderExtensions.AddResiliencePipeline(name, Action<ResiliencePoliciesOptions>)— registers a named resilience pipeline, wherenameis the scope passed toIResiliencePipelineProvider.Get(name). Each name gets its ownResiliencePoliciesOptions(resolved viaIOptionsMonitornamed options), so different scopes can carry different retry/timeout/circuit-breaker settings.AddResilienceStrategiespredefinesResiliencePipelineNames.ReadandWritefrom the base configuration; consumers can add new pipelines or retune the built-ins. Only registered names resolve to a real pipeline. TheResiliencePipelineFactoryconstructor now takesIOptionsMonitor<ResiliencePoliciesOptions>instead ofIOptions<ResiliencePoliciesOptions>so it can resolve per-scope options;Create<TResult>selects the options for its scope viaoptionsMonitor.Get(scope). -
RedisSetCacheOptions.ResilienceKeyName— the name of the resilience pipeline used for the destructive-readSPOPoperations behindRedisSetCache.PopAsync(both overloads). The pipeline is resolved generically viaIResiliencePipelineProvider.Get(ResilienceKeyName), so a consumer who needs special handling for non-idempotent commands (e.g. a no-retry pipeline — a retry after a lost response would re-runSPOPserver-side and silently drop members the first attempt already popped) registers their own scope and pointsResilienceKeyNameat it. WhenResilienceKeyNameis null/empty (the default), pops run with no resilience pipeline (EmptyResiliencePipeline), i.e. at-most-once with no retry. Wire it viaAddRedisSetCache(opt => opt.ResilienceKeyName = "..."). The idempotent read/write operations continue to use theRead/Writepipelines. -
ICachingTelemetryProvideris now span-based:TrackDependency,TrackEvent,TrackException, andTrackMetrictakeReadOnlySpan<KeyValuePair<string, string>>/ReadOnlySpan<KeyValuePair<string, double>>instead ofIDictionary.NullTelemetryProvideris span-aware as a true no-op (zero allocation when telemetry is disabled).CachingTelemetryProvider(the adapter toUiPath.Platform.Telemetry.ITelemetryProvider) materializes the span once at the boundary viaTelemetryTags.ToDictionaryOrNullto forward to the dict-based upstream. All hot-path call sites inCaching.Runtimemigrated to span — cold-missRedisDistributedLockevents, Redis connection/maintenance events, memory-cache setter failure events, and stream subject writer events no longer allocate a tag dictionary at the call site. -
ICache.GetCacheEntryAsync<T>andICache.GetCacheEntriesAsync<T>— bundled GET + TTL reads. Implementations may fetch the value and its remote expiration in a single network round-trip;RedisCacheuses aMULTI/EXECtransaction (mirroring the hash-cache pattern). -
RedisStreamsTopicsupports an optional Pub/Sub notify doorbell (NotifyEnabled) that drops publish-to-deliver latency from the poll interval to network RTT, while preserving stream durability and consumer-group semantics. Channel name defaults to the stream's Redis key joined withNotifyChannelName(default"notify") using the sameCacheOptions.Separatoras the rest of the key scheme. SetNotifyShardedPubSub = trueto use sharded Pub/Sub (SPUBLISH/SSUBSCRIBE, requires Redis 7.0+) so the doorbell does not fan out across cluster nodes; the sharded strategy wraps the stream key as a Redis Cluster hash tag (or inherits an existing one) so the channel and stream share the same slot —XADDandSPUBLISHgo to the same node. Otherwise regularPUBLISH/SUBSCRIBEis used. Override the channel entirely viaNotifyChannelStrategy. Pub/Sub is best-effort — the existing poll continues to run as a safety net. -
Single-flight locking on
MultilayerCache.GetOrAddAsync/MultilayerHashCache.GetOrAddAsyncvia two new abstractions:ILocalLock(in-process serialization per cache key, default implAsyncKeyedLocalLockbacked byAsyncKeyedLock) andIDistributedLock(cross-process coordination, default implRedisDistributedLockusingLockTakeAsync/LockReleaseAsyncwith aSourceUri-prefixed token). Both are layered behind double-checked reads so a single generator runs per key on cache miss; lock-take failures fall back to a no-op disposable so a Redis outage degrades to thundering-herd behavior rather than stalling. New options onIMultilayerCacheOptions:LocalLockEnabled,DistributedLockEnabled,DistributedLockTimeout(default 500 ms),DistributedLockExpiry(default 5 s),LockKeyStrategy(default appends:lck). New options onCacheOptions:LocalLockPoolSize(default 100),LocalLockPoolInitialFill(default 10). Wire viaAddLocalLock()/AddRedisDistributedLock()onICachingBuilder;AddMemoryandAddInMemoryRedisregister them automatically.CachingBuilder.CompleteregistersNullLocalLock/NullDistributedLockas singletons viaTryAddSingleton, so providers that do not register a lock get a safe no-op. Direct (non-DI) callers can also passNullLocalLock.Instance/NullDistributedLock.Instance(bothpublic) to opt out of locking.
- BREAKING:
ITelemetryOperationgains two members —Track(bool hit, int keyCount)(per-operation hit/miss metric carrying the key count) andTrackKeyReads((string Key, bool Hit)[] reads)(opt-in per-key dependencies). External implementers ofITelemetryOperationmust add them; the shipped implementations (TelemetryOperation,NullTelemetryOperation) already do.TrackKeyReadsis invoked only whenRedisCacheOptions.KeyReadTelemetryEnabledis enabled; the keylessTrack(bool)path is unchanged for existing consumers. MultilayerCacheandMultilayerHashCacheno longer issue a separateExpireTimeAsynccall after a cache-miss read. They now use the bundledICacheEntry.Expirationreturned by the inner cache. For Redis-backed multilayer caches this collapses N + 1 sequential commands to one transaction (one round-trip, oneEXECdependency in telemetry) when fetching N keys, eliminating per-keyPTTL/EXPIRETIMEtraffic on the read path. Public APIs are unchanged.- BREAKING:
ICachingBuilder.RegisterOnCompleteCallback(Action<ICachingBuilder>)is replaced byRegisterOnCompleteCallback(object key, Action<ICachingBuilder>).CachingBuilderkeeps a per-builder set of seen keys and ignores re-registrations against an already-seen key on the same instance. Callers should pass a deterministic key (typicallytypeof(YourExtensionsClass)). - BREAKING:
Caching.Polly.CachingBuilderExtensions.ConfigureTelemetry(this ICachingBuilder, bool, Action<TelemetryOptions>?)is removed. Telemetry is now configured exclusively throughAddResilienceStrategies(..., configureTelemetryOptions: ...)andResiliencePoliciesOptions.TelemetryEnabled, which flow throughIOptions<TelemetryOptions>/IOptions<ResiliencePoliciesOptions>per-container instead of process-static fields. - BREAKING:
MultilayerCacheandMultilayerHashCacheconstructors take two new required parameters —ILocalLock localLockandIDistributedLock distributedLock— inserted beforeILogger logger(now the last parameter). Apps using the built-in DI extensions (AddMemory,AddInMemoryRedis) are wired automatically through the newAddLocalLock()/AddRedisDistributedLock()registrations. Callers that instantiate these caches directly must pass both arguments; use the now-publicNullLocalLock.Instance/NullDistributedLock.Instanceto opt out (or resolveILocalLock/IDistributedLockfrom DI). No overload was added on purpose so the breakage is loud rather than silent. - BREAKING:
InMemoryCacheProviderandInMemoryRedisCacheProviderconstructors take new required parameters for the lock services —ILocalLockon the former,ILocalLock+IDistributedLockon the latter. Same rationale as the multi-layer cache ctors: DI users are unaffected (CachingBuilder.CompleteTryAddSingleton-registersNullLocalLock/NullDistributedLock), but direct callers must now pass them explicitly. The previous optional / nullable parameter shape was rejected because it preserves source compatibility while still binary-breaking, which is the worst combination — silent for source readers, loud for production consumers. - BREAKING:
IMultilayerCacheOptionsgains five lock-related members —LocalLockEnabled,DistributedLockEnabled,DistributedLockTimeout,DistributedLockExpiry,LockKeyStrategy. External types that implement this interface (rather than deriving fromInMemoryRedisCacheOptions/InMemoryCacheOptions) must add the new properties; default interface implementations were avoided so missing storage cannot silently drop user-set values. - BREAKING:
ICachingTelemetryProvider'sTrackDependency/TrackEvent/TrackException/TrackMetricmembers no longer takeIDictionary<string, string>?/IDictionary<string, double>?— they now takeReadOnlySpan<KeyValuePair<string, string>>/ReadOnlySpan<KeyValuePair<string, double>>. The dict-based members are removed from the interface entirely. The members carry empty default interface bodies (no-op) so that proxy-based mocking frameworks (NSubstitute / Castle.DynamicProxy) can build proxies for the interface — those frameworks cannot generate valid IL for abstract methods with ref-struct parameters. External implementers must override the span methods to do real work; relying on a previous dict-based implementation will silently drop telemetry because the dict members are no longer part of the interface contract. Migration: implement the four span methods directly; for callers building tag bags dynamically, useList<KeyValuePair<string, string>>plusCollectionsMarshal.AsSpan(list), or convert an existing dictionary viadict.ToArray().
RedisCache.GetCacheEntryAsync/GetCacheEntriesAsyncandRedisHashCache.GetCacheEntryAsyncnow passCommandFlags.PreferReplicatotransaction.ExecuteAsync(...), so the bundled GET + TTL transaction actually routes to a replica. SE.Redis ignores the flag set on inner queued commands when picking a server for the transaction; without an explicit flag onExecuteAsyncthe read landed on the master. These read paths now also use the_readresilience pipeline instead of_write.- Bulk write transactions in
RedisCache.SetAsync(KeyValuePair<>[])andRedisHashCacheSet/Refresh paths now passCommandFlags.DemandMastertotransaction.ExecuteAsync(...)for symmetry with the read fix and to make the master-only routing intent explicit (inner-command flags do not propagate to transaction routing in SE.Redis). AddInMemoryRedisandAddResilienceStrategiesno longer use a process-static_callbackRegisteredflag to gate their on-complete callback. The static guard silently broke L1 invalidation / resilience pipelines for any second host wired up in the same process: only the first builder's callback ever ran, leaving subsequent builders withNullChangeTokenFactoryandEmptyResiliencePipelineProvider.Instance. Both extensions now register their callbacks against a deterministic per-extension key (e.g.,typeof(InMemoryRedisCollectionExtensions)/typeof(CachingBuilderExtensions)) via the keyedRegisterOnCompleteCallbackoverload.AddResilienceStrategiesno longer stores telemetry enable/config in process-static fields.IResiliencePipelineFactorynow resolvesIOptions<TelemetryOptions>andIOptions<ResiliencePoliciesOptions>from its own container, so two hosts in the same process keep independent telemetry settings. Previously the secondAddResilienceStrategiescall would silently overwrite the first host's telemetry configuration (the factory singleton read the statics at resolution time, not at registration time).
- Restructured
docs/into a layered surface:quickstart.md,concepts.md,how-to/,recipes/,reference/.docs/basics.md,docs/advanced-usage.md, anddocs/telemetry.mdare removed; their content is migrated. Seedocs/index.mdfor the decision tree. Sample.AspNetCore/appsettings.all.jsonnow lists every binding-visible option on every shipped options class with shipped defaults. Verified byCaching.Tests/AppSettingsAllJsonBindingTests.cs.