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.
What this skill does
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
| Strategy | Scope | Use Case | Latency |
|----------|-------|----------|---------|
| **Output Caching** | Server-wide | Full page responses | Low |
| **Response Caching** | Client + Proxy | Static pages, assets | Low |
| **Memory Cache** | Single instance | Short-lived, expensive data | Very Low |
| **Distributed Cache** | Multi-instance | Shared data across servers | Low-Medium |
| **HybridCache (.NET 9+)** | Multi-instance | Best of memory + distributed | Very 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.DefRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.