caching-layer-placementCaching Strategies & Placement — Speed of Light at the Data Layer
Even with Sharding and Replication, disk I/O takes 5ms to 50ms. Placing an in-memory caching tier like Redis in front of your database serves 95%+ of queries in <1ms directly from RAM.
In-Memory Caching Architecture & Strategies
Master the memory hierarchy, read/write caching patterns, eviction algorithms, and the 3 classic cache failure disasters.
1. First Principles: The Latency Numbers Every Engineer Must Know
Why does caching make systems blindingly fast? Because reading from RAM is orders of magnitude faster than reading from Disk or Network.
2. The 4 Core Read & Write Caching Patterns
How should your application coordinate writes and reads between the cache and the primary database?
• Write: App writes to DB, then deletes/invalidates the cache key.
✅ Pros: Resilient — if cache dies, app still reads from DB. Only caches requested data.
⚠️ Cons: Three network round trips on cache miss (Cache check → DB read → Cache write).
• When data is written, the Cache synchronously writes to the DB before confirming success.
✅ Pros: Zero stale data; cache is always in sync with DB.
❌ Cons: Higher write latency because every write must complete both in Cache and DB.
• Cache periodically batches and flushes writes to the DB in the background.
✅ Pros: Blazing fast write performance. Ideal for write-heavy apps (e.g. tracking video view counts, real-time analytics).
🚨 Danger: If the cache server crashes before flushing to DB, data is permanently lost.
• Only when that data is read later does it enter the cache.
✅ Pros: Prevents cache flooding for data that is written once and rarely read (e.g. archival logs, legal contracts).
3. Visualizing Cache-Aside: Hit vs. Miss Request Flows
Watch the live query routing below: Cache Hits resolve instantly from RAM in <1ms, while Cache Misses query the database and backfill the cache.
4. Cache Eviction Policies & Invalidation: Update vs. Delete
Memory is finite. When Redis runs out of RAM, it must evict older keys to make room for new ones.
TTL = 3600s). Guarantees eventually consistent data even if invalidation logic fails.Always DELETE the cache key (cache.del(key)), never UPDATE it!
If two concurrent requests (Request A and Request B) update the database at the same time, network delays can cause Request A's cache update to arrive after Request B's cache update, leaving permanently corrupt/stale data in Redis. Deleting the key forces the next read to fetch the latest truth from the database cleanly.
5. The 3 Classic Cache Disasters (Interview Gold)
In high-scale production, three specific failure modes can bring down entire data infrastructures. Here is how they happen and how senior engineers prevent them:
The Attack: A malicious bot or bug requests millions of non-existent IDs (e.g. GET /user/-9999). Because the key does not exist in Redis, every request misses cache and hits the database directly, overloading the DB.
NULL value with a short 60-second TTL.The Scenario: A viral breaking news article receiving 100,000 requests/sec has its cache key expire at 12:00:00. At that exact millisecond, all 100,000 requests miss cache simultaneously and rush to query the database to rebuild the cache. The database immediately dies.
SETNX) so only one worker queries the DB to rebuild cache while all other requests wait or receive stale data.The Scenario: At midnight, an e-commerce platform caches 500,000 products with a fixed TTL = 2 hours (7200s). At exactly 2:00:00 AM, all 500,000 keys expire simultaneously. An avalanche of requests crashes the database.
TTL = 7200 + random(0, 600). This scatters key expiration smoothly over a 10-minute window.6. Caching Patterns Comparison Matrix
Quick reference guide for System Design Interviews:
| Pattern | Cache-Aside | Write-Through | Write-Back | Write-Around |
|---|---|---|---|---|
| Read Performance | Fast (on Hit) | Fast (always Hit) | Fast (always Hit) | Fast (after 1st read) |
| Write Latency | Low (Writes to DB) | High (Writes to both) | Ultra Low (<1ms RAM) | Normal (DB only) |
| Data Consistency | Eventual (via TTL/Del) | Strong (always in sync) | Weak (lagged flush) | Eventual |
| Data Loss Risk | None (DB is primary) | None | High (if Cache crashes) | None |
| Best Used For | General Web, User Profiles | Financial, Core Metadata | Analytics, View Counters | Logs, Write-Once Data |
7. Interactive Caching Scenario Quiz
Test your caching engineering intuition:
Build Your Cache-Aside Architecture
Design an in-memory caching topology: Route user traffic through the App Server to an in-memory Redis Cache for instant reads, with fallback and persistence to the Primary Database.
Task: Cache-Aside Layer Placement
Drag components to arrange them freely, and click two nodes to connect them.