Caching & Redis Patterns


What is Caching?

Caching = Storing frequently accessed data in fast-access storage to improve performance

Benefits:

  • Faster response times - Avoid expensive operations

  • 💰 Reduced costs - Fewer database queries

  • 📈 Better scalability - Handle more requests

  • 🛡️ Resilience - Serve cached data if backend is down

  • 🔋 Resource efficiency - Less CPU/memory/network usage

Common Use Cases:

  • Database query results

  • API responses

  • Computed values

  • User sessions

  • Configuration data

  • Static content


Caching Strategies

When to Cache?

Cache Levels


In-Memory Caching (IMemoryCache)

Setup

Basic Usage

Cache Options

GetOrCreate Pattern

Cache Invalidation

Cache Keys Helper


Distributed Caching (IDistributedCache)

Why Distributed Cache?

Setup (Redis)

Basic Usage

Helper Extension Methods


Redis Deep Dive

Connection Setup

Direct Redis Operations

Redis Data Structures Examples


Cache Patterns

1. Cache-Aside (Lazy Loading)

Most common pattern

2. Write-Through

Cache updated when database is updated

3. Write-Behind (Write-Back)

Cache updated immediately, database updated asynchronously

4. Refresh-Ahead

Proactively refresh cache before expiration


Cache Invalidation Strategies

1. Time-Based Expiration

2. Event-Based Invalidation

3. Tag-Based Invalidation

4. Version-Based Invalidation


Hybrid Caching (L1 + L2)

Combine in-memory (L1) and distributed (L2) cache


Response Caching

Output Caching (.NET 7+)

Response Caching Middleware (.NET 6)


Best Practices

1. Choose Appropriate Cache Duration

2. Cache Null Results

3. Use Structured Cache Keys

4. Handle Cache Failures Gracefully

5. Avoid Cache Stampede

6. Monitor Cache Performance


Performance Comparison

Memory Cache vs Distributed Cache


Common Mistakes

❌ 1. Not Setting Expiration

❌ 2. Caching Too Much

❌ 3. Not Invalidating on Updates


Quick Reference: When to Use What

Scenario
Solution

Single server

IMemoryCache

Multiple servers

IDistributedCache (Redis)

User sessions

Redis with Hash

Recent items

Redis with List

Leaderboard

Redis with Sorted Set

API responses

Output Caching

Static content

Response Caching

Fast reads, slow writes

Cache-Aside

Consistency critical

Write-Through

Best performance

Hybrid (Memory + Redis)


Guide Complete! This comprehensive caching guide covers in-memory caching, distributed caching with Redis, cache patterns, invalidation strategies, hybrid caching, and best practices for building high-performance .NET applications! 🚀

Last updated