Phase 28 of 30 · Topic 28.1

.NET 9 `HybridCache`: Two-Tier L1 (In-Memory) + L2 (Redis) Architecture

1Concept

`HybridCache` combines ultra-fast in-process L1 memory caching with out-of-process distributed L2 caching (Redis). Reads hit L1 memory in ~5ns, falling back to L2 Redis in ~1ms, and database in ~20ms.

2Architecture Diagram

API Request for Key: "user:101"
       │
   [ L1 In-Memory Cache (RAM) ] ── Hit (~5ns)? ──> Return immediately!
       │ (Miss)
   [ L2 Distributed Cache (Redis) ] ── Hit (~1ms)? ──> Populate L1 RAM & Return!
       │ (Miss)
   [ Database Query (PostgreSQL) ] ──> Populate L2 Redis & L1 RAM & Return!

3Code Example

C# 13 & .NET 9
using System;

public class HybridCacheConceptDemo
{
    public static void Main()
    {
        Console.WriteLine("--- .NET 9 HybridCache ---");
        Console.WriteLine("var user = await hybridCache.GetOrCreateAsync(");
        Console.WriteLine("    $"user:{userId}",");
        Console.WriteLine("    async token => await dbContext.Users.FindAsync(userId, token)");
        Console.WriteLine(");");
    }
}

4Expected Output

--- .NET 9 HybridCache ---
var user = await hybridCache.GetOrCreateAsync(
    $"user:{userId}",
    async token => await dbContext.Users.FindAsync(userId, token)
);

5Key Takeaways

  • `HybridCache` replaces boilerplate multi-layer cache helper code.
  • Automatically synchronizes L1 eviction across server cluster nodes via Redis pub/sub.
  • Drastically reduces network bandwidth between web servers and Redis cluster.