Logo Caching Strategies

Caching Strategies

Cộng đồng
wshaddix
caching-strategies

Comprehensive caching patterns for ASP.NET Core Razor Pages applications. Covers output caching, response caching, memory caching, distributed caching with Redis, cache invalidation strategies, and HybridCache (.NET 9+). Use when implementing caching in Razor Pages applications, choosing between memory and distributed caching, or optimizing application performance with caching.

Add to TypingMind

Tổng quan

Nhà phát hànhwshaddix
Kho mãdotnet-skills
Tên kỹ năngcaching-strategies
Sao
79
Bản fork
13
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI dùng hướng dẫn viết bằng Markdown thay vì mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Hướng dẫn có đủ mọi thứ cần thiết

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được wshaddix công bố trên GitHub. Hãy đọc các tệp nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Caching Strategies trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL của thư mục kỹ năng được hiển thị bên dưới rồi xác nhận.
    https://github.com/wshaddix/dotnet-skills/tree/master/skills/caching-strategies
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wshaddix/dotnet-skills.git /tmp/dotnet-skills
mkdir -p .claude/skills
cp -r /tmp/dotnet-skills/skills/caching-strategies .claude/skills/caching-strategies
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Caching Strategies trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự nạp Caching Strategies ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên bạn có thể dùng Caching Strategies với cả những mô hình khác ngoài mô hình ban đầu. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên khi kỹ năng chưa được dùng, bạn không tốn token cho phần hướng dẫn.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

You are a senior ASP.NET Core architect specializing in caching strategies. When implementing caching in Razor Pages applications, apply these patterns to maximize performance while maintaining correctness. Target .NET 8+ with modern features and nullable reference types enabled.

Rationale

Caching is one of the most effective ways to improve application performance, but improper implementation leads to stale data, cache stampedes, and complexity. These patterns provide a hierarchy of caching solutions from simple to distributed, with clear guidance on when to use each.

Caching Hierarchy

StrategyScopeUse CaseLatency
Output CachingServer-wideFull page responsesLow
Response CachingClient + ProxyStatic pages, assetsLow
Memory CacheSingle instanceShort-lived, expensive dataVery Low
Distributed CacheMulti-instanceShared data across serversLow-Medium
HybridCache (.NET 9+)Multi-instanceBest of memory + distributedVery Low

Pattern 1: Output Caching (Full Page)

Use for pages that don't change often and don't contain user-specific data.

Configuration

csharp
// Program.cs
builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(builder =>
        builder.Expire(TimeSpan.FromSeconds(10)));
    options.AddPolicy("LongCache", builder =>
        builder.Expire(TimeSpan.FromMinutes(5)));
    options.AddPolicy("AuthenticatedCache", builder =>
        builder.Expire(TimeSpan.FromMinutes(1))
               .Tag("user-specific"));
});

// Add middleware (order matters!)
var app = builder.Build();
app.UseOutputCache(); // After UseRouting, before endpoints

Page-Level Usage

csharp
// Cache entire page for 60 seconds
[OutputCache(Duration = 60)]
public class IndexModel : PageModel { }

// Named policy with tags for invalidation
[OutputCache(PolicyName = "LongCache")]
public class PrivacyModel : PageModel { }

// Vary by query string parameter
[OutputCache(Duration = 300, VaryByQueryKeys = new[] { "page", "category" })]
public class BlogListModel : PageModel { }

// Vary by header (e.g., for mobile vs desktop)
[OutputCache(Duration = 300, VaryByHeaderNames = new[] { "User-Agent" })]
public class ProductListModel : PageModel { }

// Different cache for authenticated users
[OutputCache(PolicyName = "AuthenticatedCache")]
[Authorize]
public class DashboardModel : PageModel { }

Cache Invalidation

csharp
// Tag-based invalidation
public class BlogAdminModel(IOutputCacheStore cache) : PageModel
{
    public async Task<IActionResult> OnPostPublishAsync()
    {
        // Invalidate all pages tagged with "blog"
        await cache.EvictByTagAsync("blog", CancellationToken.None);
        
        return RedirectToPage("/Blog/List");
    }
}

Pattern 2: Response Caching (Client-Side)

Use for static assets and pages that can be cached by browsers and CDNs.

csharp
// Program.cs
builder.Services.AddResponseCaching();

var app = builder.Build();
app.UseResponseCaching(); // Before UseOutputCache
csharp
// Page-level cache control
[ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Any)]
public class StaticContentModel : PageModel { }

// No caching (for error pages, authenticated content)
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel { }

