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:

  1. You have a massive Textbook (The Database).
  2. It takes a long time to find information in 1,000 pages.
  3. The Cache is your Cheat Sheet.
  4. You write down the 10 most important formulas on a small piece of paper.
  5. When the exam starts, you look at the cheat sheet (Cache) first. It's instant!
  6. If the formula isn't there, only then do you open the textbook (Database).

πŸ” The Deep Dive

Where to Cache?

  1. Client-side: Browser cache (Session storage, Cookies).
  2. CDN: Caching static assets (Images, JS, CSS) closer to the user.
  3. Load Balancer: Caching entire responses at the edge.
  4. Application-side: In-memory caches like Redis or Memcached.
  5. 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." πŸš