Skip to content

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 data
SET user:101 <data> EX 3600   -- cache with TTL
GET user:101                   -- cache hit → instant response

Caching Strategies ​

StrategyHow it WorksBest For
Cache AsideApp checks cache first, loads from DB on missMost common, flexible
Write ThroughWrite to cache and DB simultaneouslyRead-heavy, consistency needed
Write BehindWrite to cache first, DB updated later asyncWrite-heavy systems
Read ThroughCache itself fetches from DB on missSimpler app logic

Cache Problems ​

ProblemDescription
Cache Miss StormMany requests hit DB simultaneously on a cold cache
Cache StampedeCache expires → thousands of requests flood DB at once
Cache PenetrationRequests for non-existent data bypass cache, hammer DB
Stale DataCache serves outdated data if not invalidated properly

Redis vs Query Cache ​

Query CacheRedis
LocationInside DB engineExternal server
FlexibilityLimitedHighly flexible
Data TypesQuery results onlyStrings, lists, sets, hashes, etc.
InvalidationAutomatic (on table change)Manual / TTL
ScalabilityPoorExcellent