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?
- Client requests data
- Application checks the cache first
- If found → return from cache (cache hit)
- 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();
using Microsoft.Extensions.Caching.Memory; public class ProductService { private readonly IMemoryCache _cache; public ProductService(IMemoryCache cache) { _cache = cache; } }
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
builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "my-redis.xxxxxx.use1.cache.amazonaws.com:6379"; options.InstanceName = "MyApp:"; });
using Microsoft.Extensions.Caching.Distributed; using System.Text.Json; public class ProductService { private readonly IDistributedCache _cache; public ProductService(IDistributedCache cache) { _cache = cache; }
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"); }
No comments
Post a Comment