// Private caching (client only, no CDN)
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Client)]
public class UserProfileModel : PageModel { }

Pattern 3: Memory Caching

Use for expensive computations and database queries within a single server instance.

Configuration

csharp
// Program.cs
builder.Services.AddMemoryCache(options =>
{
    options.SizeLimit = 100_000_000; // 100MB total cache size
    options.CompactionPercentage = 0.25; // Remove 25% when limit reached
    options.ExpirationScanFrequency = TimeSpan.FromMinutes(5);
});

Usage in Handlers/PageModels

csharp
public class ProductService(IMemoryCache cache, AppDbContext db)
{
    private static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(10);
    
    public async Task<Product?> GetProductAsync(Guid id)
    {
        var cacheKey = $"product:{id}";
        
        if (cache.TryGetValue(cacheKey, out Product? product))
        {
            return product;
        }
        
        product = await db.Products.FindAsync(id);
        
        if (product != null)
        {
            var cacheOptions = new MemoryCacheEntryOptions()
                .SetAbsoluteExpiration(CacheDuration)
                .SetSize(1) // For size-limited cache
                .RegisterPostEvictionCallback((key, value, reason, state) =>
                {
                    // Log cache eviction
                });
                
            cache.Set(cacheKey, product, cacheOptions);
        }
        
        return product;
    }
    
    public void InvalidateProduct(Guid id)
    {
        cache.Remove($"product:{id}");
    }
}

Cache-Aside Pattern with GetOrCreateAsync

csharp
public async Task<List<Category>> GetCategoriesAsync()
{
    return await cache.GetOrCreateAsync(
        "categories:all",
        async entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
            entry.SetSize(1);
            
            return await db.Categories
                .AsNoTracking()
                .ToListAsync();
        });
}

Pattern 4: Distributed Caching (Redis)

Use for multi-instance deployments where cache must be shared.

Configuration

csharp
// Program.cs
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "MyApp:"; // Prefix for all keys
});

// Or using Aspire
builder.AddRedis("cache");

Usage

csharp
public class DistributedProductService(IDistributedCache cache, AppDbContext db)
{
    private static readonly TimeSpan CacheDuration = TimeSpan.FromMinutes(10);
    
    public async Task<Product?> GetProductAsync(Guid id)
    {
        var cacheKey = $"product:{id}";
        
        // Try to get from distributed cache
        var cached = await cache.GetStringAsync(cacheKey);
        if (cached != null)
        {
            return JsonSerializer.Deserialize<Product>(cached);
        }
        
        // Fetch from database
        var product = await db.Products.FindAsync(id);
        
        if (product != null)
        {
            // Serialize and store
            var serialized = JsonSerializer.Serialize(product);
            var options = new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = CacheDuration
            };
            
            await cache.SetStringAsync(cacheKey, serialized, options);
        }
        
        return product;
    }
}

Sliding Expiration Pattern

csharp
public async Task<UserSession?> GetSessionAsync(string sessionId)
{
    var options = new DistributedCacheEntryOptions
    {
        SlidingExpiration = TimeSpan.FromMinutes(20), // Extend on access
        AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(8) // Max lifetime
    };
    
    var session = await cache.GetStringAsync($"session:{sessionId}");
    if (session == null) return null;
    
    // Touch the cache to extend sliding expiration
    await cache.RefreshAsync($"session:{sessionId}");
    
    return JsonSerializer.Deserialize<UserSession>(session);
}

Pattern 5: HybridCache (.NET 9+)

Recommended for .NET 9+: Provides both local memory cache (fast) and distributed cache (shared) with automatic synchronization.

Configuration

csharp
// Program.cs
builder.Services.AddHybridCache(options =>
{
    options.DefaultLocalCacheExpiration = TimeSpan.FromMinutes(5);
    options.DefaultExpiration = TimeSpan.FromMinutes(30);
    options.LocalCacheMaximumSizeBytes = 50_000_000; // 50MB
});

Usage

csharp
public class HybridProductService(IHybridCache cache, AppDbContext db)
{
    public async Task<Product?> GetProductAsync(Guid id, CancellationToken ct = default)
    {
        return await cache.GetOrCreateAsync(
            $"product:{id}",
            async cancel => await db.Products.FindAsync(new object[] { id }, cancel),
            new HybridCacheEntryOptions
            {
                LocalCacheExpiration = TimeSpan.FromMinutes(5),
                Expiration = TimeSpan.FromMinutes(30)
            },
            tags: new[] { "products" },
            cancellationToken: ct);
    }
    
    public async Task RemoveProductAsync(Guid id)
    {
        await cache.RemoveByTagAsync("products");
    }
}

