.NET Caching: IMemoryCache, HybridCache and Redis
On this page
Learning Objective
Apply the cache-aside pattern with IMemoryCache, HybridCache and Redis, prevent cache stampedes, design keys that cannot leak data between users or tenants, choose safe serialization and TTLs, and secure the Redis server itself.
Concept Explanation
Caching stores the result of expensive work so repeated requests can skip it. On the server there are two layers. In-process memory, IMemoryCache, is the fastest possible cache and needs no network, but each server instance has its own copy, which can drift and is lost on restart. A distributed cache such as Redis is shared by all instances and survives an application restart, at the price of a network round trip and serialization. The standard usage pattern for both is cache-aside: look in the cache first, on a miss load from the source of truth, store the result with an expiry, and return it. Writes go to the database, and the cached copy is either updated or removed.
HybridCache, generally available in .NET since version 9, combines the two layers behind one API. A call to GetOrCreateAsync checks a small in-process level first, then Redis, and only then runs your factory method to load the data. It also solves a problem that hand-written cache-aside code usually gets wrong, the cache stampede: when a popular entry expires, hundreds of concurrent requests miss at once and all hit the database. HybridCache coalesces concurrent requests for the same key so only one runs the factory and the others wait for its result. It supports tags for invalidating groups of entries, and configurable expirations for each level. Facebook's 2013 memcache paper described lease mechanisms for the same herd problem at very large scale.
Cache keys and contents are where security bugs occur. A key that omits something the data depends on will serve one caller's data to another. If you cache a project list under the key projects, every user gets whichever list was cached first. Keys must include every input that changes the answer: the tenant, the user or their permission set, the language, and the parameters. A safer design is to cache only data that is identical for everyone, for example reference data, and to apply authorization to the result after retrieving it from the cache, never relying on the cache to decide who may see what. Also cache misses deserve thought: negative caching, remembering that something does not exist, saves database calls for repeated lookups of missing ids but must expire quickly and be bounded so an attacker cannot fill the cache with random keys.
Serialization and the cache server need care. Use System.Text.Json or another safe serializer, never BinaryFormatter, whose deserialization is a well-known code execution vector and is removed from modern .NET. Choose TTLs deliberately: short for data that changes and matters, longer for stable reference data, and add jitter so many keys do not expire at the same instant. The Redis server itself is a high-value target. Historically it shipped with no authentication and listening broadly, and large numbers of exposed instances have been found and abused. Run it on a private network, require authentication and TLS, prefer identity-based access on Azure Cache for Redis, and disable dangerous administrative commands. Since cached data is a copy of your database, it carries the same sensitivity, so avoid caching secrets and personal data unless you have decided to.
| Layer | Strength | Limit |
|---|---|---|
| IMemoryCache | Fastest, no network | Per instance, lost on restart, can differ between servers |
| Redis, IDistributedCache | Shared by all instances, survives restarts | Network and serialization cost |
| HybridCache | Both layers, stampede protection, tags | Requires serializer configuration |
| Output caching | Whole HTTP responses | Only safe for data identical across callers |
| Cache-aside | Read from cache, fall back to source, then store | You manage invalidation |
| Negative caching | Remember missing items briefly | Short TTL, bounded size |
Worked Example: HybridCache with Safe Keys, Tags and a Hardened Redis Connection
The configuration sets up HybridCache over Redis. The service shows keys that include tenant, stampede-safe loading, tag invalidation, and authorization applied after retrieval.
// Program.cs
builder.Services.AddStackExchangeRedisCache(o =>
{
o.Configuration = builder.Configuration["Redis:Configuration"]; // rediss:// with TLS, from Key Vault, never committed
o.InstanceName = "taskboard:";
});
builder.Services.AddHybridCache(o =>
{
o.MaximumPayloadBytes = 256 * 1024; // refuse to cache huge values
o.MaximumKeyLength = 256;
o.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5), // distributed level
LocalCacheExpiration = TimeSpan.FromMinutes(1), // in-process level
};
});public sealed class ProjectQueries(AppDb db, HybridCache cache, ICurrentTenant tenant)
{
// The key contains everything the answer depends on. No shared "projects" key.
private string Key(string what, params object[] parts) =>
$"t:{tenant.Id}:{what}:{string.Join(':', parts)}";
// Reference data that is identical for everyone in the tenant: safe to cache directly.
public ValueTask<IReadOnlyList<LabelDto>> GetLabelsAsync(Guid projectId, CancellationToken ct) =>
cache.GetOrCreateAsync(
Key("labels", projectId),
async token => (IReadOnlyList<LabelDto>)await db.Labels.AsNoTracking()
.Where(l => l.ProjectId == projectId).Select(l => new LabelDto(l.Id, l.Name)).ToListAsync(token),
new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(10 + Random.Shared.Next(0, 120) / 60.0) }, // jitter
tags: [$"tenant:{tenant.Id}", $"project:{projectId}"],
cancellationToken: ct);
// User-specific data: the user is part of the key, and authorization still runs against live data.
public ValueTask<IReadOnlyList<ProjectSummary>> GetMyProjectsAsync(Guid userId, CancellationToken ct) =>
cache.GetOrCreateAsync(
Key("myprojects", userId),
async token => (IReadOnlyList<ProjectSummary>)await db.Projects.AsNoTracking()
.Where(p => p.Members.Any(m => m.UserId == userId))
.Select(p => new ProjectSummary(p.Id, p.Name)).ToListAsync(token),
new HybridCacheEntryOptions { Expiration = TimeSpan.FromSeconds(30), LocalCacheExpiration = TimeSpan.FromSeconds(30) },
tags: [$"user:{userId}"],
cancellationToken: ct);
// Invalidate after a write. Removing by tag clears every related entry on every instance.
public ValueTask InvalidateProjectAsync(Guid projectId, CancellationToken ct) =>
cache.RemoveByTagAsync($"project:{projectId}", ct);
}
// Bad, for contrast: a key that ignores the caller leaks data between users.
// cache.GetOrCreateAsync("projects", ...) // the first user's list is served to everyone// A test that proves the keys isolate users and tenants.
[Fact]
public async Task Cached_project_lists_never_cross_users()
{
var alice = await queries.GetMyProjectsAsync(aliceId, default);
var bob = await queries.GetMyProjectsAsync(bobId, default);
Assert.DoesNotContain(bob, p => alice.Select(a => a.Id).Contains(p.Id) && !BobIsMember(p.Id));
}# Redis hardening checklist (Azure Cache for Redis or self-hosted)
- Private network only: private endpoint or VNet, never a public address
- TLS required, non-TLS port disabled; Microsoft Entra authentication or a strong secret from Key Vault
- Disable or rename dangerous commands such as CONFIG, FLUSHALL, DEBUG, and EVAL where not needed
- Set maxmemory and an eviction policy so a flood of keys cannot exhaust memory
- Never cache secrets, tokens, or full personal records unless there is a documented reasonThe user-specific query is cached for only 30 seconds, since a membership change should take effect quickly; for anything where revocation must be immediate, skip the cache or invalidate by tag on every membership change.
Real-World Examples
- The 2013 NSDI paper Scaling Memcache at Facebook described how a single hot key expiring could send thousands of simultaneous requests to the database, and introduced leases so that one client is chosen to refill the value while others wait or receive slightly stale data. HybridCache's request coalescing applies the same idea inside a .NET process.
- Security researchers regularly find very large numbers of Redis servers exposed to the internet without authentication, and attackers have used them to steal cached data and to plant scheduled tasks or SSH keys for remote code execution through the CONFIG command. It is a leading example of how a performance component becomes an entry point when its network exposure and default settings are ignored.
Review Questions & Answers
When a popular entry expires, many concurrent requests miss at the same moment and all query the database, which can overload it. HybridCache coalesces concurrent requests for the same key so only one runs the factory to reload the value while the rest wait for its result, turning a burst of database calls into one.
If the key omits an input the result depends on, such as the user, tenant, or filter parameters, all callers share one entry, and the first caller's data is served to everyone else. Keys must include everything that changes the answer, and the design should prefer caching data that is truly identical for all callers.
Deserializing untrusted or tamperable data with it can instantiate arbitrary types and execute code, and an attacker who can write to the cache can exploit that. It has been removed from current .NET. Safe serializers such as System.Text.Json only populate the declared type, which removes that attack vector.
If many entries are created together with the same lifetime, they all expire together, causing a wave of misses and database load at the same instant. Adding a random amount to each expiration spreads reloads over time and keeps the load on the source smooth.