๐ Caching โ Explained Simply
Caching is the process of storing copies of data in a temporary storage location (called a cache) so that future requests for that data can be served faster.
๐ Why Caching?
Fetching data from the original source (like a database, API, or disk) is slow and expensive. Caching avoids this by keeping frequently accessed data in a fast-access layer (usually memory).
๐ง Real-life Example
Imagine youโre Googling โweather in Puneโ:
-
Without cache: It hits the weather server every time you search.
-
With cache: If someone already searched this recently, the result is shown instantly from memory.
๐งฑ Types of Caching
| Type | Where It Happens | Example |
|---|---|---|
| Browser Cache | On the client | Images, CSS, JS files |
| CDN Cache | On edge servers | Cloudflare serving static content |
| Application Cache | In app memory | Storing API responses |
| Database Cache | Beside DB | Redis/Memcached storing query results |
| Operating System Cache | At OS level | File system cache |
๐ How Caching Works (Basic Flow)
User Request
โ
Check Cache โ Hit? โ Serve from cache โ
โ
Miss? โ Fetch from DB/API โ Save in Cache โ Return
๐ ๏ธ Tools Commonly Used
-
Memory-based:
Redis,Memcached -
Browser-level:
LocalStorage,IndexedDB, HTTP headers (Cache-Control) -
CDNs:
Cloudflare,Akamai,Fastly
โ ๏ธ Cache Invalidation โ The Hard Part
Biggest challenge is knowing when to update or delete stale cache. Strategies:
-
Time-Based (TTL): Cache expires after
xseconds -
Manual Invalidate: Clear when data changes (e.g., on DB write)
-
Write-through Cache: Update cache immediately after writing to DB
-
Stale-while-revalidate: Serve stale data while fetching updated data in the background
โ๏ธ Pros vs Cons
โ Pros:
-
Faster performance (lower latency)
-
Reduces backend load
-
Cost-effective at scale
โ Cons:
-
Hard to keep fresh (stale data issues)
-
More system complexity
-
Risk of serving outdated or inconsistent data
๐ฆ When Should You Use Caching?
-
Data is read-heavy
-
Data doesnโt change frequently
-
Performance is critical
-
You want to reduce DB/API costs