caching — скилл для Claude Code: кеширование .NET
Настраивает кеширование в приложениях .NET 10: HybridCache, кеш ответов и распределённый кеш. Нужен при снижении нагрузки на базу данных и настройке инвалидации.
npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a claude-codeЧто делает caching
Скилл подсказывает, как кешировать чтения в .NET 10 через HybridCache, который объединяет локальный кеш L1 и распределённый уровень L2. Он также рассматривает защиту от одновременного заполнения кеша, явные сроки жизни записей и ключи с идентификатором пользователя для персональных данных.
Для целых HTTP-ответов предлагается middleware output caching: политики задают срок жизни, вариант по параметру маршрута и тег, по которому можно очистить ответы после изменения данных. Операции POST, PUT и DELETE кешировать не следует; после мутаций запись удаляют через cache.RemoveAsync() или сбрасывают по тегу.
Для нового кода скилл прямо советует HybridCache, потому что ручной cache-aside через IDistributedCache требует сериализации и не даёт слоёв L1/L2 или встроенной защиты от stampede. Redis подключается как L2 для распределённого развёртывания.
Какие задачи решает
- закешировать результат чтения через
HybridCache - удалить запись кеша после обновления данных
- настроить кеширование полного HTTP-ответа
- разделить кеш персональных данных по идентификатору пользователя
- подключить Redis как распределённый уровень L2
Примеры запросов агенту
- Настрой
HybridCacheдля чтения товара из базы данных и очистку кеша после обновления. - Добавь output caching для списка товаров и сбрасывай его по тегу после
PUT. - Проверь cache-aside с
IDistributedCacheи замени его наHybridCache, где это уместно.
Как установить caching
1Через Skills CLI (Vercel)
npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a claude-code2Вручную: положить файлы
~/.claude/skills/caching/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/caching/
1Через Skills CLI (Vercel)
npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a codex2Вручную: положить файлы
.agents/skills/caching/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a cursor2Вручную: положить файлы
.cursor/skills/caching/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install codewithmukesh/dotnet-claude-kit caching2Вручную: положить файлы
.github/skills/caching/SKILL.md1Через Skills CLI (Vercel)
npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a gemini-cli2Командой платформы
gemini skills install https://github.com/codewithmukesh/dotnet-claude-kit --path skills/cachingВручную: положить файлы
.devin/skills/caching/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о caching
Как установить caching в Claude Code?
Выполните npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a claude-code, затем повторите npx skills add codewithmukesh/dotnet-claude-kit --skill caching -a claude-code. Файл скилла размещается в ~/.claude/skills/caching/SKILL.md.
Что делает скилл caching?
Он даёт рекомендации по кешированию для приложений .NET 10: HybridCache, output caching, response caching и распределённые схемы. Также описывает инвалидацию и сроки жизни записей.
Почему для нового кода предлагается HybridCache?
HybridCache объединяет локальный L1 и распределённый L2-кеш, а также содержит защиту от stampede. Ручной cache-aside через IDistributedCache требует сериализации и не даёт такой слоистой схемы.
Исходный текст
SKILL.md · MIT
---
name: caching
description: >
Caching strategies for .NET 10 applications. Covers HybridCache (the default),
output caching, response caching, and distributed cache patterns.
Load this skill when implementing caching, optimizing read performance, reducing
database load, or when the user mentions "cache", "HybridCache", "Redis",
"output cache", "response cache", "distributed cache", "IMemoryCache",
"cache invalidation", "stampede protection", or "cache-aside".
---
# Caching
## Core Principles
1. **HybridCache is the default** — .NET 9+ introduced `HybridCache` as the unified caching abstraction. It combines in-memory (L1) and distributed (L2) caching with stampede protection. See ADR-004.
2. **Cache reads, not writes** — Cache GET operations. Invalidate on mutations. Never cache POST/PUT/DELETE responses.
3. **Output caching for entire responses** — When the full HTTP response can be cached (public APIs, static data), use output caching middleware.
4. **Set explicit TTLs** — Every cached item needs an expiration. No unbounded caches.
## Patterns
### HybridCache (Recommended Default)
```csharp
// Program.cs
builder.Services.AddHybridCache(options =>
{
options.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5),
LocalCacheExpiration = TimeSpan.FromMinutes(2)
};
});
// Optional: Add Redis as the L2 distributed cache
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("Redis");
});
```
```csharp
// Usage in a handler
public class GetProduct
{
public record Query(Guid Id);
public record Response(Guid Id, string Name, decimal Price);
internal class Handler(AppDbContext db, HybridCache cache)
{
public async Task<Response?> Handle(Query query, CancellationToken ct)
{
return await cache.GetOrCreateAsync(
$"products:{query.Id}",
async token => await db.Products
.Where(p => p.Id == query.Id)
.Select(p => new Response(p.Id, p.Name, p.Price))
.FirstOrDefaultAsync(token),
new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(10)
},
cancellationToken: ct);
}
}
}
```
### Cache Invalidation
```csharp
// Invalidate on mutation
public class UpdateProduct
{
internal class Handler(AppDbContext db, HybridCache cache)
{
public async Task<Result> Handle(Command command, CancellationToken ct)
{
var product = await db.Products.FindAsync([command.Id], ct);
if (product is null) return Result.Failure("Product not found");
product.Update(command.Name, command.Price);
await db.SaveChangesAsync(ct);
// Invalidate the cached entry
await cache.RemoveAsync($"products:{command.Id}", ct);
return Result.Success();
}
}
}
```
### Output Caching (Full Response Caching)
```csharp
// Program.cs
builder.Services.AddOutputCache(options =>
{
options.AddBasePolicy(b => b.NoCache()); // Don't cache by default
options.AddPolicy("ProductList", b => b
.Expire(TimeSpan.FromMinutes(5))
.Tag("products"));
options.AddPolicy("ProductById", b => b
.Expire(TimeSpan.FromMinutes(10))
.SetVaryByRouteValue("id")
.Tag("products"));
});
app.UseOutputCache();
// Apply to endpoints
group.MapGet("/", ListProducts).CacheOutput("ProductList");
group.MapGet("/{id:guid}", GetProduct).CacheOutput("ProductById");
// Invalidate by tag on mutations
group.MapPut("/{id:guid}", async (Guid id, UpdateProductRequest request,
IOutputCacheStore store, CancellationToken ct) =>
{
// ... update logic ...
await store.EvictByTagAsync("products", ct);
return TypedResults.NoContent();
});
```
### Cache-Aside Pattern (Legacy)
> **Prefer HybridCache** for all new code. Manual `IDistributedCache` cache-aside lacks stampede
> protection, requires manual serialization, and has no L1/L2 layering. Use only when
> integrating with existing code that already uses `IDistributedCache` directly.
## Anti-patterns
### Don't Cache Without Expiration
```csharp
// BAD — cache lives forever, stale data guaranteed
await cache.SetStringAsync(key, value);
// GOOD — always set TTL
await cache.SetStringAsync(key, value, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
```
### Don't Cache Mutable User-Specific Data
```csharp
// BAD — caching user's cart with a global key
await cache.GetOrCreateAsync("shopping-cart", ...);
// GOOD — include user ID in key
await cache.GetOrCreateAsync($"shopping-cart:{userId}", ...);
```
### Don't Build Your Own Stampede Protection
```csharp
// BAD — manual lock to prevent cache stampede
private static readonly SemaphoreSlim Lock = new(1, 1);
await Lock.WaitAsync();
try { /* check cache, populate if missing */ }
finally { Lock.Release(); }
// GOOD — HybridCache has built-in stampede protection
await hybridCache.GetOrCreateAsync(key, factory);
```
## Decision Guide
| Scenario | Recommendation |
|----------|---------------|
| General data caching | HybridCache (`GetOrCreateAsync`) |
| Full HTTP response | Output caching with `.CacheOutput()` |
| Frequently read, rarely written | HybridCache with longer TTL |
| User-specific data | HybridCache with user-scoped key |
| Cache invalidation on write | `cache.RemoveAsync()` or output cache tags |
| Distributed deployment | HybridCache + Redis L2 backend |
| Single-server deployment | HybridCache with in-memory only |
© codewithmukesh · MIT · codewithmukesh/dotnet-claude-kit