Caching Strategies in ASP.NET Core (In-Memory vs Distributed)

>

๐Ÿ’ก Concept Name

Caching Strategies: In-Memory & Distributed

๐Ÿ“˜ Quick Intro

Caching is a way to store data temporarily to reduce database or API calls. ASP.NET Core supports In-Memory and Distributed caching mechanisms. In-Memory is simple and fast, but works only within a single server. Distributed cache like Redis allows sharing across servers.

๐Ÿง  Analogy / Short Story

Think of In-Memory cache like a whiteboard on your desk โ€” quick to access but only for you. If your desk moves (server restarts), data is lost. Distributed cache is like a shared cloud drive โ€” accessible from multiple desks (servers) and persists even if one machine fails.

๐Ÿ”ง Technical Explanation

ASP.NET Core offers two built-in cache interfaces: `IMemoryCache` for local caching and `IDistributedCache` for external stores like Redis or SQL Server.

Caching reduces server load and response time. Data can be stored with expiration settings like absolute or sliding expiration. Use distributed caching for scalable apps and clustered environments.

๐ŸŽฏ Purpose & Use Case

  • โœ… Improve performance by reducing repetitive DB calls
  • โœ… Store frequently accessed configuration or query results
  • โœ… Enable scalable caching across multiple servers (Distributed)
  • โœ… Reduce latency for read-heavy APIs
  • โœ… Persist cache even after server restarts (Distributed)

๐Ÿ’ป Real Code Example

// In-Memory Caching Setup
builder.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 FetchProductFromDb(id); // Simulate DB call
        });
    }
}

// Distributed Cache Setup (Redis)
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "localhost:6379";
});

โ“ Interview Q&A

Q1: What is In-Memory Caching?
A: Local cache stored in server RAM, fast but non-distributed.

Q2: What is Distributed Caching?
A: External caching system (e.g., Redis) accessible across servers.

Q3: Which interface does In-Memory cache use?
A: `IMemoryCache`

Q4: Which interface does Distributed cache use?
A: `IDistributedCache`

Q5: Can you use expiration in cache?
A: Yes, using absolute and sliding expiration options.

Q6: When to prefer Distributed cache?
A: When running in multi-server environments or needing persistence.

Q7: Name a popular Distributed cache system.
A: Redis

Q8: Is caching secure for sensitive data?
A: Not recommended unless encrypted and protected.

Q9: Can we use both caches together?
A: Yes, depending on data type and need.

Q10: How to clear a specific cache item?
A: Use `Remove(key)` method of the cache service.

๐Ÿ“ MCQs

Q1. Which interface is used for In-Memory cache?

  • IDistributedCache
  • ICacheService
  • IMemoryCache
  • ICacheManager

Q2. Which caching is suitable for distributed apps?

  • Memory Cache
  • Session Cache
  • Cookie Cache
  • Distributed Cache

Q3. What is used to cache data for 10 minutes?

  • CacheTimeout
  • SlidingExpiration
  • FixedExpiration
  • AbsoluteExpirationRelativeToNow

Q4. Which system is commonly used for distributed cache?

  • MongoDB
  • MySQL
  • Redis
  • SQLite

Q5. Is In-Memory cache shared across servers?

  • Yes
  • No
  • Sometimes
  • Only with Redis

Q6. How do you remove a cached item?

  • cache.Clear()
  • cache.Flush()
  • cache.Remove(key)
  • cache.DeleteAll()

Q7. What happens to In-Memory cache after restart?

  • Data persists
  • Data syncs
  • It is cleared
  • It auto-saves

Q8. Which caching is best for high-availability?

  • Session
  • In-Memory
  • Distributed
  • None

Q9. Where does `IDistributedCache` store data?

  • Client browser
  • Memory
  • Temp folder
  • External systems like Redis

Q10. Which cache allows `GetOrCreate()` method?

  • IDistributedCache
  • IMemoryCache
  • ICacheHelper
  • ICustomCache

๐Ÿ’ก Bonus Insight

Use cache thoughtfully. Never cache sensitive data unless encrypted. Also consider cache busting strategies to avoid serving stale data to users.

๐Ÿ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

๐Ÿ’ฌ Feedback
๐Ÿš€ Start Learning
Share:

Tags: