UiPath Caching
Multilayer caching for .NET — L1 in-memory + L2 Redis, cross-node sync over Redis Streams, single-flight stampede protection, hydrating cache, and CloudEvents — behind a small, opinionated DI surface.

The library powers caching in UiPath Platform services. It is built for multi-tenant workloads that need a hot in-process tier, a shared Redis tier, and cross-node coherence — without each service reinventing the same patterns.
Quick Start
dotnet add package UiPath.Caching
dotnet add package UiPath.Caching.Polly
dotnet add package UiPath.Caching.CloudEvents
Wire it once in Program.cs:
using UiPath.Caching;
using UiPath.Caching.CloudEvents;
using UiPath.Caching.Config;
using UiPath.Caching.Polly;
var section = builder.Configuration.GetSection("Caching");
builder.Services.AddCaching(
section,
b => b.AddRedisConnection().AddBroadcast()
.AddRedis().AddInMemoryRedis().AddMemory()
.AddResilienceStrategies().AddCloudEvents(),
o => { section.Bind(o); o.AppShortName = "my-service"; });
Inject and call:
public class UserService(ICache<User> cache, IUserRepository repo)
{
public ValueTask<User?> GetAsync(int id, CancellationToken ct) =>
cache.GetOrAddAsync(id.ToString(), c => repo.LoadAsync(id, c),
TimeSpan.FromMinutes(5), ct);
}
That lambda is the default shape. The GetOrAddAsync overloads that take an interpolated key or a static lambda with its state exist for hot paths; what each one costs, and when it pays, is in docs/how-to/choosing-a-get-or-add-overload.md.
Minimum appsettings.json:
{
"Caching": {
"AppShortName": "my-service",
"Connections": {
"Redis": { "ConnectionString": "localhost:6379" }
}
}
}
That's it. Everything else has a sensible default. Five-minute onboarding lives in docs/quickstart.md; the full settings reference is in docs/reference/settings.md.
Optional add-ons
Two packages plug into the same builder callback — Entra ID authentication for Azure Managed Redis, and set ("queue") caches:
dotnet add package UiPath.Caching.Azure
dotnet add package UiPath.Caching.Queue
using UiPath.Caching.Queue.Config; // on top of the usings above; Entra auth needs no extra namespace
builder.Services.AddCaching(
section,
b => b.AddRedisConnection().AddAzureEntraAuthentication() // passwordless Redis, tokens auto-refreshed
.AddBroadcast().AddRedis().AddInMemoryRedis().AddMemory()
.AddQueueInMemoryRedis() // ISetCache / ISetCache<T>
.AddResilienceStrategies().AddCloudEvents(),
o => { section.Bind(o); o.AppShortName = "my-service"; });
With Entra the connection string is the endpoint alone, no access key: "myamr.region.redis.azure.net:10000". An empty Caching:AzureEntra section uses DefaultAzureCredential; set ManagedIdentityClientId for a user-assigned identity. Set caches are injected like any other cache:
public class InviteService(ISetCache<string> pending)
{
public ValueTask<bool> TrackAsync(string tenant, string email, CancellationToken ct) =>
pending.AddAsync($"invites:{tenant}", email, ct);
}
Details: Entra recipe, set-cache settings.
A second Redis connection
A named caching stack is the whole thing again on another server: caches, set caches, locks, topics, warm-up. It reads the same Caching section; only Connections:<name> differs, and consumers pick it by key.
// The configuration root, not the section: AddNamedCaching takes the same sectionName as AddCaching ("Caching" by default).
builder.Services
.AddNamedCaching("SecondaryRedis", builder.Configuration, b => b.AddBroadcast().AddRedis().AddInMemoryRedis().AddQueueInMemoryRedis())
.ExposeQueueCaches();
public class ColdReports([FromKeyedServices("SecondaryRedis")] ICacheFactory cold) { ... }
Details: second Redis connection recipe.
Features
Resiliency
- Single-flight stampede protection — one generator runs per key on a cache miss; other callers coalesce. In-process single-flight per key (default on); cross-node via
IDistributedLock (AddInMemoryRedis() registers the impl automatically — opt in with DistributedLockEnabled: true; AddMemory()-only or custom wiring needs an explicit .AddRedisDistributedLock()).
- Hydrating cache — proactive background refresh before a key expires (
CachePolicy.RehydrateEnabled + RehydrateOptions). Avoids the expiry-miss path on hot keys so reads against still-live entries don't pay the factory cost. First-time misses still run the factory on the foreground caller.
- Polly pipelines — retry + circuit-breaker around every cache op (
AddResilienceStrategies). Configurable per-op timeout, break duration, and rethrow behavior.
- Connection-aware L1 fallback —
UseLocalOnlyWhenDisconnected + LocalMaxExpirationDisconnected keep the cache useful when Redis blips.
Distribution
- Multilayer L1 + L2 — in-process MemoryCache + Redis, written together, read L1-first. Different TTLs per tier.
- Redis Streams backplane — durable, at-least-once cross-node L1 invalidation with consumer groups and replay. Fallback to Pub/Sub if you don't need durability.
- Per-topic options — fine-grained overrides for fan-out, polling, backpressure, and the streams notify doorbell.
- Sharded Pub/Sub doorbell (Redis 7+) —
NotifyEnabled + NotifyShardedPubSub drop publish-to-deliver latency from PollInterval to network RTT without leaving the shard.
- Redis Cluster aware — shard-key routing, primary/replica split (writes to the primary, reads from replicas).
- Azure Managed Redis with Entra ID — passwordless auth via managed identity, workload identity, or any
TokenCredential (UiPath.Caching.Azure, AddAzureEntraAuthentication()). Tokens refresh automatically; TLS and RESP3 on by default. Other schemes (AWS IAM, a custom token source) plug into the same IRedisConnectionConfigurator seam without an Azure reference.
Advanced
- Set caches (
ISetCache / ISetCache<T>) — Redis-set collections next to the key-value caches (SADD / SPOP / SMEMBERS / SREM), in UiPath.Caching.Queue, with memory, Redis, and multilayer backings. Despite the package name a set is unordered: PopAsync removes a random member, not the oldest.
IHashCache<T> — one entry, many fields, one TTL. Subset reads via HMGET; side-channel metadata via HashCacheEntryOptions. Bundled GET + TTL in a single transaction for hydrating-cache math.
- Named cache policies — per-
ICache<T> settings keyed by typeof(T).FullName (TTLs, jitter, rehydration, lock profile). Inherits from DefaultCachePolicy with null-means-inherit semantics.
- L2 jitter —
JitterMaxDuration spreads cluster-wide expirations after bulk writes.
- Large-value auditing —
AuditEnabled + LargeValueThreshold log writes over a byte threshold.
Observability
ICachingTelemetryProvider seam with struct tag bags (TelemetryTags<T>; allocation-free when telemetry is off, and mockable). An OpenTelemetry adapter (ActivitySource + Meter) ships as UiPath.Caching.OpenTelemetry; OpenTelemetry Redis instrumentation wires up via the IConnectionMultiplexerFactory hook (see the sample).
- CloudEvents — broadcast events wrapped in the CNCF CloudEvents envelope (
UiPath.Caching.CloudEvents).
Architecture
flowchart LR
App["App code\n(ICache<T> / IHashCache<T>)"] --> ML[MultilayerCache]
ML -->|read first| L1[(L1: in-process)]
ML -->|miss / write| L2[(L2: Redis)]
ML -. wraps .-> SF[Single-flight\nlock]
ML -. wraps .-> POL[Polly pipeline]
L2 -.write fan-out.-> TOPIC{{Redis Streams\nbackplane}}
TOPIC -->|invalidation event| OtherL1[(Other nodes' L1)]
OtherL1 -.evicts.-> ML2[MultilayerCache on node B]
InMemoryRedis is the default provider — multilayer with the backplane wired. Redis (L2-only) and InMemory (L1-only, optional broadcast) are available for single-tier scenarios. See docs/concepts.md for the full mental model.
Packages
| Package |
When you need it |
UiPath.Caching.Abstractions |
Always (transitive). |
UiPath.Caching |
Always — providers, topics, locks. |
UiPath.Caching.Polly |
Resilience pipelines. Recommended. |
UiPath.Caching.CloudEvents |
CloudEvents envelope for broadcast events. Recommended. |
UiPath.Caching.OpenTelemetry |
OpenTelemetry adapter for ICachingTelemetryProvider — ActivitySource + Meter named UiPath.Caching. |
UiPath.Caching.Azure |
Microsoft Entra ID authentication for Azure Managed Redis / Azure Cache for Redis. Adds AddAzureEntraAuthentication(). |
UiPath.Caching.Queue |
Set ("queue") caches — ISetCache / ISetCache<T>, registered per backing via AddQueueMemory / AddQueueRedis / AddQueueInMemoryRedis. |
UiPath.Caching.MessagePack |
MessagePack value serializer with LZ4 compression above a size threshold; selected per policy through Serializer.Write. |
UiPath.Caching.Migration |
Moves cache groups between an existing Redis client and the library on one shared local tier, with the same keys and bytes on both. |
Documentation
| Topic |
Doc |
| 5-minute onboarding |
docs/quickstart.md |
| Upgrading from 1.x to 2.0 |
docs/upgrade-to-2.0.md |
| Architecture & mental model |
docs/concepts.md |
Which GetOrAddAsync shape to use (lambda, delegate, state, interpolated key) |
docs/how-to/choosing-a-get-or-add-overload.md |
| Resilience (single-flight, hydrating, jitter, Polly) |
docs/how-to/resilience.md |
| Broadcast (per-topic, notify doorbell, sharded Pub/Sub) |
docs/how-to/broadcast.md |
| Hash cache (metadata, bundled GET+TTL) |
docs/how-to/hash-cache.md |
| Telemetry + custom strategies |
docs/how-to/telemetry-and-strategies.md |
Quiet fills (TryFillAsync, SetIfChangedAsync) |
docs/how-to/quiet-fills.md |
| Router (existing Redis client and the library on one local tier) |
docs/how-to/router.md |