Caching — The Secret Behind High-Performance Backend Systems
From CDN Edge Nodes and DNS to CPU L1/L2/L3, RAM vs Disk, Redis Cache-Aside, Eviction (LRU/LFU/TTL), Database Query Caching, and In-Memory Rate Limiting.
Caching is the fundamental engineering practice of storing a frequently requested subset of data in high-speed storage (RAM/Edge) to avoid repeated expensive computation or disk retrieval. Mastering multi-level caching—from CDNs and DNS resolution to hardware CPU caches, Redis Cache-Aside patterns, eviction policies (LRU/LFU/TTL), and in-memory rate limiting—transforms database bottlenecks into sub-millisecond responses.
1. What is Caching & Why It Exists: Core Mechanics & Mental Model
At its first principles level, Caching is the technique of storing a subset of original data in a high-speed, faster-access storage medium (RAM or Edge PoP) to drastically decrease the time and computational effort required for subsequent retrievals.
01Trigger #1: Expensive Computation
02Trigger #2: Expensive or Large Data Retrieval
Avoiding Repeated Index Ranking
Google SearchWhen millions of users search 'weather in Delhi' or 'cricket score', Google serves pre-computed search result cards from distributed in-memory cache clusters, skipping crawling and ranking pipelines.
Global Edge Content Delivery
Netflix StreamingInstead of streaming 4K video from a central US origin server, Netflix encodes videos into multi-bitrate chunks (1080p, 720p, 480p) and caches popular regional movies at local CDN Edge Nodes (Open Connect).
Trending Topics Precomputation
Twitter / XAnalyzing millions of live tweets for viral trends requires heavy ML processing. Twitter precomputes trends periodically into Redis, allowing millions of timeline refreshes to hit in-memory RAM with zero latency.
// Request 1 (Cache MISS):
GET /api/products/456
1. Check Redis: NOT FOUND (Miss)
2. Query PostgreSQL on NVMe Disk: ~120ms
3. Write to Redis (TTL = 3600s)
4. Return Response// Request 2 (Cache HIT):
GET /api/products/456
1. Check Redis: FOUND (Hit) ~0.8ms
2. Return Response immediately (Bypassing PostgreSQL entirely!)2. Multi-Layer Network & Edge Caching: CDNs and Multi-Level DNS
Caching begins long before a network packet reaches your backend server. Geographically distributed network caches eliminate long-distance speed-of-light latency.
01Content Delivery Networks (CDNs) & Edge Locations
02Why CDNs Cache Popular Subsets, Not Everything
03Multi-Level DNS Caching Architecture
example.com to an IP address without caching would require traversing the global DNS hierarchy on every single HTTP link click. DNS employs a 4-tier caching chain that halts resolution as early as possible.| DNS Cache Layer | Location & Storage | Typical Resolution Latency | Role & Scope |
|---|---|---|---|
| 1. Browser DNS Cache | Client browser memory (Chrome/Firefox) | < 1 ms | Checks if the active browser session has resolved the hostname within the last few minutes. |
| 2. OS DNS Cache | Operating System socket resolver cache | < 2 ms | Maintained by Windows DNS Client / macOS mDNS / Linux systemd-resolved across all local apps. |
| 3. Recursive Resolver Cache | ISP or Public DNS (1.1.1.1, 8.8.8.8) | ~10 – 30 ms | Caches domain records for thousands of neighboring users; queries Root/TLD servers only on miss. |
| 4. Authoritative Name Server | Domain Registrar / Cloudflare DNS | ~50 – 150 ms | The authoritative single source of truth containing official A/AAAA/CNAME records. |
TTL = 3600). Long TTL maximizes cache hits and speeds up page loads, but slows down DNS failover if an IP address changes during server migrations. Short TTL allows fast failover but increases recursive DNS lookup latency.3. Hardware-Level Caching: CPU L1/L2/L3 & RAM vs. Disk
The principle of caching is universal—it is implemented in silicon inside modern CPUs as well as across server memory hierarchies.
| Memory Layer | Physical Location | Typical Size | Access Latency | Relative Speed Factor |
|---|---|---|---|---|
| CPU L1 Cache | Directly on CPU Core | 32 KB – 64 KB per core | ~0.5 – 1 nanosecond | Instantaneous (1x) |
| CPU L2 Cache | Dedicated Core Cache | 512 KB – 1 MB per core | ~3 – 5 nanoseconds | ~5x slower than L1 |
| CPU L3 Cache | Shared across all Cores | 16 MB – 64 MB shared | ~10 – 20 nanoseconds | ~20x slower than L1 |
| System RAM (Memory) | DDR4 / DDR5 Modules | 16 GB – 512 GB | ~60 – 100 nanoseconds | ~100x slower than L1 |
| NVMe SSD (Disk Storage) | PCIe Flash Bus | 500 GB – 8 TB | ~50 – 150 microseconds | ~1,000x slower than RAM! |
4. Software Caching Strategies: Cache-Aside vs. Write-Through
Selecting how the application coordinates reads and writes between the cache and the primary database is critical for balancing performance against data freshness.
Populate on Demand
Strategy 1: Cache-Aside (Lazy Caching)The application checks the cache first. On a cache hit, it returns data immediately. On a cache miss, it reads from the database, writes the fetched record into the cache with a TTL, and returns it. Most popular and resilient pattern for read-heavy REST APIs.
Simultaneous Dual-Write
Strategy 2: Write-ThroughWhenever data is created or updated, the application writes simultaneously to both the primary database and the cache. Guarantees the cache is always 100% fresh, but adds write latency and populates keys that may never be read again.
| Architectural Dimension | Cache-Aside (Lazy Caching) | Write-Through Caching |
|---|---|---|
| Cache Population Trigger | On Read Miss (GET request) | On Write Mutation (POST/PUT/DELETE) |
| Read Latency | Sub-millisecond on hits; penalty on initial miss | Always sub-millisecond (cache is pre-warmed) |
| Write Latency | Minimal (writes go straight to DB) | Higher (must wait for DB + Redis write confirmation) |
| Memory Efficiency | High: Only actually requested data occupies RAM | Lower: Caches written data that might never be queried |
| Staleness Risk | Possible if DB is modified without cache eviction | Zero: Cache is updated synchronously with DB |
5. Cache Eviction Policies & Memory Management (LRU, LFU, TTL)
Because cache storage (RAM) is strictly bounded, when the cache reaches its memory limit (e.g. maxmemory 2gb), the engine must execute an Eviction Policy to discard old keys to accommodate new incoming data.
01LRU (Least Recently Used) — Recency-Based
02LFU (Least Frequently Used) — Frequency-Based
03TTL (Time-To-Live / volatile-ttl) — Expiration-Based
04noeviction (Strict Fail-Safe)
SET, HSET) return an OOM (Out of Memory) error while read operations continue to work.6. Practical Backend Use Cases & Real-World Patterns
In production backend engineering, caching solves four critical scalability bottlenecks:
E-Commerce Product Catalogs
1. Database Query CachingComplex SQL queries with multiple table JOINs, aggregations, and category filtering (e.g. Amazon product pages) are cached in Redis. Millions of users read the cached JSON, protecting the PostgreSQL database from crashing during Black Friday sales.
User Authentication Stores
2. Session ManagementAfter a user logs in, their profile, permissions, and session metadata are stored in Redis (sess_a8b9c0...). Verifying user identity on every API request becomes a 1ms RAM lookup rather than a disk query.
Third-Party Rate Limit & Cost Defense
3. External API CachingCalling external APIs (e.g. Weather API, Stripe FX rates, AI models) consumes API quota and incurs monetary billing. Caching API responses with a 1-hour TTL cuts external API costs by over 95%.
DDoS & Abuse Mitigation
4. Rate LimitingUsing high-speed Redis atomic increments (INCR + EXPIRE) to track IP request counts (e.g. 50 req/sec) without burdening persistent relational databases with high-frequency counter writes.
UPDATE users SET request_count = request_count + 1 WHERE ip = '...' to PostgreSQL on every incoming HTTP request, you generate massive disk write contention and lock bottlenecks. In-memory Redis INCR handles 100,000+ atomic operations per second with microsecond latency.7. Multi-Language Code Implementations: Cache-Aside & Rate Limiting
Production-ready implementations of the Cache-Aside Pattern with fallback database lookups and Redis Rate Limiting Middleware across TypeScript, Go, and Rust:
8. The Fundamental Tradeoffs & The Cache Invalidation Dilemma
Phil Karlton famously observed: 'There are only two hard things in Computer Science: cache invalidation and naming things.' Understanding when NOT to cache is as critical as knowing how to cache.
| Scenario | Should You Cache? | Architectural Rationale |
|---|---|---|
| Read-Heavy Data (Read >>> Write) | ✅ Highly Recommended | Huge performance payoff; database load drops by 90%+. |
| Expensive Computations / Aggregations | ✅ Highly Recommended | Saves CPU/GPU resources by computing once and reusing results. |
| External API Responses with Rate Limits | ✅ Highly Recommended | Protects against third-party billing costs and rate limit exhaustion. |
| Rapidly Mutating Data (Write-Heavy) | ❌ Avoid / Be Cautious | High mutation rate constantly invalidates cache, causing cache churn and low hit ratio. |
| Strict Consistency Requirements (Banking Balances) | ❌ Avoid Caching Authoritative State | Serving stale financial balances or inventory stock causes double-spending and data corruption. |
INCR/EXPIRE) for high-throughput rate limiting instead of relational DB writes.Multi-Tier Cache & Eviction Engine
Directly inside browser RAM. Eliminates network roundtrips completely.
Geographically close edge server. Serves static chunks and images.
Stores hot precomputed trends, user sessions, and database query results.
Authoritative disk storage. High latency sequential scan or index lookup.