Redis  

How to Use Distributed Caching in ASP.NET Core with Redis

Redis Object Cache – WordPress plugin | WordPress.org

Introduction

When you build an ASP.NET Core application, one of the biggest challenges is performance. As your application grows and more users start using it, your database gets hit again and again for the same data. This slows down your application and increases server load.

This is where distributed caching with Redis helps.

Instead of calling the database every time, you store frequently used data in a fast in-memory system like Redis. The next time someone requests the same data, it is returned instantly from the cache instead of the database.

In this guide, you will learn step-by-step how to use Redis distributed caching in ASP.NET Core in simple and practical terms.

What is Distributed Caching?

Distributed caching means storing your cached data outside your application, usually in a separate service like Redis.

In a normal (in-memory) cache, data is stored inside a single server. If your application runs on multiple servers, each server will have its own cache, which can cause inconsistency.

But in distributed caching:

  • All servers share the same cache

  • Data remains consistent across the application

  • It works well in scalable environments

In simple words, distributed cache is like a shared memory that all your application servers can use.

What is Redis?

Redis is a very fast, in-memory data store that is widely used for caching.

Think of Redis as a super-fast dictionary where:

  • You store data using a key

  • You retrieve data using the same key

Why developers prefer Redis:

  • It is extremely fast because it stores data in memory

  • It supports simple key-value storage

  • It is easy to integrate with ASP.NET Core

  • It works great for scalable and cloud-based applications

Prerequisites

Before starting, make sure you have the following ready:

  • .NET SDK installed on your system

  • A working ASP.NET Core project

  • Redis installed locally or access to a cloud Redis service

  • Basic understanding of controllers and services in ASP.NET Core

If Redis is not installed locally, you can use Docker or any cloud provider.

Step 1: Install Required NuGet Package

First, you need to install the Redis caching package.

Run the following command:

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

This package connects your ASP.NET Core application with Redis and enables distributed caching support.

Step 2: Configure Redis in ASP.NET Core

Next, you need to tell your application how to connect to Redis.

Open your Program.cs file and add the following configuration:

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
    options.InstanceName = "SampleApp_";
});

Explanation in simple terms:

  • localhost:6379 → This is the address where Redis is running

  • InstanceName → A prefix added to all cache keys (helps in organizing data)

If you are using cloud Redis, replace the localhost value with your connection string.

Step 3: Inject IDistributedCache Service

ASP.NET Core provides a built-in interface called IDistributedCache to work with Redis.

You need to inject it into your service or controller.

public class ProductService
{
    private readonly IDistributedCache _cache;

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

In simple words, this allows your class to talk to Redis.

Step 4: Store Data in Redis Cache

To store data in Redis, you use the SetStringAsync method.

public async Task SetCacheDataAsync(string key, string value)
{
    var options = new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
    };

    await _cache.SetStringAsync(key, value, options);
}

What is happening here:

  • You are saving data using a unique key

  • You are setting an expiration time (10 minutes)

Why expiration is important:

  • Prevents outdated data

  • Keeps cache clean

  • Saves memory

Step 5: Retrieve Data from Cache

To get data from Redis, you use:

public async Task<string> GetCacheDataAsync(string key)
{
    return await _cache.GetStringAsync(key);
}

If the data exists, it returns instantly.
If not, it returns null.

This is much faster than calling the database.

Step 6: Implement Cache-Aside Pattern

The most common way to use caching is the Cache-Aside pattern.

This means:

  1. First check cache

  2. If data exists → return it

  3. If not → fetch from database and store in cache

Example:

public async Task<string> GetProductAsync(string productId)
{
    string cacheKey = $"product_{productId}";

    var cachedData = await _cache.GetStringAsync(cacheKey);

    if (!string.IsNullOrEmpty(cachedData))
    {
        return cachedData;
    }

    var productData = "Product from Database";

    await _cache.SetStringAsync(cacheKey, productData, new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
    });

    return productData;
}

This approach:

  • Reduces database calls

  • Improves response time

  • Automatically fills cache when needed

Step 7: Working with Complex Objects

Redis stores data as strings, so for objects, you need to convert them into JSON.

public async Task SetObjectAsync<T>(string key, T data)
{
    var jsonData = JsonSerializer.Serialize(data);

    await _cache.SetStringAsync(key, jsonData);
}

public async Task<T> GetObjectAsync<T>(string key)
{
    var jsonData = await _cache.GetStringAsync(key);

    return jsonData == null ? default : JsonSerializer.Deserialize<T>(jsonData);
}

In simple words:

  • Convert object → JSON → store in Redis

  • Retrieve JSON → convert back to object

Step 8: Remove Data from Cache

Sometimes you need to delete outdated or incorrect cache data.

await _cache.RemoveAsync("product_1");

This is useful when:

  • Data is updated in database

  • Cache becomes invalid

Step 9: Best Practices for Redis Caching

To use Redis effectively, follow these simple practices:

  • Use clear and unique cache keys

  • Always set expiration time

  • Do not cache sensitive data

  • Avoid storing very large objects

  • Monitor cache usage and performance

These practices help maintain performance and avoid issues later.

Step 10: Common Use Cases

Redis caching is commonly used for:

  • API response caching

  • Product listings

  • User sessions

  • Frequently accessed data

  • Dashboard data

If data is read frequently but changes less often, it is a good candidate for caching.

Advantages of Using Redis in ASP.NET Core

Using Redis gives several benefits:

  • Faster application performance

  • Reduced database load

  • Better scalability

  • Improved user experience

It is especially useful in high-traffic applications.

Summary

Distributed caching with Redis in ASP.NET Core is a simple yet powerful way to improve application performance. Instead of repeatedly calling the database, you store frequently used data in Redis and retrieve it quickly when needed. By following the step-by-step approach, using patterns like Cache-Aside, and applying best practices, you can build fast, scalable, and efficient applications. Start small, implement caching where it matters most, and gradually optimize your system for better performance.