Section 2 of 6

Distributed Caching

🎯 What You'll Learn

  • What is distributed caching
  • IDistributedCache interface
  • SQL Server cache
  • Redis cache
  • Serialization

What is Distributed Caching?

Distributed caching stores cache data in an external system (Redis, SQL Server) shared across multiple servers, enabling scalability and persistence.

In-Memory vs Distributed

Aspect In-Memory Distributed
Storage Local server memory External cache server
Shared No (per server) Yes (across servers)
Persistence Lost on restart Can persist
Speed Fastest Slower (network)
Use Case Single server Multiple servers

IDistributedCache Interface

Inject IDistributedCache C#
public class ProductsController : Controller
{
    private readonly IDistributedCache _cache;

    public ProductsController(IDistributedCache cache)
    {
        _cache = cache;
    }
}

SQL Server Distributed Cache

Install Package Bash
dotnet add package Microsoft.Extensions.Caching.SqlServer
Create Cache Table Bash
dotnet sql-cache create "Data Source=.;Initial Catalog=InvenTrack;Integrated Security=True" dbo CacheTable
Program.cs C#
builder.Services.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    options.SchemaName = "dbo";
    options.TableName = "CacheTable";
});

Redis Distributed Cache

Install Package Bash
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
Program.cs C#
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "InvenTrack_";
});

Using IDistributedCache

IDistributedCache stores byte arrays, so you need to serialize objects.

Set and Get with Serialization C#
// Set
var json = JsonSerializer.Serialize(products);
await _cache.SetStringAsync("products", json, new DistributedCacheEntryOptions
{
    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});

// Get
var cachedJson = await _cache.GetStringAsync("products");
if (cachedJson != null)
{
    var products = JsonSerializer.Deserialize<List<Product>>(cachedJson);
}

InvenTrack Example

ProductsController.cs C#
public class ProductsController : Controller
{
    private readonly IDistributedCache _cache;
    private readonly InvenTrackDbContext _context;

    [HttpGet]
    public async Task<IActionResult> Index()
    {
        const string cacheKey = "products_list";

        // Try get from cache
        var cachedJson = await _cache.GetStringAsync(cacheKey);
        
        List<Product> products;
        
        if (cachedJson != null)
        {
            // Deserialize from cache
            products = JsonSerializer.Deserialize<List<Product>>(cachedJson);
        }
        else
        {
            // Fetch from database
            products = await _context.Products.ToListAsync();

            // Serialize and cache
            var json = JsonSerializer.Serialize(products);
            await _cache.SetStringAsync(cacheKey, json, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
            });
        }

        return View(products);
    }
}

Key Takeaways

  • Distributed cache: Shared across servers
  • IDistributedCache: Interface for distributed caching
  • SQL Server: AddDistributedSqlServerCache()
  • Redis: AddStackExchangeRedisCache()
  • Serialization: Use JSON for objects
  • SetStringAsync/GetStringAsync: String methods