Monday, 22 September 2025

Caching

💡 What Is Caching?

Caching means storing frequently used data in a fast place (memory or a dedicated cache server) so you don’t have to recalculate or re-fetch it every time.

Think of it like keeping your most-used tools on your desk instead of running to the garage each time.


🎯 Why Use Caching?

  • Speed: Faster responses for users.

  • 💰 Cost: Fewer database or API calls → saves money.

  • 🔒 Resilience: Can serve data even if the database is slow or temporarily down.


🏷️ Common Types of Caching

1. In-Memory Cache

  • Data stored inside the app’s memory (RAM).

  • Super fast but cleared when the app restarts or scales out to multiple servers.

  • .NET Example: IMemoryCache (built into ASP.NET Core).

services.AddMemoryCache();
public class ProductService { private readonly IMemoryCache _cache; public ProductService(IMemoryCache cache) { _cache = cache; } public Product GetProduct(int id) { return _cache.GetOrCreate($"product_{id}", entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10); return LoadProductFromDatabase(id); }); } }

2. Distributed Cache

  • Shared cache for multiple servers/instances.

  • Good for cloud or load-balanced apps.

  • Examples: Redis, SQL Server cache, NCache.

services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost:6379"; });

3. Output/Response Caching

  • Cache the whole HTTP response.

  • Useful for pages or APIs that don’t change often.

[ResponseCache(Duration = 60)] public IActionResult GetWeather() => Ok(weatherData);

4. Client-Side/Browser Cache

  • Store static files (images, CSS, JS) or API responses in the browser.

  • Controlled with HTTP headers (Cache-Control, ETag).


🧠 Cache Strategies

  • Absolute Expiration: Cache expires after a fixed time (e.g., 10 minutes).

  • Sliding Expiration: Reset the timer every time the data is accessed.

  • Cache Aside (Lazy Loading): Check cache first; if not present, load from source and add to cache.

  • Write-Through / Write-Behind: Write data to the cache and database at the same time or asynchronously.


⚠️ Things to Watch

  • Stale Data: Data might become outdated—set expiration wisely.

  • Cache Invalidation: Decide how/when to remove or refresh data.

  • Memory Limits: Monitor size to avoid crashes or evictions.


✅ Quick Best Practices

  • Cache only expensive or frequently used data.

  • Use distributed caching for scalable web apps.

  • Monitor hit/miss rates and memory usage.

  • Protect sensitive data—don’t cache private info carelessly.


🏁 Recap

Caching = storing frequently used data for quick reuse.

TypeWhere storedExample in .NET
In-MemoryApp memoryIMemoryCache
DistributedExternal serverRedis, SQL Server
Output/ResponseWeb/API responses[ResponseCache]
Client/BrowserUser’s browserCache headers

By combining the right caching type and strategy, you can make your .NET apps faster, cheaper, and more reliable.

No comments:

Post a Comment