---
title: "How can you implement distributed caching with Azure Redis Cache in an ASP.NET Core application?"  
description: "How can you implement distributed caching with Azure Redis Cache in an ASP.NET Core application?"  
author: "John Smith"  
published: 2026-09-17  
updated: 2026-10-12  
canonical: https://answers.mindstick.com/qa/117207/how-can-you-implement-distributed-caching-with-azure-redis-cache-in-an-asp-net-core-application  
category: "Performance"  
tags: ["Redis", "Caching", "performance"]  
reading_time: 4 minutes  

---

# How can you implement distributed caching with Azure Redis Cache in an ASP.NET Core application?

## Offloading State with Redis

Session state, rate-limit counters, and expensive query results all benefit from an external cache. Azure Cache for Redis gives you a managed, low-latency store that sits outside your app's process memory.

### Connection and Configuration

Add the Microsoft.Extensions.Caching.StackExchangeRedis package, then wire it into Startup.cs with the connection string from your app settings. The default serializer works for most DTOs, but switch to MessagePack if you need smaller payloads.

```cs
// Register Redis as the distributed cache in Startup.ConfigureServices.
// The connection string should come from environment variables, not source code.
services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = Environment.GetEnvironmentVariable("REDIS_CONNECTION");
    options.InstanceName = "myapp-cache";
    // Setting a reasonable size limit prevents memory bloat on the Redis node.
    options.SizeLimit = 100 * 1024 * 1024; // 100 MB
});

// Example usage inside a controller action:
// cache.StringSet("user:42", userData, TimeSpan.FromMinutes(10));
// var cached = cache.StringGet("user:42");
```

Monitor eviction rates and memory usage in the Azure portal. If you see frequent evictions, either increase the SKU size or rethink your key TTL strategy.

## Answers

### Answer by Mukul Goenka

For an ASP.NET Core app running on multiple instances, [Azure Cache for Redis](https://answers.mindstick.com/qa/117207/how-can-you-implement-distributed-caching-with-azure-redis-cache-in-an-aspnet-core-application) can provide a shared cache: one instance writes a value, and the others can read it. The built-in `IDistributedCache` abstraction keeps your application code independent of Redis-specific commands.

## Register the Redis cache

Install the `Microsoft.Extensions.Caching.StackExchangeRedis` package. Store the Redis connection string in configuration supplied securely by your deployment environment or a secret store, rather than committing credentials to source control.

```cs
var builder = WebApplication.CreateBuilder(args);

// Read the connection string from configuration; keep its credentials outside source control.
var redisConnection = builder.Configuration.GetConnectionString("Redis")
    ?? throw new InvalidOperationException("Redis connection string is missing.");

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = redisConnection;
    // Prefix keys to distinguish this application from other users of the same Redis instance.
    options.InstanceName = "catalog:";
});

builder.Services.AddScoped<ProductCache>();

var app = builder.Build();
```

For Azure Cache for Redis, the connection string typically includes the cache host, TLS settings, and authentication details. Use the endpoint and authentication method configured for your Azure resource; keep TLS enabled for connections over the network.

## Use a cache-aside pattern

With cache-aside, the app checks Redis first, loads from the underlying data source on a miss, then stores the result for later requests. This example assumes your application already has an `IProductRepository` that loads products from its database.

```cs
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;

public sealed class ProductCache
{
    private readonly IDistributedCache _cache;
    private readonly IProductRepository _repository;

    public ProductCache(IDistributedCache cache, IProductRepository repository)
    {
        _cache = cache;
        _repository = repository;
    }

    public async Task<Product?> GetAsync(int id, CancellationToken cancellationToken)
    {
        // Versioned product cache keys make future cache format changes easier to manage.
        var key = $"product:v1:{id}";
        var cached = await _cache.GetStringAsync(key, cancellationToken);

        if (cached is not null)
        {
            return JsonSerializer.Deserialize<Product>(cached);
        }

        // Load from the source of truth only when Redis does not contain the product.
        var product = await _repository.GetByIdAsync(id, cancellationToken);
        if (product is null)
        {
            return null;
        }

        var options = new DistributedCacheEntryOptions
        {
            // A finite lifetime prevents old values from staying in the cache indefinitely.
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
        };

        var json = JsonSerializer.Serialize(product);
        await _cache.SetStringAsync(key, json, options, cancellationToken);

        return product;
    }

    public Task RemoveAsync(int id, CancellationToken cancellationToken)
    {
        // Call this after a product update so the next read fetches fresh data.
        return _cache.RemoveAsync($"product:v1:{id}", cancellationToken);
    }
}
```

Call `RemoveAsync` after successful writes to the product database. That cache invalidation step matters: expiration limits how long stale data can linger, but it does not make an update visible immediately. Choose a key format and expiration that suit your data, and avoid caching sensitive values unless your security and retention requirements allow it.

Because all app instances use the same Redis service, this approach provides a shared Redis cache across instances without relying on each server’s local memory. It is a straightforward way to add distributed cache in ASP.NET Core while keeping the Redis implementation behind `IDistributedCache`.


---

Original Source: https://answers.mindstick.com/qa/117207/how-can-you-implement-distributed-caching-with-azure-redis-cache-in-an-asp-net-core-application

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