Cache Invalidation Strategies

1. Tag-Based Invalidation

csharp
// Add tags during cache entry creation
await cache.SetAsync(key, data, options, tags: new[] { "users", $"user:{userId}" });

// Invalidate by tag
await cache.RemoveByTagAsync("users"); // Removes all user entries

2. Event-Driven Invalidation

csharp
public class ProductUpdatedHandler(IDistributedCache cache) : INotificationHandler<ProductUpdated>
{
    public async Task Handle(ProductUpdated notification, CancellationToken ct)
    {
        await cache.RemoveAsync($"product:{notification.ProductId}");
        await cache.RemoveByTagAsync("products:list");
    }
}

3. Time-Based Invalidation

csharp
// Different expiration strategies for different data freshness requirements
public class CachePolicies
{
    public static readonly TimeSpan UserData = TimeSpan.FromMinutes(5);
    public static readonly TimeSpan ProductData = TimeSpan.FromHours(1);
    public static readonly TimeSpan ReferenceData = TimeSpan.FromDays(1);
}

Anti-Patterns

Cache Stampede

csharp
// ❌ BAD: Multiple requests hit database simultaneously when cache expires
public async Task<Product> GetProduct(Guid id)
{
    if (!cache.TryGetValue(id, out var product))
    {
        product = await db.Products.FindAsync(id); // All requests hit here
        cache.Set(id, product);
    }
    return product!;
}

// ✅ GOOD: Use locking to prevent stampede
public async Task<Product?> GetProductAsync(Guid id)
{
    return await cache.GetOrCreateAsync(
        $"product:{id}",
        async _ => await db.Products.FindAsync(id));
}

Storing Large Objects

csharp
// ❌ BAD: Storing entire collections
var allProducts = await db.Products.ToListAsync();
cache.Set("products:all", allProducts);

// ✅ GOOD: Store individual items, paginate
var products = await db.Products
    .Skip(offset)
    .Take(50)
    .ToListAsync();

Inconsistent Cache Keys

csharp
// ❌ BAD: Inconsistent key generation
var key1 = $"user-{userId}";
var key2 = $"user:{userId}";
var key3 = $"User:{userId}";

// ✅ GOOD: Centralized key helpers
public static class CacheKeys
{
    public static string User(Guid id) => $"user:{id}";
    public static string UserList(string? filter = null) => 
        filter == null ? "users:all" : $"users:filter:{filter}";
}

Razor Pages Specific Patterns

Partial Page Caching

csharp
// Cache partial view output
public class ProductCardViewComponent(IDistributedCache cache) : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync(Guid productId)
    {
        var cacheKey = $"product-card:{productId}";
        
        var html = await cache.GetStringAsync(cacheKey);
        if (html != null)
        {
            return Content(html);
        }
        
        var product = await GetProductAsync(productId);
        var result = View(product);
        
        // Render and cache the HTML
        using var writer = new StringWriter();
        await result.RenderViewComponentAsync(writer);
        html = writer.ToString();
        
        await cache.SetStringAsync(cacheKey, html, 
            new DistributedCacheEntryOptions 
            { 
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) 
            });
        
        return Content(html);
    }
}

Cache Per User

csharp
[OutputCache(Duration = 60, VaryByCookie = new[] { ".AspNetCore.Identity.Application" })]
public class UserDashboardModel : PageModel { }

// Or vary by custom header
[OutputCache(Duration = 60, VaryByHeaderNames = new[] { "X-User-Tier" })]
public class PricingModel : PageModel { }

References

Câu hỏi thường gặp

Kỹ năng AI Caching Strategies làm được gì?

Comprehensive caching patterns for ASP.NET Core Razor Pages applications. Covers output caching, response caching, memory caching, distributed caching with Redis, cache invalidation strategies, and HybridCache (.NET 9+). Use when implementing caching in Razor Pages applications, choosing between memory and distributed caching, or optimizing application performance with caching.

Vì sao nên dùng Caching Strategies trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Caching Strategies là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Caching Strategies trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/wshaddix/dotnet-skills/tree/master/skills/caching-strategies. TypingMind đọc tệp SKILL.md rồi cài đặt kỹ năng để bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Caching Strategies?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Có thể dùng Caching Strategies với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Caching Strategies với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Caching Strategies có miễn phí không?

Kỹ năng này được wshaddix phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp các công cụ mới mà mô hình có thể gọi. Khi mô hình gọi một công cụ, mã của công cụ đó chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và những tiêu chí mà kết quả cần đáp ứng. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