|
| 1 | +# Caching Guide |
| 2 | + |
| 3 | +This guide explains how to configure and use caching in the BookStore API, specifically focusing on the hybrid caching strategy integrated with .NET Aspire and localization. |
| 4 | + |
| 5 | +## Overview |
| 6 | + |
| 7 | +The BookStore API uses **Hybrid Caching** (`HybridCache`), enriched by **.NET Aspire** for seamless distributed cache orchestration. |
| 8 | + |
| 9 | +**Components:** |
| 10 | +- **L1 Cache (In-Memory)**: Local, fast access. |
| 11 | +- **L2 Cache (Distributed)**: Redis, orchestrated by Aspire. |
| 12 | +- **Stampede Protection**: Built-in to coalescing requests. |
| 13 | +- **Localization Awareness**: Automatically scopes cache keys to the user's culture. |
| 14 | + |
| 15 | +## Configuration |
| 16 | + |
| 17 | +### Aspire Orchestration |
| 18 | + |
| 19 | +The caching infrastructure is automatically wired up by .NET Aspire. |
| 20 | + |
| 21 | +1. **AppHost**: Declares the Redis resource. |
| 22 | + ```csharp |
| 23 | + var cache = builder.AddRedis("cache"); |
| 24 | + builder.AddProject<Projects.BookStore_ApiService>("apiservice") |
| 25 | + .WithReference(cache); |
| 26 | + ``` |
| 27 | + |
| 28 | +2. **Service Defaults**: Redis configuration is injected via service discovery. The API service adds the distributed cache: |
| 29 | + ```csharp |
| 30 | + builder.Services.AddRedisDistributedCache("cache"); |
| 31 | + builder.Services.AddHybridCache(); |
| 32 | + ``` |
| 33 | + |
| 34 | +## Localized Caching |
| 35 | + |
| 36 | +**Challenge**: Content (e.g., book descriptions) changes based on the user's language (`Accept-Language`). If you cache "book-123" without considering culture, a Portuguese user might receive English content cached by a previous request. |
| 37 | + |
| 38 | +**Solution**: Use the `GetOrCreateLocalizedAsync` extension method. |
| 39 | + |
| 40 | +### Usage Pattern |
| 41 | + |
| 42 | +Instead of `GetOrCreateAsync`, use `GetOrCreateLocalizedAsync`. This method automatically appends the current UI culture (e.g., `|en-US`, `|pt-BR`) to the cache key. |
| 43 | + |
| 44 | +```csharp |
| 45 | +public class BookService(HybridCache cache) |
| 46 | +{ |
| 47 | + public async Task<Book?> GetBookAsync(string id, CancellationToken token = default) |
| 48 | + { |
| 49 | + // Key becomes "book-{id}|{culture}" automatically |
| 50 | + return await cache.GetOrCreateLocalizedAsync( |
| 51 | + key: $"book-{id}", |
| 52 | + factory: async cancel => await RetrieveBookFromDatabaseAsync(id, cancel), |
| 53 | + token: token |
| 54 | + ); |
| 55 | + } |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +### Invalidation |
| 60 | + |
| 61 | +When invalidating localized content, ensure you remove the localized entry or use tags. |
| 62 | + |
| 63 | +**Remove specific localized entry**: |
| 64 | +```csharp |
| 65 | +// Removes "book-{id}|{current_culture}" |
| 66 | +await cache.RemoveLocalizedAsync($"book-{id}"); |
| 67 | +``` |
| 68 | + |
| 69 | +**Remove by Tag (Recommended)**: |
| 70 | +Tags are culture-agnostic. Tagging all variations of a book allows you to clear all languages at once. |
| 71 | + |
| 72 | +```csharp |
| 73 | +await cache.GetOrCreateLocalizedAsync( |
| 74 | + $"book-{id}", |
| 75 | + factory, |
| 76 | + tags: [$"book:{id}"] |
| 77 | +); |
| 78 | + |
| 79 | +// Clears English, Portuguese, Spanish, etc. for this book |
| 80 | +await cache.RemoveByTagAsync($"book:{id}"); |
| 81 | +``` |
| 82 | + |
| 83 | +## Best Practices |
| 84 | + |
| 85 | +1. **Use Tags for Entities**: Always tag cache entries with the entity ID (e.g., `book:123`). This makes invalidation much easier than tracking every culture-variant key. |
| 86 | +2. **Use Localized Methods**: Prefer `GetOrCreateLocalizedAsync` for any content that *might* be localized, even if it isn't yet. |
| 87 | +3. **Environment Awareness**: Aspire handles the connection strings. In development, it spins up a Redis container. In production, it points to your managed Redis instance. |
0 commit comments