Caching & Rate Limiting
Two cheap ways to make an API faster and sturdier: caching avoids repeating expensive work, and rate limiting stops a single client from using up all of it. Both are built into ASP.NET Core 9.
The caching toolbox
| Tool | What is cached | Where | Good for |
|---|---|---|---|
IMemoryCache |
any object you choose | this server's memory | lookups, computed values |
IDistributedCache |
byte[] |
Redis, SQL Server, … | sharing between several servers |
HybridCache (.NET 9) |
any object | memory and optional distributed cache | the recommended default for new code |
| Output caching | whole HTTP responses | server memory (or Redis) | GET endpoints whose result changes rarely |
| Response caching | HTTP headers for clients/proxies | the browser or a CDN | public, static-ish content |
Cache-aside with IMemoryCache
The classic pattern is cache-aside: look in the cache; on a miss, compute the value, store it with an expiry, and return it.
builder.Services.AddMemoryCache();
app.MapGet("/rates/{currency}", async (string currency, IMemoryCache cache, RatesClient client) =>
{
var rate = await cache.GetOrCreateAsync(quot;rate:{currency}", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return await client.FetchRateAsync(currency); // slow external call
});
return Results.Ok(new { currency, rate });
});The mechanics fit in a few lines of plain C#. A fake clock keeps the demo deterministic:
using System;
using System.Collections.Generic;
var clock = new FakeClock();
var cache = new SimpleCache(clock);
int slowCalls = 0;
decimal LoadRate(string currency)
{
slowCalls++;
return currency == "EUR" ? 0.92m : 1.00m;
}
for (int minute = 0; minute <= 6; minute += 2)
{
clock.Now = TimeSpan.FromMinutes(minute);
decimal rate = cache.GetOrCreate("rate:EUR", TimeSpan.FromMinutes(5), () => LoadRate("EUR"));
Console.WriteLine(quot;t={minute}min rate={rate} slow calls so far={slowCalls}");
}
class FakeClock { public TimeSpan Now { get; set; } }
class SimpleCache(FakeClock clock)
{
private readonly Dictionary<string, (object Value, TimeSpan ExpiresAt)> items = new();
public T GetOrCreate<T>(string key, TimeSpan ttl, Func<T> factory)
{
if (items.TryGetValue(key, out var hit) && clock.Now < hit.ExpiresAt)
return (T)hit.Value; // cache hit
T value = factory(); // miss or expired
items[key] = (value!, clock.Now + ttl);
return value;
}
}t=0min rate=0.92 slow calls so far=1
t=2min rate=0.92 slow calls so far=1
t=4min rate=0.92 slow calls so far=1
t=6min rate=0.92 slow calls so far=2
HybridCache (.NET 9)
HybridCache (package Microsoft.Extensions.Caching.Hybrid) wraps both levels in one API and fixes a subtle problem: cache stampedes. When 100 requests miss the same key at once, HybridCache runs the factory only once and lets the other 99 wait for that result.
builder.Services.AddHybridCache(options =>
{
options.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5), // distributed + local
LocalCacheExpiration = TimeSpan.FromMinutes(1) // in-memory copy
};
});
// Optional second level: builder.Services.AddStackExchangeRedisCache(...)
app.MapGet("/products/{id:int}", async (int id, HybridCache cache, ShopDb db, CancellationToken ct) =>
await cache.GetOrCreateAsync(quot;product:{id}",
async token => await db.Products.FindAsync([id], token),
tags: ["products"],
cancellationToken: ct));
app.MapPut("/products/{id:int}", async (int id, Product p, HybridCache cache, ShopDb db) =>
{
// ...save changes...
await cache.RemoveAsync(quot;product:{id}");
return Results.NoContent();
});Output caching
Output caching stores the complete response and replays it without running your endpoint at all:
builder.Services.AddOutputCache(options =>
{
options.AddBasePolicy(b => b.Expire(TimeSpan.FromSeconds(30)));
options.AddPolicy("ByPage", b => b.SetVaryByQuery("page").Tag("notes"));
});
var app = builder.Build();
app.UseOutputCache();
app.MapGet("/time", () => DateTime.UtcNow.ToString("HH:mm:ss.fff")).CacheOutput();
app.MapGet("/notes", (int page = 1) => LoadPage(page)).CacheOutput("ByPage");
app.MapPost("/notes", async (Note n, IOutputCacheStore store, CancellationToken ct) =>
{
// ...insert note...
await store.EvictByTagAsync("notes", ct); // clear every cached page
return Results.Created();
});$ curl -s localhost:5000/time; echo
$ curl -s localhost:5000/time; echo
$ sleep 30; curl -s localhost:5000/time; echo09:00:01.274
09:00:01.274
09:00:31.906
The second call returns the same timestamp: it came from the cache. By default only GET/HEAD requests answering 200 are cached, and requests from authenticated users are not cached.
Tip: Every cache needs an invalidation plan. Prefer short expirations plus explicit eviction (by key or tag) when data changes.
Rate limiting
The rate limiting middleware (in the shared framework since .NET 7) rejects requests above a limit. Four algorithms are available:
| Limiter | Rule |
|---|---|
| Fixed window | N requests per window (e.g. 5 per 10 s); the counter resets when the window ends |
| Sliding window | like fixed, but the window is split into segments for smoother limits |
| Token bucket | a bucket refills at a steady rate; each request takes a token, allowing short bursts |
| Concurrency | at most N requests in progress at the same time |
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; // default is 503!
options.AddFixedWindowLimiter("fixed", o =>
{
o.PermitLimit = 3;
o.Window = TimeSpan.FromSeconds(10);
o.QueueLimit = 0;
});
// One bucket per client IP
options.AddPolicy("per-ip", http => RateLimitPartition.GetTokenBucketLimiter(
http.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new TokenBucketRateLimiterOptions
{
TokenLimit = 20, TokensPerPeriod = 10,
ReplenishmentPeriod = TimeSpan.FromSeconds(1),
}));
});
var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/search", (string q) => new { q, hits = 0 }).RequireRateLimiting("fixed");$ for i in 1 2 3 4 5; do curl -s -o /dev/null -w "%{http_code} " "localhost:5000/search?q=asp"; done; echo200 200 200 429 429
A fixed-window limiter with a fake clock, in plain C#:
using System;
var limiter = new FixedWindowLimiter(permitLimit: 3, window: TimeSpan.FromSeconds(10));
double[] requestTimes = { 0.0, 1.5, 2.0, 4.0, 9.9, 10.0, 10.5 };
foreach (double t in requestTimes)
{
bool ok = limiter.TryAcquire(TimeSpan.FromSeconds(t));
Console.WriteLine(quot;t={t,4:F1}s -> {(ok ? "200 OK" : "429 Too Many Requests")}");
}
class FixedWindowLimiter(int permitLimit, TimeSpan window)
{
private TimeSpan windowStart = TimeSpan.Zero;
private int used;
public bool TryAcquire(TimeSpan now)
{
if (now - windowStart >= window)
{
windowStart = now - TimeSpan.FromTicks((now - windowStart).Ticks % window.Ticks);
used = 0; // a new window begins: counter resets
}
if (used >= permitLimit) return false;
used++;
return true;
}
}t= 0.0s -> 200 OK
t= 1.5s -> 200 OK
t= 2.0s -> 200 OK
t= 4.0s -> 429 Too Many Requests
t= 9.9s -> 429 Too Many Requests
t=10.0s -> 200 OK
t=10.5s -> 200 OK
Note: If your app runs behind a reverse proxy, every request appears to come from the proxy's IP. Configure forwarded headers first, or the "per-IP" limit becomes one global limit.
Test yourself
What does HybridCache do when many requests miss the same key at the same moment?
- Runs the factory once and shares the result with the waiting callers
- Runs the factory once per request
- Returns 503 to all but the first
- Throws a
CacheStampedeException
Without configuration, which status code does the rate limiting middleware use for rejected requests?
- 429
- 403
- 503
- 400
Which tool replays a complete HTTP response without running the endpoint again?
- IMemoryCache
- Output caching
- IDistributedCache
- A token bucket limiter