πŸ—„οΈ 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:

  1. App checks the cache for the required data.

  2. If cache hit β†’ return the data immediately.

  3. 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

TypeWhat It StoresExample
Query result cacheFull SQL result setsSELECT queries
Object/Entity cacheApp-level data objectsORM entities (Hibernate, Sequelize)
Key-value cacheCustom app dataproduct_42 β†’ { id: 42, name: "Shoes" }
Materialized viewsPrecomputed query resultsStored 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

PatternHow It Works
Read-throughApp reads from cache; on miss, fetches from DB and stores in cache.
Write-throughApp writes to cache and DB simultaneously.
Write-behindApp 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.