Slider

Caching in ASP.NET Core.

Caching is the technique of storing frequently accessed data in temporary fast storage so that future requests can be served faster without repeatedly calling a slow source like a database or external API.

👉 In simple words: Cache = Fast memory that avoids repeated expensive operations

Without caching:

  • Every request hits the database
  • Higher response time
  • Increased load on DB
  • Poor scalability

With caching:

  • Faster response time
  • Reduced database calls
  • Better scalability
  • Lower infrastructure cost

Imagine a restaurant menu:
  • ❌ Without cache → Chef cooks every dish from scratch every time
  • ✅ With cache → Popular dishes are pre-prepared and served instantly
That pre-prepared dish = Cache

How does caching work?
  1. Client requests data
  2. Application checks the cache first
  3. If found → return from cache (cache hit)
  4. If not found → fetch from DB, store in cache (cache miss)

Types of Caching in ASP.NET Core

There are two main types you must know as a .NET developer:
  • In-Memory Cache
  • Distributed Cache

In-Memory Caching.

In-Memory Cache stores data in the RAM of the application server.

  • Lives inside the application process
  • Very fast
  • Data is lost when the app restarts
How To Implement In-Memory Caching?

Step 1: Register Memory Cache.
builder.Services.AddMemoryCache();

Step 2: Inject IMemoryCache
using Microsoft.Extensions.Caching.Memory;

public class ProductService
{
    private readonly IMemoryCache _cache;

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

Step 3: Cache Data Using Cache-Aside Pattern
public List<string> GetProducts()
{
    const string cacheKey = "products";

    if (!_cache.TryGetValue(cacheKey, out List<string> products))
    {
        // Simulate DB call
        products = GetProductsFromDatabase();

        var cacheOptions = new MemoryCacheEntryOptions()
            .SetAbsoluteExpiration(TimeSpan.FromMinutes(5))
            .SetSlidingExpiration(TimeSpan.FromMinutes(2));

        _cache.Set(cacheKey, products, cacheOptions);
    }

    return products;
}
When to Use In-Memory Cache:
  • Small applications
  • Single server apps
  • Lookup / static data
  • Config values
  • Not suitable for load-balanced systems

Distributed Caching.

Distributed Cache stores data in a separate cache server shared across multiple application instances.
Common implementations:
  • Redis
  • SQL Server Cache
  • NCache
Let's understand in detail, with Redis as an example, because it is one of the most popular Caching System.

Redis is an in-memory distributed cache used to:
  • Share cached data across multiple app instances
  • Improve performance
  • Reduce database load
👉 Unlike in-memory cache, Redis works in load-balanced & microservice environments.

Prerequisites
  • Option 1: Run Redis using Docker (Port: 6379)
  • Option 2: Local Redis
Step 1: Install Required NuGet Packages
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Step 2: Configure Redis in ASP.NET Core
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration =
        "my-redis.xxxxxx.use1.cache.amazonaws.com:6379";

    options.InstanceName = "MyApp:";
});

Step 3: Use Redis via IDistributedCache (Service Layer).
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

public class ProductService
{
    private readonly IDistributedCache _cache;

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

Step 4: Cache-Aside Pattern Implementation.
public async Task<List<Product>> GetProductsAsync()
{
    const string cacheKey = "products";

    var cachedData = await _cache.GetStringAsync(cacheKey);

    if (cachedData != null)
    {
        return JsonSerializer.Deserialize<List<Product>>(cachedData);
    }

    // Simulate DB call
    var products = GetProductsFromDatabase();

    var options = new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
        SlidingExpiration = TimeSpan.FromMinutes(2)
    };

    await _cache.SetStringAsync(
        cacheKey,
        JsonSerializer.Serialize(products),
        options
    );

    return products;
}

Step 5: Cache Invalidation
public async Task UpdateProductAsync(Product product)
{
    // Update DB logic

    await _cache.RemoveAsync("products");
}
Note: Caching without invalidation is a bug, not a feature.
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents