Cache layers, from HTTP caching to the database
Explore the caching hierarchy across browser caches, shared CDNs, reverse proxy caches, in-process application memory, Redis key-value stores, and database query buffers.
Contentsand lesson path
On this page
- Why it matters
- The cache tiers, from browser to disk
- Choosing the right tier
- Check your understanding
- Apply it
- Review prompt
Lessons of Caching Strategies
- Cache layers, from HTTP caching to the database Concept · 20 min
- Cache-aside, read-through, write-through, write-behind and refresh-ahead Concept · 25 min
- Invalidation, TTLs, HTTP revalidation and the staleness budget Concept · 20 min
- Hit-ratio math and sizing a cache tier Worked example · 25 min
- Surviving stampedes and hot keys Lab · 30 min
- Caching check Knowledge check · 8 questions
What you will learn
- Choose cache placement (HTTP client and CDN, reverse proxy, application, database) and a pattern (cache-aside, read-through, write-through, write-behind, refresh-ahead) for a read/write profile.
01. Why it matters
Suppose the featured-products page of a shop takes 300 ms because every request runs the same catalogue query, and a sale will double the traffic next week. "Add a cache" sounds like one decision, but a copy of that response can live in at least six places between the user's screen and the database's disk. Each place gives different answers to three questions: who may share the copy, how stale it may get, and who can clear it when a price changes. Pick the wrong place and you either save little work or, worse, serve one customer's data to another. This lesson maps the places, so the later lessons can choose between them.
02. The cache tiers, from browser to disk
Caching is not a single feature or one Redis box. In a typical web system it is a hierarchy of caches stretching from the user's browser, through edge networks and internal proxies, into application processes and down to the database's own memory.
Each tier has its own latency, its own invalidation problem and its own owner:
- Client and browser caches. Memory and disk caches inside browsers and mobile apps. A hit costs no network round trip at all. They are controlled by HTTP headers such as
Cache-Control: private, max-age=.... A browser cache is private: a response cached on Alice's phone does nothing for Bob. - Shared edge CDNs (Cloudflare, CloudFront, Fastly). Servers in points of presence (PoPs) close to users. For public, non-personalised endpoints, a header such as
Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=60lets the edge keep one shared copy for five minutes while browsers keep theirs for one. Repeat requests are then answered at the edge; the origin still sees cache misses, expired entries being revalidated, and requests whose cache key differs. How much origin traffic this removes depends on the edge hit ratio, which you measure rather than assume. - Reverse proxy caches (Nginx, Varnish, Envoy). Caches directly in front of your service. In Nginx,
proxy_cache_lock onlets only one request per cache key go upstream to fill a missing entry while the others wait for it, andproxy_cache_use_stale error timeout updating http_500 http_502keeps serving the stale copy while one request refreshes it (in the background withproxy_cache_background_update on) or while backend pods restart. - In-process application memory. Caches such as Python's
functools.lru_cache, a Gosync.Mapor a Guava cache, living inside each API worker. A hit is a dictionary lookup in the same process: no network hop and no JSON decoding. But every worker process keeps its own copy, which costs RAM in each process and lets the copies drift apart across pods. - Distributed key-value stores (Redis, Valkey, Memcached). In-memory stores shared by all application instances. A read costs one network round trip, usually well under a millisecond inside one data centre, and Redis adds atomic operations on hashes, sets and sorted sets. Every instance sees the same primary copy; replicas, if you read from them, can lag behind it.
- The database buffer pool (
shared_buffersin PostgreSQL). Shared memory in which the database keeps recently used 8 kB table and index pages, so a hit avoids a read from disk.
To see how the layers compose, follow one request for a product catalogue (GET /api/v1/products/featured). The client checks its local HTTP cache. On a miss, the request travels to an edge PoP. If the edge has no fresh entry, the request passes through the load balancer to an Nginx reverse proxy, which checks its own cache. On a miss there, an application worker checks its in-process L1 cache, then Redis over the private network. If Redis misses too, the worker sends a SQL query to PostgreSQL, which looks in shared_buffers; only on a miss there does the database (or the operating system's page cache) read from disk. On the way back, each layer decides whether to keep a copy, based on cache headers and its own policy.
03. Choosing the right tier
Choosing where to place a cache means weighing five things:
- Latency. Costs differ by orders of magnitude: nanoseconds for memory inside the process; tens to hundreds of microseconds for Redis on the same host; around a millisecond or less for Redis across a data-centre network; about the same for a PostgreSQL query answered from
shared_buffers, most of it network round trip; and much more when that query has to read from disk, especially network-attached cloud disks. Measure your own stack before you optimise it; the ranking matters more than any single number. - Distance from the user. The closer the cache is to the user, the shorter the network round trip. A user in Tokyo talking to an origin in Virginia pays a trans-Pacific round trip on every miss; an edge location in the same city answers without it.
- Personalisation. Shared caches (CDNs, Nginx) must not store personalised responses, or one user's data can be served to another. Private data such as account balances or shopping carts is cached either in the user's own browser with
Cache-Control: private, or server-side in Redis under keys that include the user id. - Invalidation. Clearing an in-process cache in 50 pods needs a broadcast, for example over pub/sub, and a CDN purge goes through an API call that can take seconds to reach every edge location. A Redis
DELtakes effect on the primary at once, though replicas and every in-process copy still need their own path. - What the cache saves. A cache close to the database, such as Redis, saves SQL work, but every request still passes through the web framework, authentication middleware and network routing. A cache closer to the user saves more of that path, at the price of harder invalidation.
import copy
import json
import time
from collections import OrderedDict
import redis
# Short timeouts: a slow cache must not stall every request
redis_client = redis.Redis(
host="localhost", port=6379, db=0,
socket_timeout=0.5, socket_connect_timeout=0.5,
)
# L1 in-process cache: per worker, bounded, holds already-decoded dicts
L1_MAX_ENTRIES = 10_000
L1_TTL_SECONDS = 10
L1_CACHE: OrderedDict[str, tuple[dict, float]] = OrderedDict()
def l1_put(key: str, value: dict, now: float) -> None:
L1_CACHE[key] = (value, now + L1_TTL_SECONDS)
L1_CACHE.move_to_end(key)
while len(L1_CACHE) > L1_MAX_ENTRIES:
L1_CACHE.popitem(last=False) # evict the least recently used entry
def get_user_settings(user_id: str) -> dict:
now = time.monotonic()
# 1. Check L1 in-process memory: no network hop, no JSON parsing
hit = L1_CACHE.get(user_id)
if hit and now < hit[1]:
L1_CACHE.move_to_end(user_id)
return copy.deepcopy(hit[0]) # callers may mutate their copy
# 2. Check L2 distributed Redis cache
redis_key = f"settings:{user_id}"
cached_raw = redis_client.get(redis_key)
if cached_raw:
settings_data = json.loads(cached_raw)
l1_put(user_id, settings_data, now) # warm L1 on this worker
return copy.deepcopy(settings_data)
# 3. Cache miss: Fetch from authoritative SQL database
settings_data = {"user_id": user_id, "theme": "dark", "locale": "en"}
redis_client.set(redis_key, json.dumps(settings_data), ex=300)
l1_put(user_id, settings_data, now)
return copy.deepcopy(settings_data)Two details make the L1 safe to copy. It is bounded: an OrderedDict kept in least-recently-used order evicts the oldest entry once it holds 10,000, so a million distinct users cannot grow a worker's memory without limit (a plain dict would keep every user it ever saw, because expired entries are only replaced, never removed). And it stores the decoded dict, so an L1 hit skips both the network and JSON parsing, returning a copy so that a caller who edits the result cannot corrupt the cached value. The library cachetools.TTLCache(maxsize=..., ttl=...) gives you the same behaviour ready-made. The cost to accept: after a settings change, each worker can keep serving the old value for up to L1_TTL_SECONDS, so keep that TTL short and use L1 only for data that tolerates it.
04. Check your understanding
05. Apply it
Audit the cache tiers of a service you know:
- Edge caching for public endpoints. For public, unauthenticated listing endpoints, let the CDN or reverse proxy honour
Cache-Control: public, s-maxage=60, stale-while-revalidate=30, then measure how much repeat traffic the edge absorbs. The origin still sees every cache miss — roughly one request per edge location per TTL, plus requests whose cache key differs (query strings, cookies,Vary), cold edge locations and purges. - Redis memory limits and eviction. Set an explicit limit in
redis.conf(for examplemaxmemory 4gb) and an eviction policy such asallkeys-lruorvolatile-lru. With no limit, Redis keeps growing until the host runs out of memory and the kernel's out-of-memory killer may stop it. - Bounded in-process caches. When you use in-memory dictionaries or Python's
lru_cache, set a hard cap (for examplemaxsize=1024), so a long-running worker cannot grow until its container is killed for using too much memory. - Two-level caches for very hot keys. For hot, read-heavy keys, combine a short-lived in-process L1 cache (5–10 seconds) with a Redis L2 cache, so that bursts on one key are absorbed inside each process instead of all reaching Redis.
- The database buffer pool. On a dedicated database server, the PostgreSQL documentation suggests about 25% of RAM for
shared_buffersas a starting point, leaving the rest to the operating system's page cache; tune it from your own measurements.
The next lesson compares five caching patterns: cache-aside, read-through, write-through, write-behind and refresh-ahead.
06. Review prompt
Without looking back: name the cache tiers between a browser and the database, from the fastest to the slowest. What is a CDN cache good at, and what is a cache inside your application process good at? Why does the browser's private cache not protect your servers when many different users arrive at once? How can a reverse proxy keep answering while the origin is down?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.