Core Module
12 min forge
Caching
Master the art of speed. Learn how to reduce database load and server latency by storing frequently accessed data in memory.
β‘ Caching: The Need for Speed
Caching is the process of storing copies of data in a temporary storage location (the cache) so that future requests for that data can be served faster.
π‘ The Logic (ELI5)
Think of a Student studying for an exam:
- You have a massive Textbook (The Database).
- It takes a long time to find information in 1,000 pages.
- The Cache is your Cheat Sheet.
- You write down the 10 most important formulas on a small piece of paper.
- When the exam starts, you look at the cheat sheet (Cache) first. It's instant!
- If the formula isn't there, only then do you open the textbook (Database).
π The Deep Dive
Where to Cache?
- Client-side: Browser cache (Session storage, Cookies).
- CDN: Caching static assets (Images, JS, CSS) closer to the user.
- Load Balancer: Caching entire responses at the edge.
- Application-side: In-memory caches like Redis or Memcached.
- Database: Internal query caches.
Key Concepts
- Cache Hit: The data was found in the cache. Fast!
- Cache Miss: The data was not found. We must query the DB and then update the cache. Slow.
- Eviction Policy: When the cache is full, which data do we delete? (Commonly LRU - Least Recently Used).
π― Interview Pulse
The "Invalidation" Nightmare
"There are only two hard things in Computer Science: cache invalidation and naming things." If you update an item in the Database, how do you make sure the Cache doesn't serve the old (stale) data? Strategies:
- TTL (Time to Live): Data expires after X minutes.
- Write-through: Update both DB and Cache at the same time.
- Cache-aside: Delete the cache entry when the DB is updated.
Popular Tools
- Redis (Supports data structures, persistence, Pub/Sub).
- Memcached (Simple, high-performance key-value store).
Top Tip
Never use Caching for data that changes constantly and must be 100% accurate (e.g., bank account balances) unless you have a very robust invalidation strategy. Use it for data that is "read-heavy" and "write-rare." π