Appearance
Database Caching (Query Cache, Redis)
Frequently accessed data is stored in a fast-access layer (memory) to avoid hitting the database repeatedly.
Caching Layers
Client
↓
Application Cache (in-memory, e.g. Redis)
↓
Query Cache (inside the DB engine)
↓
Buffer Pool (DB caches disk pages in RAM)
↓
Disk (actual data)1. Query Cache (DB-Level)
Built inside the database engine. Stores the result of a SELECT query and reuses it if the same query is fired again.
- Cache hit → return result directly
- Cache miss → execute query → store result → return
- If underlying table changes → cached result is invalidated immediately
- In write-heavy systems, cache is constantly invalidated → useless overhead
Note: MySQL removed query cache in version 8.0. Works well only for read-heavy, rarely updated data.
2. Redis (Application-Level Cache)
In-memory key-value store used as an external caching layer between your application and the database.
App → Check Redis → HIT → Return data
→ MISS → Query DB → Store in Redis → Return dataSET user:101 <data> EX 3600 -- cache with TTL
GET user:101 -- cache hit → instant responseCaching Strategies
| Strategy | How it Works | Best For |
|---|---|---|
| Cache Aside | App checks cache first, loads from DB on miss | Most common, flexible |
| Write Through | Write to cache and DB simultaneously | Read-heavy, consistency needed |
| Write Behind | Write to cache first, DB updated later async | Write-heavy systems |
| Read Through | Cache itself fetches from DB on miss | Simpler app logic |
Cache Problems
| Problem | Description |
|---|---|
| Cache Miss Storm | Many requests hit DB simultaneously on a cold cache |
| Cache Stampede | Cache expires → thousands of requests flood DB at once |
| Cache Penetration | Requests for non-existent data bypass cache, hammer DB |
| Stale Data | Cache serves outdated data if not invalidated properly |
Redis vs Query Cache
| Query Cache | Redis | |
|---|---|---|
| Location | Inside DB engine | External server |
| Flexibility | Limited | Highly flexible |
| Data Types | Query results only | Strings, lists, sets, hashes, etc. |
| Invalidation | Automatic (on table change) | Manual / TTL |
| Scalability | Poor | Excellent |