ποΈ Database Caching β Practical Explanation
Database caching is the practice of storing frequently accessed data (like query results or computed values) in a faster, temporary storage layer (like memory) to reduce database load and speed up response times.
βοΈ How It Works
Instead of hitting the DB every time:
-
App checks the cache for the required data.
-
If cache hit β return the data immediately.
-
If cache miss β fetch from DB β store in cache β return to client.
π Example
-
Query:
SELECT * FROM products WHERE id=42 -
First time: Fetches from DB β stores in Redis.
-
Next time: Checks Redis β returns instantly.
π§ Types of Database Caching
| Type | What It Stores | Example |
|---|---|---|
| Query result cache | Full SQL result sets | SELECT queries |
| Object/Entity cache | App-level data objects | ORM entities (Hibernate, Sequelize) |
| Key-value cache | Custom app data | product_42 β { id: 42, name: "Shoes" } |
| Materialized views | Precomputed query results | Stored in DB but refreshed manually or on schedule |
π Tools Used
-
In-memory stores:
-
Redis (most popular)
-
Memcached (simpler, faster for small data)
-
-
ORM-level cache:
-
Hibernate 2nd-level cache
-
Sequelize, Prisma with custom cache layers
-
-
Built-in DB caches:
-
MySQL query cache (deprecated in 8.0)
-
PostgreSQL shared buffers
-
π¦ Cache Patterns
| Pattern | How It Works |
|---|---|
| Read-through | App reads from cache; on miss, fetches from DB and stores in cache. |
| Write-through | App writes to cache and DB simultaneously. |
| Write-behind | App writes to cache β cache writes to DB later (async). |
| Cache-aside (Lazy loading) | App manually checks cache β populates on miss (most common). |
π Invalidation Strategies
To prevent stale data:
-
Time-based: TTL (e.g., 60 seconds)
-
Manual: Delete/Update cache on write
-
Versioning: Use versioned keys (
user_123_v2) -
Event-based: Invalidate when DB change events occur
β Benefits
-
β‘ Up to 10xβ100x faster than DB reads
-
π Less pressure on the DB (especially with read-heavy apps)
-
π Scales better for high-traffic systems
β οΈ Pitfalls
-
β Stale data if cache isnβt updated
-
π Memory overhead
-
π Race conditions when writes happen fast
-
π΅οΈ Hard to debug if data inconsistencies arise
π§ͺ Real-World Example
In an e-commerce app:
-
Product details are cached by product ID in Redis.
-
When inventory or price changes β you invalidate the cache.
-
On next read, data is fresh again.