Cache Systems Every Developer Should Know
Summary of Cache Systems Every Developer Should Know from ByteByteGo · Published 2023-04-04 · Views: 663,038
This note was generated automatically from the video transcript.
TL;DR
Caching permeates every layer of a modern system—from CPU registers to browsers, CDNs, load balancers, message brokers, distributed stores, and databases. By keeping frequently accessed data close to the consumer, each cache reduces latency, off‑loads downstream resources, and improves overall throughput.
Key Insights
- Hardware caches (L1‑L3, TLB) keep the CPU fed with the hottest data, shrinking memory‑access latency from nanoseconds to a few cycles.
- OS page cache and inode cache turn disk blocks into RAM, turning costly I/O into fast memory reads.
- Browsers, CDNs, and some load balancers cache HTTP responses, turning round‑trip network latency into near‑instant local fetches.
- Message brokers like Kafka persist large on‑disk caches, enabling consumers to replay data according to retention policies.
- Distributed in‑memory caches (e.g., Redis) provide sub‑millisecond key‑value lookups, dramatically faster than relational DB reads.
- Databases layer caching (WAL, buffer pool, materialized views, replication logs) decouples write‑ahead durability from query performance.
- Each cache introduces consistency, eviction, and capacity trade‑offs that must be tuned per workload.
Detailed Breakdown
1. Hardware‑Level Caches
- L1 Cache – Smallest (typically < 64 KB) and fastest; sits inside each CPU core. Stores the most frequently accessed instructions and data.
- L2 Cache – Larger (hundreds of KB) but slower; located on the CPU die or a nearby chip. Acts as a secondary buffer for L1 misses.
- L3 Cache – Even larger (several MB) and shared across cores; bridges the gap between CPU cores and main memory.
- Translation Lookaside Buffer (TLB) – Caches recent virtual‑to‑physical address translations, avoiding page‑table walks for every memory access.
flowchart LR
cpuCore["CPU Core"] --> l1["L1 Cache"]
l1 --> l2["L2 Cache"]
l2 --> l3["L3 Cache"]
l3 --> mem["Main Memory"]
cpuCore --> tlb["TLB"]
tlb --> mem
2. Operating‑System Caches
- Page Cache – Resides in RAM; holds recently read disk blocks. When a process reads a file, the OS first checks the page cache, turning a potential 5‑10 ms disk read into a ~0.1 ms memory read.
- Inode Cache – Stores filesystem metadata (inode structures) to avoid repeated disk seeks for file attributes.
3. Front‑End Caching (Browser → CDN → Load Balancer)
- Browser Cache – On first HTTP request, the server sends
Cache‑Control/Expiresheaders. Subsequent identical requests are served from the local browser store, eliminating network latency. - Content Delivery Network (CDN) – Edge servers cache static assets (images, JS, CSS). If a request misses the edge cache, the CDN fetches from the origin, stores it, and serves future requests directly.
- Load Balancer Cache – Some LBs (e.g., NGINX with
proxy_cache) keep a copy of HTTP responses. This reduces load on backend services for cache‑able endpoints.
sequenceDiagram
participant User
participant Browser
participant CDN
participant LB as LoadBalancer
participant Origin
User->>Browser: GET /static/logo.png
Browser->>Browser: Check local cache
alt Hit
Browser-->>User: Serve from local cache
else Miss
Browser->>CDN: Request /static/logo.png
CDN->>CDN: Check edge cache
alt Hit
CDN-->>Browser: Serve cached asset
else Miss
CDN->>LB: Forward request
LB->>Origin: Fetch asset
Origin-->>LB: Asset
LB-->>CDN: Asset (cache it)
CDN-->>Browser: Asset (cache it)
end
Browser-->>User: Asset
end
4. Messaging & Distributed Caches
- Kafka – Persists messages on disk in a log structure. The log acts as a massive, ordered cache; consumers can read at their own pace, and retention policies (e.g., 7 days) keep data available long after production.
- Redis (or similar) – In‑memory key‑value store. Provides O(1) reads/writes, often used for session data, leaderboards, or as a read‑through cache in front of a slower database.
5. Database‑Level Caching
- Write‑Ahead Log (WAL) – Guarantees durability by writing changes to a sequential log before applying them to the data pages.
- Buffer Pool – In‑memory area that caches frequently accessed pages (B‑tree nodes, rows). Queries hit the buffer pool first, avoiding disk I/O.
- Materialized Views – Pre‑computed query results stored as tables; read queries hit these directly, bypassing expensive joins or aggregations.
- Replication Log – Tracks changes for replica nodes; also serves as a cache for read‑only replicas.
flowchart LR
app["Application"] --> db["Database"]
db --> wal["Write‑Ahead Log"]
db --> buffer["Buffer Pool"]
buffer --> btree["B‑Tree Pages"]
db --> matView["Materialized View"]
db --> replLog["Replication Log"]
Trade-offs and Gotchas
- Staleness vs. Freshness – Aggressive caching reduces latency but can serve outdated data; cache‑invalidation strategies are critical.
- Memory Pressure – Over‑allocating cache (e.g., large Redis cluster) can starve other processes; eviction policies (LRU, LFU) must match access patterns.
- Cache Warm‑up – Cold caches cause initial latency spikes; consider pre‑warming or lazy loading.
- Consistency Overhead – Distributed caches need coherence protocols; network partitions can cause split‑brain scenarios.
- Complexity – Each additional cache layer adds operational complexity (monitoring, metrics, debugging cache misses).
Takeaways
- Map the data flow of your system and identify the hottest read paths; place the smallest, fastest caches (CPU, page cache) closest to the consumer.
- Use HTTP caching headers wisely; a proper
Cache‑Controlpolicy can off‑load billions of requests to browsers and CDNs. - Pair an in‑memory cache (Redis) with a durable store (DB + WAL) to get both speed and reliability.
- Monitor cache hit ratios at every layer; a low ratio often signals mis‑sized caches or poor eviction policies.
- Always design a clear invalidation or expiration strategy to avoid serving stale data.
Glossary
- L1/L2/L3 Cache: Hierarchical CPU caches with decreasing speed and increasing size.
- TLB (Translation Lookaside Buffer): Cache for virtual‑to‑physical address translations.
- Page Cache: OS‑level RAM cache of disk blocks.
- Inode Cache: OS cache of filesystem metadata structures.
- CDN (Content Delivery Network): Distributed edge servers that cache and serve static content close to users.
- Load Balancer Cache: Optional caching performed by a reverse proxy or LB to reduce backend load.
- Write‑Ahead Log (WAL): Sequential log ensuring durability before data pages are modified.
- Buffer Pool: In‑memory cache of database pages used to satisfy queries without disk I/O.
- Materialized View: Pre‑computed result set stored as a table for fast reads.
- Replication Log: Log of changes propagated to replica nodes in a DB cluster.
Leave a comment