Redis  

How to Implement Redis Caching in ASP.NET Core for High Performance

Introduction

When your application starts growing, one of the first problems you will notice is performance. APIs become slower, database calls increase, and users start experiencing delays.

This is where caching plays a very important role.

Caching helps you store frequently used data in memory so that your application does not need to fetch it again and again from the database.

Redis is one of the most popular and powerful caching solutions used in modern applications.

In this guide, we will understand Redis caching in very simple words and learn how to implement it step by step in an ASP.NET Core application.

What is Caching?

Caching means storing data temporarily so that it can be reused quickly.

Instead of doing this every time:

  • Call database

  • Process data

  • Return result

You do this:

  • Check cache

  • If data exists → return immediately

  • If not → fetch from database and store in cache

In simple words:
Caching saves time by avoiding repeated work.

What is Redis?

Redis is an in-memory data store.

This means:

  • Data is stored in RAM (very fast)

  • Read/write operations are extremely quick

Redis is commonly used for:

  • Caching

  • Session storage

  • Real-time analytics

In simple words:
Redis is a super-fast storage system for temporary data.

Why Use Redis in ASP.NET Core?

  • Improves API response time

  • Reduces database load

  • Handles high traffic easily

  • Works well in distributed systems

Types of Caching in .NET

There are mainly two types:

  1. In-Memory Cache

    • Stored inside application memory

    • Fast but not shared across servers

  2. Distributed Cache (Redis)

    • Shared across multiple servers

    • Scalable and production-ready

In-Memory vs Redis Caching

FeatureIn-Memory CacheRedis Cache
ScopeSingle serverMultiple servers
SpeedVery fastVery fast
ScalabilityLimitedHigh
PersistenceNoOptional

Step-by-Step: Implement Redis in ASP.NET Core

Let’s implement Redis caching in a simple Web API.

Step 1: Install Redis Server

You can install Redis using:

  • Docker (recommended)

docker run -d -p 6379:6379 redis

This starts Redis locally.

Step 2: Install Required NuGet Package

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Step 3: Configure Redis in appsettings.json

{
  "Redis": {
    "ConnectionString": "localhost:6379"
  }
}

Step 4: Register Redis in Program.cs

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration["Redis:ConnectionString"];
});

This enables Redis as a distributed cache.

Step 5: Create a Caching Service

using Microsoft.Extensions.Caching.Distributed;

public class CacheService
{
    private readonly IDistributedCache _cache;

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

    public async Task SetAsync(string key, string value)
    {
        await _cache.SetStringAsync(key, value);
    }

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

Step 6: Use Cache in Controller

[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
    private readonly CacheService _cacheService;

    public ProductController(CacheService cacheService)
    {
        _cacheService = cacheService;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var cacheKey = "products";

        var cachedData = await _cacheService.GetAsync(cacheKey);

        if (!string.IsNullOrEmpty(cachedData))
        {
            return Ok("Data from cache: " + cachedData);
        }

        // Simulate database call
        var data = "Product list from database";

        await _cacheService.SetAsync(cacheKey, data);

        return Ok("Data from DB: " + data);
    }
}

Step 7: Add Expiration (Important)

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

This ensures data is refreshed after some time.

Step 8: Cache Invalidation Strategy

Caching is useful, but you must update cache when data changes.

Common strategies:

  • Remove cache when data updates

  • Use short expiration times

  • Use versioned keys

Best Practices for Redis Caching

  • Cache only frequently used data

  • Do not cache sensitive data

  • Use proper expiration

  • Use meaningful cache keys

  • Monitor cache usage

Real-World Use Cases

  • Product listing APIs

  • Dashboard data

  • Session storage

  • API response caching

Conclusion

Redis caching is one of the easiest ways to improve performance in ASP.NET Core applications. It reduces database load, speeds up responses, and helps your application scale efficiently.

Start with basic caching, then move towards advanced strategies like cache invalidation and distributed caching to build high-performance applications.