Caching — Speed Up करा
Cache, Redis आणि CDN
Cache म्हणजे frequently accessed data जवळ (fast storage मध्ये) store करणे जेणेकरून database ला वारंवार query करावं लागणार नाही. Database query 100ms, cache hit 1ms — 100x faster!
Marathi Analogy
Library मधून book आणायला 10 मिनिटे लागतात. पण तुमच्या desk वर book ठेवलं तर 1 second. Cache म्हणजे desk — frequently needed गोष्टी जवळ ठेवा!
Cache कुठे कुठे असतो?
- ▸Client-side Cache — Browser मध्ये (localStorage, HTTP cache headers)
- ▸CDN Cache — Edge servers वर static files (images, JS, CSS)
- ▸Application Cache — Server मेमरीमध्ये (in-process, Redis)
- ▸Database Cache — Query results cache (MySQL query cache)
Redis — Most Popular Cache
Redis with Node.js
const redis = require('redis');
const client = redis.createClient();
// Cache-aside pattern
async function getUserById(userId) {
const cacheKey = `user:${userId}`;
// 1. Cache मध्ये बघा
const cached = await client.get(cacheKey);
if (cached) {
return JSON.parse(cached); // Cache hit!
}
// 2. Cache miss — DB query
const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
// 3. Cache मध्ये store करा (TTL: 1 hour)
await client.setEx(cacheKey, 3600, JSON.stringify(user));
return user;
}Cache Eviction Policies
- ▸LRU (Least Recently Used) — सर्वात कमी recently used data काढा — most common
- ▸LFU (Least Frequently Used) — सर्वात कमी वेळा accessed data काढा
- ▸TTL (Time To Live) — X seconds नंतर automatically expire
- ▸Write-through — data write होताना DB आणि cache दोन्ही update
- ▸Write-behind — cache update, DB asynchronously update होतो
CDN — Content Delivery Network
CDN म्हणजे जगभरात distributed edge servers चं network. तुमची Mumbai website चा static content (images, videos, CSS) Amsterdam, Singapore, New York च्या servers वरही cache होतो. User त्याच्या जवळच्या server वरून content मिळवतो — latency कमी होतो.
YouTube चे videos Cloudflare/Akamai CDN वर cache असतात. तुम्ही Pune मधून बघताना video Singapore server वरून नाही, Mumbai edge server वरून येतो!
✅ Key Points — लक्षात ठेवा
- ▸Cache = fast storage मध्ये frequent data store
- ▸Redis — in-memory key-value store, most popular cache
- ▸Cache-aside pattern — most common strategy
- ▸TTL — data stale होण्यापासून वाचवतो
- ▸CDN — global static content delivery