Caching in Depth
Caching in Depth, Part 2: Frontend or Backend? Every Layer, with Examples You Can Use
October 21, 2026 · 40 min read
Caching, Software Architecture, Performance, Web Development, C#, Python, TypeScript, Redis
This is Part 2 of Caching in Depth. Part 1 covered the strategies: cache-aside, read-through, the write patterns, refresh-ahead, eviction, invalidation and stampedes. This part answers the question that comes right after: do we cache on the frontend or the backend?
The short answer is both, but not for the same data. A request passes through several places that can keep a copy of the answer. Each one is closer to the user than the next, so it's faster, but it's also harder for you to reach when the data changes. A copy in a user's browser is free to read and almost impossible to take back. A copy in your Redis is a network hop away, but you can delete it in one call.
So the real question is not "frontend or backend". It's "how close to the user can this data live, given how often it changes and who is allowed to see it?"
This post walks the request path from the user outward, one layer at a time:
| # | Layer | Lives in | You control invalidation? |
|---|---|---|---|
| 1 | Browser HTTP cache | The user's browser | Only through headers you sent earlier |
| 2 | CDN / edge cache | Your CDN's edge servers | Yes: purge by URL or tag |
| 3 | Service worker | The user's browser, your code | Only when your code next runs there |
| 4 | Client data cache | Your app's JavaScript memory | Yes, inside that tab |
| 5 | UI memoization and local storage | The component or device | Yes, inside that app |
| 6 | In-process cache | Each server instance's memory | Yes, but per instance |
| 7 | Distributed cache | Redis or similar | Yes, one place for all instances |
| 8 | Output cache | Your web server | Yes: evict by tag |
| 9 | Database caches | The database engine | Mostly automatic |
Every runnable snippet below was run, and the output shown is the real output. Snippets that need a browser or a Redis server are labelled not run.
1. Browser HTTP cache
What it caches. Whole HTTP responses: scripts, styles, images, fonts, and API responses if you let it. It's the fastest cache there is, because a hit never leaves the user's machine.
How you control it. Only with response headers. The browser does what Cache-Control tells it:
| Directive | Meaning |
|---|---|
max-age=600 | Reuse this for 600 seconds without asking the server |
no-cache | You may store it, but check with the server before every reuse |
no-store | Don't store it at all, anywhere |
private | Only the user's browser may store it, not a CDN or proxy |
public | Shared caches (CDNs, proxies) may store it too |
immutable | This URL's content will never change, so don't even revalidate |
stale-while-revalidate=30 | After it expires, you may serve it for 30 more seconds while you fetch a fresh copy in the background |
The one people mix up: no-cache does not mean "don't cache". It means "always revalidate". no-store is the one that means "never keep this".
Revalidation: ETag and 304. When a cached response is stale (or marked no-cache), the browser doesn't have to download it again. It sends the ETag it got last time in an If-None-Match header. If the content hasn't changed, the server answers 304 Not Modified with no body. The browser keeps using its copy. You still pay a round trip, but not the download. Last-Modified and If-Modified-Since do the same thing with a timestamp, which is coarser (one-second resolution) but cheap to compute.
Hashed filenames. For static assets, the best trick is to put a content hash in the filename (app.3f9a1c.js) and cache it for a year with immutable. A new build produces a new filename, and the HTML points to it. You never need to invalidate the old file; nobody asks for it anymore. Every modern bundler does this for you, and Next.js does it for everything under /_next/static. The HTML page itself must not be cached long, because it's the thing that points to the new filenames.
When to use it. Static assets, always. Public API responses that change slowly, with a short max-age or with no-cache plus an ETag.
When not to. Anything you might need to take back fast. Once a browser has a response with max-age=86400, you can't recall it for a day. Responses with personal or sensitive data should be private at least, and no-store if they shouldn't sit on a shared computer's disk.
Python: a server that sends ETags and 304s
Standard library only. The server and the client run in the same script.
import hashlib, json, threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.request import Request, urlopen
from urllib.error import HTTPError
PRODUCTS = [{"id": 1, "name": "Desk lamp", "price": 39.0}]
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/api/products":
body = json.dumps(PRODUCTS).encode()
etag = '"' + hashlib.sha256(body).hexdigest()[:16] + '"'
# no-cache = "you may store it, but check with me before reusing it"
headers = {"Cache-Control": "no-cache", "ETag": etag}
if self.headers.get("If-None-Match") == etag:
self.send_response(304) # not modified: no body sent
for k, v in headers.items(): self.send_header(k, v)
self.end_headers()
return
self.send_response(200)
for k, v in headers.items(): self.send_header(k, v)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif self.path.startswith("/static/app.3f9a1c.js"):
# hashed filename: the content can never change under this URL
body = b"console.log('hi')"
self.send_response(200)
self.send_header("Cache-Control", "public, max-age=31536000, immutable")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
else:
self.send_error(404)
def log_message(self, *args): pass # keep the demo output clean
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) # port 0 = any free port
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"
def get(path, etag=None):
req = Request(base + path, headers={"If-None-Match": etag} if etag else {})
try:
with urlopen(req) as r:
return r.status, r.headers, r.read()
except HTTPError as e: # urllib raises on 304
return e.code, e.headers, b""
status, h, body = get("/api/products")
print(status, h["Cache-Control"], h["ETag"], f"{len(body)} bytes")
status, h, body = get("/api/products", etag=h["ETag"])
print(status, h["Cache-Control"], h["ETag"], f"{len(body)} bytes")
PRODUCTS[0]["price"] = 35.0 # data changes, so the ETag changes
status, h2, body = get("/api/products", etag=h["ETag"])
print(status, h2["ETag"], f"{len(body)} bytes")
status, h, _ = get("/static/app.3f9a1c.js")
print(status, h["Cache-Control"])
server.shutdown()
200 no-cache "a730499e7a8d5848" 47 bytes
304 no-cache "a730499e7a8d5848" 0 bytes
200 "afdad15501cee73f" 47 bytes
200 public, max-age=31536000, immutable
The second request sends the ETag back and gets a 304 with zero bytes. After the price changes, the same old ETag no longer matches, so the server sends a full 200 with a new ETag. In FastAPI or Flask the logic is the same: compute the tag, compare it to If-None-Match, return 304 or set the headers on the response.
C#: the same in ASP.NET Core
A .NET 10 file-based app. It starts a real Kestrel server on a free port, calls it with HttpClient, and stops.
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
var app = builder.Build();
app.Urls.Add("http://127.0.0.1:0"); // any free port
var products = new List<Product> { new(1, "Desk lamp", 39.0m) };
app.MapGet("/api/products", (HttpContext ctx) =>
{
var json = JsonSerializer.Serialize(products);
var etag = $"\"{Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(json)))[..16].ToLowerInvariant()}\"";
ctx.Response.Headers.CacheControl = "no-cache"; // store, but revalidate before reuse
ctx.Response.Headers.ETag = etag;
if (ctx.Request.Headers.IfNoneMatch == etag)
return Results.StatusCode(StatusCodes.Status304NotModified);
return Results.Text(json, "application/json");
});
// Hashed static assets: cache "forever", because a new build gets a new filename.
app.MapGet("/static/app.3f9a1c.js", (HttpContext ctx) =>
{
ctx.Response.Headers.CacheControl = "public, max-age=31536000, immutable";
return Results.Text("console.log('hi')", "text/javascript");
});
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(app.Urls.First()) };
async Task<(int Status, string? ETag, int Bytes, string CacheControl)> Get(string path, string? etag = null)
{
var req = new HttpRequestMessage(HttpMethod.Get, path);
if (etag is not null) req.Headers.IfNoneMatch.Add(EntityTagHeaderValue.Parse(etag));
var res = await http.SendAsync(req);
var body = await res.Content.ReadAsByteArrayAsync();
return ((int)res.StatusCode, res.Headers.ETag?.Tag, body.Length, res.Headers.CacheControl?.ToString() ?? "");
}
var first = await Get("/api/products");
Console.WriteLine(first);
Console.WriteLine(await Get("/api/products", first.ETag));
products[0] = products[0] with { Price = 35.0m }; // data changes, so the ETag changes
Console.WriteLine(await Get("/api/products", first.ETag));
Console.WriteLine(await Get("/static/app.3f9a1c.js"));
await app.StopAsync();
record Product(int Id, string Name, decimal Price);
(200, "ced0420364146f6b", 42, no-cache)
(304, "ced0420364146f6b", 0, no-cache)
(200, "065aebd5a8c70c3e", 42, no-cache)
(200, , 17, public, max-age=31536000, immutable)
For real static files you don't write this by hand. ASP.NET Core's static file middleware sets ETag and Last-Modified for you, and MapStaticAssets (from .NET 9) fingerprints files at build time and serves them with long cache lifetimes. Write it by hand for API responses.
Invalidation story. You can't invalidate a browser cache from the server. You choose up front: a short max-age, no-cache with an ETag, or a hashed URL that you simply stop linking to.
2. CDN / edge cache
What it caches. The same HTTP responses, but on servers near your users and shared between all of them. One user's request fills the cache, and the next thousand users in that region get the copy.
The headers that matter.
s-maxagesets the lifetime for shared caches only, and overridesmax-agethere. That lets you say "browsers keep it 60 seconds, the CDN keeps it 10 minutes", which works well because you can purge the CDN but not browsers.CDN-Cache-Control(RFC 9213) is a header only CDNs read, if you want to separate the two completely. Support varies by provider, so check yours.Varytells caches which request headers change the response.Vary: Accept-Encodingis normal.Vary: CookieorVary: Authorizationusually means the CDN can't usefully cache the response at all, because every user gets their own entry.
The cache key. By default a CDN keys on the URL, including the query string. That's a source of bugs in both directions. Tracking parameters like ?utm_source=... split one page into many cache entries, and a CDN rule that ignores the query string can serve page 1 to someone who asked for page 2. Decide on purpose which query parameters and headers are part of the key.
Purging. You can purge by URL, by prefix, or (on most CDNs) by tag: you label responses with a header, then purge everything with that label in one call. Fastly calls these surrogate keys; Cloudflare and others call them cache tags. Tag purging is the one you want, because "product 42 changed" touches the product page, three category pages and the search results, and you don't want to track those URLs yourself.
What never goes to the edge. Anything personalized or behind a login: account pages, carts, dashboards, anything that reads a session cookie. The classic incident is a CDN rule that caches /account and serves one user's page to everyone. Mark those responses private or no-store, and don't rely on the CDN's defaults to notice.
Header examples, not run (they are configuration):
# Public catalog page: browser 60 s, CDN 10 min, serve stale for 30 s while refreshing
Cache-Control: public, max-age=60, s-maxage=600, stale-while-revalidate=30
Vary: Accept-Encoding
Cache-Tag: products, category-lighting
# Hashed static asset
Cache-Control: public, max-age=31536000, immutable
# Logged-in page: never in a shared cache
Cache-Control: private, no-store
In Next.js. The framework sets these headers for you based on how a route renders. A page with export const revalidate = 600 is statically generated and refreshed at most every 10 minutes (incremental static regeneration), and on Vercel the edge caches it. You invalidate by tag from a Server Action or route handler. Not run (needs a Next.js app):
// app/products/page.tsx
export const revalidate = 600; // regenerate at most every 10 minutes
export default async function ProductsPage() {
const res = await fetch("https://api.example.com/products", {
next: { revalidate: 600, tags: ["products"] },
});
const products: { id: number; name: string }[] = await res.json();
return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
// app/actions.ts
"use server";
import { revalidateTag } from "next/cache";
export async function updatePrice(id: number, price: number) {
await fetch(`https://api.example.com/products/${id}`, {
method: "PATCH",
body: JSON.stringify({ price }),
});
revalidateTag("products", "max"); // Next.js 16: mark tagged data stale, refresh on next visit
}
With Cache Components turned on, Next.js 16 also offers the "use cache" directive with cacheLife and cacheTag, which does the same job at function level.
Invalidation story. Purge by tag on write, and keep s-maxage short enough that a missed purge heals itself.
3. Service worker and Cache Storage
What it caches. Whatever your code puts there. A service worker is a script that sits between your page and the network and can answer requests itself, from the Cache Storage API. Unlike the HTTP cache, it follows your rules, not header rules, and it works offline.
The three strategies you'll use.
- Cache-first: answer from the cache, go to the network only on a miss. For the app shell and hashed assets.
- Network-first: try the network, fall back to the cache when offline. For HTML pages and data that should be current when possible.
- Stale-while-revalidate: answer from the cache at once, fetch a fresh copy in the background for next time. For data where slightly old is fine: avatars, a news list, settings.
When to use it. Installable apps and anything that must work offline or on bad connections. If you're building offline-first, the service worker is the read side; the write side needs an outbox and a sync rule, which I covered in app architecture patterns.
When not to. A normal website that's always online gets most of the benefit from good HTTP headers. A service worker adds a layer that can serve old code long after you've deployed new code, and bugs in it are hard for users to escape.
Not run (needs a browser). TypeScript, framework-free:
// sw.ts, compiled to /sw.js and registered with navigator.serviceWorker.register("/sw.js")
declare const self: ServiceWorkerGlobalScope;
const VERSION = "v42"; // bump on every deploy
const SHELL = `shell-${VERSION}`;
const RUNTIME = `runtime-${VERSION}`;
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(SHELL).then((c) => c.addAll(["/", "/offline.html", "/app.3f9a1c.js"])),
);
});
self.addEventListener("activate", (event) => {
// Invalidation: delete every cache that doesn't belong to this version.
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => !k.endsWith(VERSION)).map((k) => caches.delete(k))),
),
);
});
async function cacheFirst(req: Request): Promise<Response> {
return (await caches.match(req)) ?? fetch(req);
}
async function networkFirst(req: Request): Promise<Response> {
try {
const res = await fetch(req);
if (res.ok) (await caches.open(RUNTIME)).put(req, res.clone());
return res;
} catch {
return (await caches.match(req)) ?? (await caches.match("/offline.html"))!;
}
}
async function staleWhileRevalidate(req: Request, event: FetchEvent): Promise<Response> {
const cache = await caches.open(RUNTIME);
const cached = await cache.match(req);
const refresh = fetch(req).then((res) => {
if (res.ok) cache.put(req, res.clone());
return res;
});
event.waitUntil(refresh.catch(() => undefined)); // keep the worker alive for the refresh
return cached ?? refresh;
}
self.addEventListener("fetch", (event) => {
const req = event.request;
if (req.method !== "GET") return; // never cache writes
const url = new URL(req.url);
if (url.pathname.startsWith("/api/me")) return; // per-user data: let it go to the network
if (url.pathname.match(/\.[0-9a-f]{6}\.(js|css)$/)) event.respondWith(cacheFirst(req));
else if (req.mode === "navigate") event.respondWith(networkFirst(req));
else if (url.pathname.startsWith("/api/news")) event.respondWith(staleWhileRevalidate(req, event));
});
In a real project, Workbox gives you these strategies ready-made, with expiry and size limits.
Invalidation story. Version your cache names and delete old ones in activate. That only runs when the browser fetches a new service worker, so make sure sw.js itself is served with no-cache.
4. Client data cache (TanStack Query, SWR, Apollo)
What it caches. API responses, in memory, inside your app, keyed by a query key like ["product", 1]. This is the layer most frontend developers mean when they say "caching".
Why it exists. Without it, every component that needs the current user or the product list fetches it separately. A client data cache gives you:
- Deduplication: ten components asking for the same key at the same moment cause one request.
- Stale-while-revalidate: show the cached data at once, refetch in the background, update the screen when it lands.
- Invalidation after mutations: after you save something, mark the related queries stale so they refetch.
The two timers people confuse (TanStack Query names; SWR and Apollo have equivalents):
staleTime: how long data counts as fresh. While fresh, reads come straight from the cache with no request. The default is 0, so data is stale immediately and refetches on the next mount or window focus.gcTime(calledcacheTimebefore v5): how long an entry stays in memory after no component is using it. After that it's removed. The default is 5 minutes.
Stale data is still shown. It just triggers a background refetch. Removed data is gone, and the next reader waits for a network call.
TypeScript: a small query cache that runs
To show what these libraries do underneath, here's a framework-free query cache with stale-while-revalidate, deduplication, invalidation by key prefix, and gcTime. It runs in Node 26 as-is (node query-cache.mts) and passes tsc --strict.
type Entry<T> = {
data?: T;
fetchedAt: number; // when data last arrived
inFlight?: Promise<T>; // shared by everyone asking at the same time
gcTimer?: ReturnType<typeof setTimeout>;
};
class QueryCache {
private entries = new Map<string, Entry<unknown>>();
private staleTimeMs: number;
private gcTimeMs: number;
constructor(staleTimeMs: number, gcTimeMs: number) {
this.staleTimeMs = staleTimeMs;
this.gcTimeMs = gcTimeMs;
}
// Stale-while-revalidate: return cached data at once, refresh in the background if stale.
async get<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
const e = (this.entries.get(key) ?? { fetchedAt: 0 }) as Entry<T>;
this.entries.set(key, e);
this.scheduleGc(key, e);
const fresh = e.data !== undefined && Date.now() - e.fetchedAt < this.staleTimeMs;
if (fresh) return e.data as T;
const refresh = this.fetch(key, e, fetcher);
if (e.data !== undefined) {
refresh.catch(() => {}); // stale data is served; a failed refresh keeps it
return e.data;
}
return refresh; // nothing cached yet: the caller has to wait
}
invalidate(prefix: string): void {
for (const [key, e] of this.entries) if (key.startsWith(prefix)) e.fetchedAt = 0;
}
private fetch<T>(key: string, e: Entry<T>, fetcher: () => Promise<T>): Promise<T> {
e.inFlight ??= fetcher()
.then((data) => { e.data = data; e.fetchedAt = Date.now(); return data; })
.finally(() => { e.inFlight = undefined; });
return e.inFlight;
}
// gcTime: drop an entry nobody has asked for in a while.
private scheduleGc(key: string, e: Entry<unknown>): void {
clearTimeout(e.gcTimer);
e.gcTimer = setTimeout(() => this.entries.delete(key), this.gcTimeMs);
}
get size() { return this.entries.size; }
}
// ---- demo ----
let serverCalls = 0;
let price = 39;
const fetchProduct = async () => {
serverCalls++;
await new Promise((r) => setTimeout(r, 20)); // pretend network
return { id: 1, price };
};
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const cache = new QueryCache(100, 300); // staleTime 100 ms, gcTime 300 ms
const [a, b, c] = await Promise.all([1, 2, 3].map(() => cache.get("product:1", fetchProduct)));
console.log("3 components, same time:", a.price, b.price, c.price, "server calls:", serverCalls);
console.log("fresh read:", (await cache.get("product:1", fetchProduct)).price, "server calls:", serverCalls);
price = 35; // someone else changes the price
await sleep(120); // data is now stale
console.log("stale read (served at once):", (await cache.get("product:1", fetchProduct)).price);
await sleep(30); // background refresh lands
console.log("next read:", (await cache.get("product:1", fetchProduct)).price, "server calls:", serverCalls);
price = 29; // our own mutation succeeds...
cache.invalidate("product:"); // ...so mark related queries stale
await cache.get("product:1", fetchProduct);
await sleep(30);
console.log("after mutation + invalidate:", (await cache.get("product:1", fetchProduct)).price, "server calls:", serverCalls);
await sleep(350);
console.log("entries after gcTime with no readers:", cache.size);
3 components, same time: 39 39 39 server calls: 1
fresh read: 39 server calls: 1
stale read (served at once): 39
next read: 35 server calls: 2
after mutation + invalidate: 29 server calls: 3
entries after gcTime with no readers: 0
Read the third line carefully: it's the whole trade-off of stale-while-revalidate. The price had already changed to 35, and the reader still got 39, instantly, while the refresh happened behind it. That's right for a product list and wrong for a checkout total.
The same with TanStack Query
Not run (needs a React app). TanStack Query v5:
import { QueryClient, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
export const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 30_000, gcTime: 5 * 60_000 } },
});
type Product = { id: number; name: string; price: number };
export function useProduct(id: number) {
return useQuery({
queryKey: ["products", id],
queryFn: async (): Promise<Product> => {
const res = await fetch(`/api/products/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
},
staleTime: 60_000, // product details: fresh for a minute
});
}
export function useUpdatePrice() {
const qc = useQueryClient();
return useMutation({
mutationFn: (p: { id: number; price: number }) =>
fetch(`/api/products/${p.id}`, { method: "PATCH", body: JSON.stringify(p) }),
// After a successful write, every query whose key starts with ["products"] refetches.
onSuccess: () => qc.invalidateQueries({ queryKey: ["products"] }),
});
}
When to use it. Almost any single-page app or React Native app that talks to an API. It removes a lot of hand-written loading state.
When not to. Data the server already rendered and that never changes on the client. And it is not a replacement for server caching: it saves one user repeat requests, but it does nothing for a thousand different users asking the same thing.
Invalidation story. Invalidate by key prefix after every mutation you make. For changes other people make, rely on staleTime plus refetch on focus, or push updates over a WebSocket and invalidate when they arrive.
5. UI memoization and on-device storage
Memoization caches the result of a calculation inside a component, not data from a server. React's useMemo, Vue's computed and SwiftUI's derived state all do this: they recompute only when their inputs change.
// Not run (React). Recompute only when items or query change, not on every render.
const visible = useMemo(
() => items.filter((i) => i.name.toLowerCase().includes(query.toLowerCase())),
[items, query],
);
Use it for calculations that are actually expensive (sorting thousands of rows, building a chart's data), or to keep an object reference stable for a child component. Don't wrap everything. A memo has its own cost, and the React Compiler now handles much of this automatically.
localStorage and IndexedDB persist data across reloads. localStorage is small (around 5 MB), synchronous and strings only, so keep it for preferences and small flags. IndexedDB is asynchronous and holds much more, so it's where offline data goes. TanStack Query can persist its cache there with a persister plugin.
Two rules for persistent client storage:
- Never put secrets or long-lived tokens in
localStorage. Any script on your page can read it, so a single XSS bug hands an attacker every token. Prefer anHttpOnly,Secure,SameSitecookie for session tokens, which JavaScript can't read at all. - Clear it on logout. On a shared device, the next user should not open your app and see the last user's cached orders. Key persisted data by user ID and delete it when the session ends.
6. In-process cache (backend)
Now we cross to the server. The fastest server-side cache is a dictionary in your own process's memory: no network, no serialization.
What it caches. Results of database queries or calls to other services, reference data (countries, tax rates, feature config), and computed values.
The catch. Each instance has its own copy. With three instances behind a load balancer you have three caches, and a write that clears one of them leaves the other two serving old data until they expire. Each instance also misses separately after a deploy or restart.
Python: a TTL cache, standard library only
functools.lru_cache has no expiry, so it's only safe for values that never change for a given input. For anything else you need a TTL. cachetools.TTLCache is the usual package; here's the same idea in the standard library:
import functools, threading, time
def ttl_cache(seconds: float, maxsize: int = 1024):
"""Per-process cache with expiry. Like cachetools.TTLCache, stdlib only."""
def decorator(fn):
store: dict = {} # key -> (expires_at, value); dicts keep insertion order
lock = threading.Lock()
@functools.wraps(fn)
def wrapper(*args):
now = time.monotonic()
with lock:
hit = store.get(args)
if hit and hit[0] > now:
return hit[1]
value = fn(*args) # call outside the lock so slow loads don't block hits
with lock:
if len(store) >= maxsize:
store.pop(next(iter(store))) # evict the oldest entry
store[args] = (now + seconds, value)
return value
wrapper.cache_clear = lambda: store.clear()
wrapper.invalidate = lambda *args: store.pop(args, None)
return wrapper
return decorator
db_calls = 0
@ttl_cache(seconds=0.2)
def get_product(product_id: int) -> dict:
global db_calls
db_calls += 1
return {"id": product_id, "price": 39.0}
get_product(1); get_product(1); get_product(1)
print("3 reads, db calls:", db_calls)
time.sleep(0.25)
get_product(1)
print("after TTL, db calls:", db_calls)
get_product.invalidate(1)
get_product(1)
print("after invalidate, db calls:", db_calls)
# lru_cache: no TTL, so only for values that never change for a given input.
@functools.lru_cache(maxsize=256)
def tax_rate(country: str) -> float:
return {"CA": 0.13, "US": 0.07}.get(country, 0.0)
tax_rate("CA"); tax_rate("CA"); tax_rate("US")
print(tax_rate.cache_info())
3 reads, db calls: 1
after TTL, db calls: 2
after invalidate, db calls: 3
CacheInfo(hits=1, misses=2, maxsize=256, currsize=2)
This version has no stampede protection: if 50 threads miss the same key at once, 50 database calls happen. Part 1 covers the fixes.
C#: IMemoryCache
#:package Microsoft.Extensions.Caching.Memory@10.0.0
using Microsoft.Extensions.Caching.Memory;
var cache = new MemoryCache(new MemoryCacheOptions { SizeLimit = 1_000 });
var dbCalls = 0;
async Task<Product> GetProduct(int id) =>
(await cache.GetOrCreateAsync($"product:{id}", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(200);
entry.Size = 1; // required once SizeLimit is set
Interlocked.Increment(ref dbCalls);
await Task.Delay(10); // pretend database
return new Product(id, 39.0m);
}))!;
await GetProduct(1); await GetProduct(1); await GetProduct(1);
Console.WriteLine($"3 reads, db calls: {dbCalls}");
await Task.Delay(250);
await GetProduct(1);
Console.WriteLine($"after expiry, db calls: {dbCalls}");
cache.Remove("product:1"); // invalidate after a write
await GetProduct(1);
Console.WriteLine($"after Remove, db calls: {dbCalls}");
// The catch: GetOrCreateAsync has no stampede protection.
dbCalls = 0;
cache.Remove("product:1");
await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => GetProduct(1)));
Console.WriteLine($"10 concurrent misses, db calls: {dbCalls}");
record Product(int Id, decimal Price);
3 reads, db calls: 1
after expiry, db calls: 2
after Remove, db calls: 3
10 concurrent misses, db calls: 10
The last line is worth knowing: IMemoryCache.GetOrCreateAsync does not stop a stampede. Ten callers that miss at the same time all run the factory. Always set a SizeLimit (or at least expiries) too, or the cache grows until the process runs out of memory.
C#: HybridCache, the default I'd reach for in .NET
HybridCache (package Microsoft.Extensions.Caching.Hybrid, built for .NET 9 and later, and it also runs on older runtimes) puts an in-process L1 in front of an optional distributed L2 such as Redis, behind one API. It adds the things IMemoryCache is missing: stampede protection, tags, and serialization handled for you.
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
#:package Microsoft.Extensions.Caching.Hybrid@10.0.0
using Microsoft.Extensions.Caching.Hybrid;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.Services.AddHybridCache(o => o.DefaultEntryOptions = new HybridCacheEntryOptions
{
Expiration = TimeSpan.FromMinutes(5), // L2 (distributed) lifetime
LocalCacheExpiration = TimeSpan.FromMinutes(1) // L1 (in-process) lifetime
});
// In production, add an L2 and HybridCache uses it automatically:
// builder.Services.AddStackExchangeRedisCache(o => o.Configuration = "localhost:6379");
using var app = builder.Build();
var cache = app.Services.GetRequiredService<HybridCache>();
var dbCalls = 0;
async ValueTask<Product> LoadProduct(int id, CancellationToken ct)
{
Interlocked.Increment(ref dbCalls);
await Task.Delay(50, ct); // pretend database
return new Product(id, "Desk lamp", 39.0m);
}
ValueTask<Product> GetProduct(int id) =>
cache.GetOrCreateAsync($"product:{id}", id, (id, ct) => LoadProduct(id, ct),
tags: ["products", "category:lighting"]);
await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => GetProduct(1).AsTask()));
Console.WriteLine($"10 concurrent misses, db calls: {dbCalls}");
await GetProduct(1);
Console.WriteLine($"another read, db calls: {dbCalls}");
await GetProduct(2);
Console.WriteLine($"product 2, db calls: {dbCalls}");
await cache.RemoveByTagAsync("category:lighting"); // one call drops every entry with that tag
await GetProduct(1); await GetProduct(2);
Console.WriteLine($"after RemoveByTagAsync, db calls: {dbCalls}");
record Product(int Id, string Name, decimal Price);
10 concurrent misses, db calls: 1
another read, db calls: 1
product 2, db calls: 2
after RemoveByTagAsync, db calls: 4
Ten concurrent misses ran the factory once, and one tag call invalidated both products. Two things to know before you rely on it in production:
- Stampede protection is per instance. Five servers that miss at the same moment can still make five database calls. That's usually fine; a stampede of five is not a stampede of five thousand.
- Removing an entry doesn't reach other servers' L1. Microsoft's docs say it plainly: invalidation by key or tag applies to the current server and to L2, but the in-memory cache on other servers isn't affected. So keep
LocalCacheExpirationshort (seconds to a minute) for data that changes. That short L1 lifetime is your bound on staleness.
When to use an in-process cache. Hot, small, read-mostly data where a few seconds or minutes of staleness per instance is fine.
When not to. Data that must be the same on every instance right after a write, or data too big to copy into every process.
7. Distributed cache (Redis)
What it caches. The same kinds of data as the in-process cache, but in one shared store that every instance reads and writes. One write, one invalidation, every instance sees it. It survives deploys, so new instances start warm.
The cost. A network hop on every read (usually under a millisecond in the same region, but it adds up across many calls per request), serialization, and one more piece of infrastructure to run and keep available. If Redis goes down, your app must fall back to the database, not fail.
The problem it solves, as a runnable demo
Two app instances, one database, and a write that lands on instance A. First each instance has its own local cache; then both use a shared cache. The shared dictionary stands in for Redis.
Python:
database = {"product:1": 39.0}
shared_l2: dict = {} # stand-in for Redis: one store every instance talks to
class AppInstance:
def __init__(self, name: str, use_shared: bool):
self.name, self.use_shared = name, use_shared
self.local: dict = {} # in-process cache: private to this instance
def get_price(self, key: str) -> float:
store = shared_l2 if self.use_shared else self.local
if key not in store:
store[key] = database[key] # cache-aside: load on miss
return store[key]
def update_price(self, key: str, price: float) -> None:
database[key] = price
store = shared_l2 if self.use_shared else self.local
store.pop(key, None) # invalidate... but only the store it can see
for use_shared in (False, True):
database["product:1"] = 39.0
shared_l2.clear()
a, b = AppInstance("A", use_shared), AppInstance("B", use_shared)
a.get_price("product:1"); b.get_price("product:1") # both warm up
a.update_price("product:1", 29.0) # request lands on A
label = "shared cache" if use_shared else "local caches"
print(f"{label}: A says {a.get_price('product:1')}, B says {b.get_price('product:1')}")
local caches: A says 29.0, B says 39.0
shared cache: A says 29.0, B says 29.0
C#:
var database = new Dictionary<string, decimal> { ["product:1"] = 39.0m };
var sharedL2 = new Dictionary<string, decimal>(); // stand-in for Redis
foreach (var useShared in new[] { false, true })
{
database["product:1"] = 39.0m;
sharedL2.Clear();
var a = new AppInstance(database, sharedL2, useShared);
var b = new AppInstance(database, sharedL2, useShared);
a.GetPrice("product:1"); b.GetPrice("product:1"); // both warm up
a.UpdatePrice("product:1", 29.0m); // request lands on A
Console.WriteLine($"{(useShared ? "shared cache" : "local caches")}: A says {a.GetPrice("product:1")}, B says {b.GetPrice("product:1")}");
}
class AppInstance(Dictionary<string, decimal> db, Dictionary<string, decimal> shared, bool useShared)
{
private readonly Dictionary<string, decimal> _local = new(); // private to this instance
private Dictionary<string, decimal> Store => useShared ? shared : _local;
public decimal GetPrice(string key)
{
if (!Store.TryGetValue(key, out var price))
Store[key] = price = db[key]; // cache-aside: load on miss
return price;
}
public void UpdatePrice(string key, decimal price)
{
db[key] = price;
Store.Remove(key); // invalidates only what it can see
}
}
local caches: A says 29.0, B says 39.0
shared cache: A says 29.0, B says 29.0
With local caches, instance B keeps selling at the old price until its entry expires, and a user who reloads the page sees the price flip back and forth depending on which instance answers. With a shared cache, one invalidation fixes it for everyone. That is the main reason to add an L2.
The real thing
Not run (needs a Redis server). C# with IDistributedCache, the plain cache-aside shape:
// Program.cs
builder.Services.AddStackExchangeRedisCache(o =>
{
o.Configuration = builder.Configuration.GetConnectionString("Redis");
o.InstanceName = "shop:"; // key prefix, so apps can share one Redis
});
// ProductService.cs
public sealed class ProductService(IDistributedCache cache, ProductRepository repo)
{
public async Task<Product?> GetAsync(int id, CancellationToken ct)
{
var key = $"product:{id}";
var bytes = await cache.GetAsync(key, ct);
if (bytes is not null) return JsonSerializer.Deserialize<Product>(bytes);
var product = await repo.FindAsync(id, ct);
if (product is not null)
await cache.SetAsync(key, JsonSerializer.SerializeToUtf8Bytes(product),
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }, ct);
return product;
}
public async Task UpdatePriceAsync(int id, decimal price, CancellationToken ct)
{
await repo.UpdatePriceAsync(id, price, ct); // database first
await cache.RemoveAsync($"product:{id}", ct); // then invalidate
}
}
If you're using HybridCache, registering AddStackExchangeRedisCache is all it takes for it to use Redis as L2; you keep calling GetOrCreateAsync.
Not run (needs a Redis server). Python with redis-py:
import json
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def get_product(product_id: int) -> dict | None:
key = f"shop:product:{product_id}"
cached = r.get(key)
if cached is not None:
return json.loads(cached)
product = db_find_product(product_id) # your data access
if product is not None:
r.set(key, json.dumps(product), ex=600) # 10-minute TTL
return product
def update_price(product_id: int, price: float) -> None:
db_update_price(product_id, price) # database first
r.delete(f"shop:product:{product_id}") # then invalidate
Combining L1 and L2. If you keep an in-process cache in front of Redis (which is what HybridCache does), other instances' L1 copies won't hear about a delete. Two ways to deal with it: keep L1 lifetimes short, or publish an invalidation message on a Redis channel that every instance subscribes to and clears its L1 on. The second gives you seconds of staleness instead of minutes, at the cost of more code.
When to use it. More than one instance, data that should look the same on all of them, or expensive results you want to survive a deploy.
When not to. A single instance with small data (in-process is simpler and faster), or as the only copy of anything. A cache can lose data at any time; the database is the source of truth.
8. Output caching (whole responses on the server)
What it caches. The final response of an endpoint: status, headers and body. A hit skips your handler, your services and your database entirely. It's the server-side twin of the CDN, and unlike the CDN it can live behind your authentication and run on your own rules.
ASP.NET Core has two middlewares, and they're different:
- Response Caching (
AddResponseCaching) follows HTTP caching headers. It caches only whatCache-Controlallows, and clients can bypass it by sendingCache-Control: no-cache. It's essentially a small HTTP cache in your server. - Output Caching (
AddOutputCache, .NET 7 and later) is controlled by your server code. You choose policies per endpoint, vary by query or header, tag entries, and evict by tag on write. It also locks so that concurrent requests for the same uncached response run the handler once. By default it only cachesGETandHEADrequests that return 200, and it skips authenticated requests and responses that set cookies. Its store is in memory by default; from .NET 8 you can back it with Redis (AddStackExchangeRedisOutputCache) so all instances share it.
For new code, Output Caching is the one to use.
C#: Output Caching with tags
Runs a real server, calls it, evicts by tag after a write:
#:sdk Microsoft.NET.Sdk.Web
#:property PublishAot=false
using Microsoft.AspNetCore.OutputCaching;
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
builder.Services.AddOutputCache(o =>
{
o.AddPolicy("Catalog", p => p
.Expire(TimeSpan.FromMinutes(10))
.SetVaryByQuery("page") // ?page=1 and ?page=2 are different entries
.Tag("catalog"));
});
var app = builder.Build();
app.Urls.Add("http://127.0.0.1:0");
app.UseOutputCache();
var handlerRuns = 0;
var price = 39.0m;
app.MapGet("/products", (int page) =>
{
Interlocked.Increment(ref handlerRuns);
return Results.Ok(new { page, price });
}).CacheOutput("Catalog");
app.MapPost("/products/1/price/{newPrice}", async (decimal newPrice, IOutputCacheStore store, CancellationToken ct) =>
{
price = newPrice;
await store.EvictByTagAsync("catalog", ct); // drop every cached catalog page
return Results.NoContent();
});
await app.StartAsync();
using var http = new HttpClient { BaseAddress = new Uri(app.Urls.First()) };
Console.WriteLine(await http.GetStringAsync("/products?page=1") + $" handler runs: {handlerRuns}");
Console.WriteLine(await http.GetStringAsync("/products?page=1") + $" handler runs: {handlerRuns}");
Console.WriteLine(await http.GetStringAsync("/products?page=2") + $" handler runs: {handlerRuns}");
await http.PostAsync("/products/1/price/29", null);
Console.WriteLine(await http.GetStringAsync("/products?page=1") + $" handler runs: {handlerRuns}");
await app.StopAsync();
{"page":1,"price":39.0} handler runs: 1
{"page":1,"price":39.0} handler runs: 1
{"page":2,"price":39.0} handler runs: 2
{"page":1,"price":29} handler runs: 3
The second request for page 1 didn't run the handler. Page 2 is a separate entry because the policy varies by page. After the price update, EvictByTagAsync("catalog") dropped both pages and the next request ran the handler again. (The 39.0 versus 29 is just how a decimal keeps the scale it was created with.)
Python: the same idea as a decorator
Python's web frameworks leave this to you or to a plugin (Flask-Caching, for example). Here's the core, standard library only, with a cache key, a TTL, tags and eviction:
import json, threading, time
from collections import defaultdict
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.request import Request, urlopen
class OutputCache:
"""Caches whole responses by path + query, with expiry and tag eviction."""
def __init__(self):
self.entries: dict = {} # cache key -> (expires_at, body)
self.by_tag = defaultdict(set) # tag -> cache keys
self.lock = threading.Lock()
def cached(self, seconds: float, tags: tuple = ()):
def decorator(handler_fn):
def wrapper(req: BaseHTTPRequestHandler):
key = req.path # path + query string = the cache key
with self.lock:
hit = self.entries.get(key)
if hit and hit[0] > time.monotonic():
return hit[1]
body = handler_fn(req)
with self.lock:
self.entries[key] = (time.monotonic() + seconds, body)
for t in tags:
self.by_tag[t].add(key)
return body
return wrapper
return decorator
def evict_by_tag(self, tag: str) -> None:
with self.lock:
for key in self.by_tag.pop(tag, set()):
self.entries.pop(key, None)
cache = OutputCache()
state = {"price": 39.0, "handler_runs": 0}
@cache.cached(seconds=600, tags=("catalog",))
def list_products(req) -> bytes:
state["handler_runs"] += 1
page = req.path.partition("page=")[2] or "1"
return json.dumps({"page": int(page), "price": state["price"]}).encode()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.startswith("/products"):
self.reply(200, list_products(self))
else:
self.send_error(404)
def do_POST(self):
if self.path.startswith("/products/1/price/"):
state["price"] = float(self.path.rsplit("/", 1)[1])
cache.evict_by_tag("catalog") # drop every cached catalog page
self.reply(204, b"")
def reply(self, status, body):
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args): pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"
get = lambda p: urlopen(base + p).read().decode()
print(get("/products?page=1"), " handler runs:", state["handler_runs"])
print(get("/products?page=1"), " handler runs:", state["handler_runs"])
print(get("/products?page=2"), " handler runs:", state["handler_runs"])
urlopen(Request(base + "/products/1/price/29", method="POST"))
print(get("/products?page=1"), " handler runs:", state["handler_runs"])
server.shutdown()
{"page": 1, "price": 39.0} handler runs: 1
{"page": 1, "price": 39.0} handler runs: 1
{"page": 2, "price": 39.0} handler runs: 2
{"page": 1, "price": 29.0} handler runs: 3
The cache key here is the full path with its query string. In real code, normalize it (sort parameters, drop tracking ones) and never cache a response that depends on who the user is unless the user ID is part of the key.
When to use it. Public or semi-public endpoints that are expensive to build and read far more often than they change: catalog pages, home page fragments, public API listings, reports.
When not to. Per-user responses (unless you vary by user, and then check the hit rate is worth it), and endpoints where a fraction of a second of staleness after a write would be wrong.
9. Database-level caching
The database caches a lot on its own, and some of it you get for free.
- Buffer pool / shared buffers. The engine keeps hot data pages in RAM. A query that hits memory is much faster than one that reads disk. This is why "add a cache" sometimes does less than "give the database more memory".
- Query plan cache. Compiling a query plan costs CPU. Engines reuse plans for queries with the same text. Use parameterized queries so
WHERE id = @idis one plan, not a new plan for every ID glued into the string. Parameters also protect you from SQL injection. - Materialized views and indexed views. A stored query result the database keeps for you. It's a cache you don't manage yourself: PostgreSQL refreshes a materialized view when you ask; SQL Server keeps an indexed view up to date on every write. Good for dashboards and aggregates that are expensive to compute on every read.
- Read replicas. Copies of the database that serve reads. They aren't a cache, but they solve the same "too many reads" problem, with replication lag as the staleness. I covered them in data at scale.
Not run (needs PostgreSQL):
CREATE MATERIALIZED VIEW daily_sales AS
SELECT date_trunc('day', placed_at) AS day, sum(total_cents) AS total_cents, count(*) AS orders
FROM orders
GROUP BY 1;
CREATE UNIQUE INDEX ON daily_sales (day); -- required for CONCURRENTLY
-- From a scheduled job: rebuild without blocking readers.
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;
Before adding Redis because "the database is slow", check the boring things first: a missing index, an N+1 query, a query that can't use the plan cache. A cache in front of a bad query hides the problem until the cache misses.
Frontend or backend? Choosing by data type
Here's how I'd place the common kinds of data. TTLs are starting points; tune them with real hit rates.
| Data | Layers | TTL | Invalidation |
|---|---|---|---|
| Static assets (JS, CSS, fonts, images) | Browser + CDN, hashed filenames; service worker cache-first if offline matters | 1 year, immutable | New build, new filename. Nothing to purge |
| HTML pages | CDN short or no-cache; browser no-cache | 0 to 60 s at the edge | Deploy or tag purge |
| Public catalog, product pages, blog posts | CDN + output cache or ISR; HybridCache for the underlying queries; client cache with staleTime | Edge 1 to 10 min; L1 30 to 60 s; L2 10 min | Tag purge at the CDN and evict by tag on the server when the product changes |
| Per-user dashboard | Client data cache; server-side per-user keys in Redis if expensive | Client 30 s; server 1 to 5 min | Invalidate the user's keys on their own writes; private, no-store at the HTTP layer |
| Prices and stock | Short server cache only; client cache with small staleTime; never trust a cached value at checkout | 5 to 30 s | Evict on write; re-read from the database for the actual purchase |
| Auth and session | Session store in Redis (it's state, not a cache); token validation keys (JWKS) in process | Session: its own lifetime; JWKS: hours, refresh on unknown key | Delete the session on logout; never at the edge, never in localStorage |
| Search results | Server cache keyed by normalized query + filters; CDN only if results aren't personalized | 1 to 5 min | Mostly TTL; tag by index version if you reindex |
| AI responses | Provider prompt caching for long fixed prefixes; exact-match cache in Redis; semantic cache for near-duplicates | Hours to days, by how fast the facts change | Version keys by model and prompt; see AI in production |
And the rules underneath the table:
- Cache as close to the user as correctness allows. Start at the browser and move inward until you reach a layer where you can invalidate fast enough and nobody can see someone else's data.
- Never put per-user data in a shared cache unless the user ID is part of the key. That covers CDNs, proxies, output caches and Redis keys alike. Mark personal responses
privateorno-store. - The layers you can't reach get the shortest lifetimes. Long TTLs belong in places you can purge (CDN, Redis), short ones in places you can't (browsers, other servers' L1).
- Every cache needs an owner and an invalidation plan. For each cache, write down: what's in it, its TTL, what event clears it, and who is paged when it serves wrong data. If you can't answer "how do I clear this", don't add it.
- The database stays the source of truth. Anything that charges money, grants access or confirms a booking reads fresh data.
- Measure hit rates. A cache with a 10% hit rate costs you memory, a network hop and a source of bugs for little gain.
For the pattern view of the cache-aside shape used throughout this post, see cloud structure patterns, and for where caching sits among the other architecture patterns, the architecture patterns map.
Check yourself: questions and answers
1. What's the difference between no-cache and no-store?
no-cache lets a cache store the response but requires it to revalidate with the server before every reuse, usually with an ETag and a cheap 304. no-store forbids storing it anywhere. Use no-cache for things that change often but are fine to keep; use no-store for sensitive data.
2. How does an ETag save bandwidth if the browser still makes a request?
The browser sends the ETag back in If-None-Match. If nothing changed, the server answers 304 Not Modified with no body, so you pay one small round trip instead of downloading the whole response again. It saves bandwidth and server rendering time, not the round trip.
3. Why cache hashed static assets for a year?
The hash is part of the URL, so the content at that URL can never change. A new build makes a new URL and the HTML points to it. Old files are never asked for again, so there's nothing to invalidate. The HTML must not be cached long, because it's what links to the new names.
4. How do you cache per-user data safely?
Keep it out of shared HTTP caches: send Cache-Control: private or no-store. Cache it on the client (TanStack Query, in memory) and on the server under keys that include the user ID, such as dashboard:user:123, with short TTLs and invalidation on that user's writes. Clear any persisted client copy on logout.
5. IMemoryCache vs IDistributedCache vs HybridCache?
IMemoryCache is in-process: fastest, but each instance has its own copy and there's no stampede protection. IDistributedCache is a shared store like Redis: one copy for all instances, with a network hop and serialization. HybridCache combines them as L1 and L2 behind one API and adds stampede protection and tags. Its limit is that removing an entry doesn't clear other servers' L1, so keep the local lifetime short.
6. How do you invalidate a CDN?
Purge by URL or, better, by tag: label responses with a cache-tag or surrogate-key header and purge the tag when the underlying data changes, from the same code path that writes it. Keep s-maxage short enough that a failed purge heals on its own, and use hashed URLs for assets so they never need purging.
7. What's the difference between staleTime and gcTime in TanStack Query?
staleTime is how long data counts as fresh; fresh data is served with no request. After that it's stale: still shown, but refetched in the background. gcTime is how long an entry stays in memory once no component is using it; after that it's deleted and the next reader waits for the network.
8. Response Caching vs Output Caching in ASP.NET Core?
Response Caching follows HTTP headers and clients can bypass it, so it behaves like a small HTTP cache in your server. Output Caching is configured in server code, supports policies, vary-by rules, tags and EvictByTagAsync, protects against concurrent misses, and can use Redis as a shared store. Use Output Caching for new code.
Further reading
- MDN, HTTP caching and the Cache-Control reference
- IETF, RFC 9111: HTTP Caching and RFC 9213: Targeted HTTP Cache Control (
CDN-Cache-Control) - web.dev, Keeping things fresh with stale-while-revalidate
- MDN, Cache (Cache Storage API), and Chrome's Workbox
- TanStack Query, Caching examples
- Next.js, revalidateTag
- Microsoft Learn, HybridCache library in ASP.NET Core, In-memory caching, Distributed caching, Output caching middleware and Response caching middleware
- Redis docs, redis-py guide
- PostgreSQL docs, Materialized views
- The previous post in this series: Caching in Depth, Part 1: strategies
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.