Skip to content
System Design

7. Caching Strategies Hindi – Redis, CDN & Distributed Cache

June 10, 2026 16 min read

नमस्ते दोस्तों!

स्वागत है The Easy Master पर!

आपने message queues, event-driven architecture seekh liya। अब एक aur important performance tool – Caching। Kya aapki API slow ho rahi hai? Database queries time ले रही हैं? Same data baar-baar fetch ho raha hai?

Yahi problem caching solve karta hai – frequently accessed data को fast storage (RAM) mein store karo, takki next requests fast ho।

Jab maine pehli baar caching implement ki, toh pahle query 200ms लेती थी, cache hit hone ke baad 5ms। Performance 40x better! User experience instantly improve hua। Caching magic hai – but सही strategy चुनना जरूरी है।

इस Caching strategies Hindi article mein main aapko sikhata hoon:

✅ Caching kya hai – types, why cache, trade-offs
✅ Application caching (in-memory) – Node.js, Python example
✅ Distributed caching – Redis, Memcached, why needed
✅ CDN caching – CloudFront, Cloudflare, edge caching
✅ Caching strategies – Cache-aside, Read-through, Write-through, Write-behind
✅ Eviction policies – LRU, LFU, TTL, FIFO
✅ Cache invalidation – The hardest problem in CS
✅ Redis vs Memcached – comparison, use cases
✅ Real-world examples – Twitter, Instagram, e-commerce
✅ Common mistakes aur best practices

Chaliye caching ki duniya mein step rakhte hain! 🚀⚡

1. Caching Kya Hai? – Performance Ka Magic Wand

Caching ek technique hai jisme frequently accessed data को temporary storage (cache) mein rakha जाता है – fast storage (usually RAM) – ताकि future requests fast serve ho सकें।

Simple analogy:
Library की popular books को reference section mein रखना – बार-बार store room (disk/database) जाने की जरूरत नहीं।

Caching layers (user request se database tak):

Caching layers

Personal Experience: Maine ek e-commerce API mein product details database से fetch kar रहा था – 500ms lagta था। Redis में cache kiya, response time 15ms हो गया। User satisfaction बढ़ा और database load 80% कम हुआ।

2. Why Cache? – Benefits and Trade-offs

Benefits of caching:

BenefitExplanation
Lower latencyRAM से data retrieval disk या network से 10-100x fast
Reduced database loadCache hit → DB query avoid
Cost savingsLess DB read operations → smaller DB instance possible
Handle traffic spikesCache absorbs peak load
Improved scalabilityReads scale with cache (horizontal)

Trade-offs / Challenges:

ChallengeExplanation
Stale dataCached data outdated हो सकता है
Cache invalidationJab data change ho, cache update करना complex
Memory costRAM expensive than disk
ComplexityCache invalidation, eviction policies, consistency
Cold startCache empty hone पर many DB hits

Famous quote: “There are only two hard things in Computer Science: cache invalidation and naming things.” – Phil Karlton

3. Types of Caching – Browser, CDN, Application, Database

Cache TypeLocationUse caseExample
Browser cacheClient browserStatic assets (HTML, CSS, JS, images)HTTP cache-control headers
CDN cacheEdge servers (geographically distributed)Static files, API responses (GET)CloudFront, Cloudflare
DNS cacheISP, OS, browserDomain to IP mappingdig TTL
Reverse proxy cacheServer side (before app)HTTP response cachingVarnish, NGINX proxy cache
Application cache (in-memory)App process memorySession data, computed resultsPython dictionary, JS Map
Distributed cacheDedicated cache servers (Redis, Memcached)Shared across app instancesSession store, rate limiting
Database cacheInside DB (buffer pool)Query results, index pagesPostgreSQL shared buffers

Focus of this article: Application cache (in-memory & distributed) and CDN caching.

4. Application Cache – In-Memory aur Distributed

4.1 In-Memory Cache (Single Node)

Cache stored within the application process (memory). Good for: single instance apps, local session data.

Node.js example (Map):

JavaScript
const userCache = new Map();

function getUser(id) {
    if (userCache.has(id)) {
        console.log('Cache hit');
        return userCache.get(id);
    }
    const user = db.query('SELECT * FROM users WHERE id = ?', id);
    userCache.set(id, user);
    return user;
}

Python example (dictionary):

Python
user_cache = {}

def get_user(user_id):
    if user_id in user_cache:
        print("Cache hit")
        return user_cache[user_id]
    user = db.query(f"SELECT * FROM users WHERE id = {user_id}")
    user_cache[user_id] = user
    return user

Limitations:

  • Cache not shared across multiple instances
  • Memory limited to app memory
  • Data lost on app restart

4.2 Distributed Cache (Shared)

Separate cache server (like Redis) shared across all app instances। Good for: multi-instance deployments, microservices, persistent session store.

Why distributed cache? When you have multiple app instances (horizontal scaling), each instance has its own memory – cache misses high। Distributed cache provides a single shared cache layer।

Popular distributed caches: Redis (most popular), Memcached, Hazelcast, Apache Ignite.

5. Distributed Caching – Redis, Memcached

5.1 Redis – Data Structure Store

Redis (REmote DIctionary Server) ek in-memory data structure store hai। Supports strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, geospatial indexes।

Why Redis popular?

  • Data structures – beyond simple key-value
  • Persistence – snapshot to disk, restart पर data recover
  • Replication – master-slave for HA
  • Atomic operations – INCR, LPUSH, SADD
  • Pub/Sub – lightweight messaging
  • Lua scripting – complex operations server-side

Common Redis use cases:

  • Session store
  • Leaderboards (sorted sets)
  • Rate limiting (INCR with TTL)
  • Caching database queries (cache-aside)
  • Real-time analytics
  • Job queues (list)
  • Distributed locks (Redlock)

5.2 Memcached – Simple Key-Value

Memcached simple, high-performance distributed memory caching system। Key-value only, no persistence, no replication (client handles distribution).

Memcached pros:

  • Simpler, easier to scale (client-side sharding)
  • Multi-threaded, very fast
  • Lower memory overhead (for pure key-value)

Memcached cons:

  • No persistence – cache loss on restart
  • No data structures
  • No authentication (older versions)

Recommendation: For most modern apps, Redis is better due to features and persistence। Use Memcached only if you need pure key-value with very high throughput and don’t need persistence/data structures.

6. CDN Caching – Content Delivery Network

CDN (Content Delivery Network) geographically distributed servers that cache static and dynamic content closer to users।

How CDN works:

  1. User requests https://example.com/image.png
  2. DNS points to CDN edge server (closest to user)
  3. If cache hit → serve instantly
  4. If cache miss → fetch from origin (your server), cache, then serve

What to cache on CDN:

  • Static assets: images, CSS, JS, fonts, videos
  • API responses (GET) – with appropriate cache-control headers
  • HTML pages (for static sites)

Popular CDNs:

  • AWS CloudFront (integrated with S3, EC2)
  • Cloudflare (free tier available)
  • Fastly (purge API, real-time logging)
  • Akamai (enterprise)

Cache headers control:

Code
Cache-Control: max-age=3600, public
Cache-Control: no-cache
Cache-Control: private, max-age=60

Pro Tip: For dynamic APIs, use CDN with short TTL (e.g., 10-60 seconds) for frequently read data (news feed, scores, weather).

7. Caching Strategies – Cache-Aside, Read-Through, Write-Through, Write-Behind

StrategyHow it worksBest forProsCons
Cache-Aside (Lazy)App checks cache first; on miss, reads DB, writes cacheMost read-heavy appsSimple, only requested data cachedCache miss latency, stale data possible
Read-ThroughCache sits between app & DB; cache fetches data from DB on missSimilar to cache-aside but abstractionApp code simplerSame as cache-aside
Write-ThroughWrite to cache and DB together (sync)Consistency-critical appsStrong consistencyHigher write latency
Write-Behind (Write-Back)Write to cache first, async write to DBHigh write throughput appsLow write latencyData loss risk if cache crashes before flush

7.1 Cache-Aside (Lazy Loading) – Most Common

JavaScript
async function getUser(userId) {
    // 1. Check cache
    let user = await redis.get(`user:${userId}`);
    if (user) return JSON.parse(user);
    
    // 2. Cache miss – fetch from DB
    user = await db.query('SELECT * FROM users WHERE id = ?', userId);
    
    // 3. Store in cache (with TTL)
    await redis.set(`user:${userId}`, JSON.stringify(user), 'EX', 3600);
    return user;
}

7.2 Write-Through

JavaScript
async function updateUser(userId, data) {
    // 1. Update database
    await db.query('UPDATE users SET ... WHERE id = ?', userId, data);
    
    // 2. Update cache (or delete)
    await redis.set(`user:${userId}`, JSON.stringify(data), 'EX', 3600);
}

7.3 Write-Behind (Write-Back)

JavaScript
async function updateUser(userId, data) {
    // Write to cache immediately
    await redis.set(`user:${userId}`, JSON.stringify(data));
    
    // Queue write to database async
    await queue.add('update-user-db', { userId, data });
}

8. Cache Eviction Policies – LRU, LFU, TTL, FIFO

When cache reaches max memory, old entries need to be removed (evicted).

PolicyHow it worksUse case
LRU (Least Recently Used)Discard least recently accessed itemsGeneral-purpose, good for temporal locality
LFU (Least Frequently Used)Discard least frequently accessed itemsAccess patterns with popularity skew
TTL (Time To Live)Expire after fixed durationTime-sensitive data (news, sessions)
FIFO (First In First Out)Evict oldest cached item (by insertion time)Simple, but less efficient
RandomRandomly evictVery simple, okay for some cases

Redis maxmemory policies:

  • noeviction – return error on maxmemory
  • allkeys-lru – evict LRU from all keys
  • volatile-lru – evict LRU among keys with TTL
  • allkeys-random – random eviction
  • volatile-random – random among keys with TTL
  • volatile-ttl – evict keys with shorter TTL first

Recommendation: Use allkeys-lru with maxmemory and set TTL on keys where freshness matters (volatile-lru).

9. Redis vs Memcached – Kaunsa Choose Karein?

AspectRedisMemcached
Data structuresStrings, hashes, lists, sets, sorted sets, streamsKey-value only
PersistenceYes (RDB snapshots, AOF log)No
ReplicationMaster-slave, Sentinel, ClusterNo (client-side sharding)
Atomic operationsYes (INCR, LPUSH, SADD)Yes (INCR, but limited)
Lua scriptingYesNo
Multi-threadedSingle-threaded (v6+ has I/O threads)Yes (multi-threaded)
Max key size512 MB250 bytes (default)
Max value size512 MB1 MB (adjustable)
Use casesCaching, real-time analytics, sessions, leaderboards, queues, locksPure caching (key-value, high throughput)

Recommendation: Use Redis for almost all use cases due to features, persistence, and active development. Use Memcached only if you need extreme key-value throughput and can’t use Redis.

Redis Cluster provides automatic sharding, high availability, and horizontal scaling (supports up to 1000 nodes). Redis 7.x+ has improved performance and reliability. In 2026, Redis is the de facto standard for distributed caching.

10. Cache Invalidation – The Hardest Problem

Cache invalidation is the process of updating or removing cached data when the underlying data changes.

Why hard? Because you may not know all places where data is cached (different caches, different keys, different patterns).

Strategies for cache invalidation:

StrategyHow it worksProsCons
TTL (Time to Live)Data expires after fixed timeSimple, no coordinationStale data until expiry
Write-throughUpdate cache on every writeStrong consistencySlower writes, cache may have unused data
Write-invalidateDelete cache entry on writeAvoids stale dataNext read will be cache miss (DB hit)
Pattern-based invalidationDelete by key pattern (e.g., user:*)EfficientRequires knowing patterns
Event-driven invalidationService publishes “data changed” event, caches listen and purgeDecoupledComplexity

Practical tip: Use TTL as default, plus explicit invalidation for critical data.

JavaScript
// Invalidation example
async function updateUser(userId, data) {
    await db.update(userId, data);
    // Delete cache entry so next read fetches fresh
    await redis.del(`user:${userId}`);
    // Or update cache with new data (write-through)
}

11. Real-World Examples – Twitter, Instagram, E-commerce

Example 1: Twitter – Feed Caching

  • User timeline – precomputed and cached in Redis (sorted sets)
  • Tweet cache – each tweet object stored in Redis with TTL
  • Home timeline – generated from cache + recent writes
  • Eviction: LRU with TTL for trending tweets

Example 2: Instagram – User Profiles & Media

  • User profile – cached in Memcached (originally, now migrating to Redis)
  • Feed – precomputed timeline using Redis sorted sets
  • Media metadata – CDN for images/videos (CloudFront)
  • Eviction: TTL for profile data (few minutes), LRU for feed

Example 3: E-commerce – Product Details

  • Product catalog – Redis cache-aside (TTL 1 hour)
  • Inventory – cached with short TTL (10 seconds) or write-through
  • CDN – product images, static assets
  • Cache invalidation – on product update, delete product cache key; also purge CDN cache path

12. Common Mistakes (aur Unka Solution!)

MistakeWhy it’s wrongSolution
Caching everythingWastes memory, evicts useful dataCache only frequently accessed, expensive-to-compute data
No TTLStale data lives foreverAlways set TTL unless cache is exact replica (e.g., session)
Using cache as primary databaseData loss risk, no query capabilityCache is ephemeral; always persist to DB
Cache stampede (thundering herd)Cache miss triggers many simultaneous DB queriesUse SETNX for single producer, or request coalescing
No monitoringCache hit ratio unknown, issues unnoticedMonitor hit ratio, memory usage, eviction count
Large cache keysWastes memory, slowUse short keys, avoid serializing huge objects
Local cache for multi-instance appsHigh cache misses, inconsistencyUse distributed cache (Redis)
Ignoring cache warmupCold start floods DBWarm cache on deployment (preload popular data)
No error handling for cache failuresCache down → app failsFallback to DB
Misconfigured eviction policyHot data evictedChoose LRU or LFU based on access pattern

13. Best Practices – Production-Level Tips

✅ Cache only what matters – Profile data, product details, API responses (GET). Don’t cache user-specific personalized data unless necessary.

✅ Set appropriate TTL – Balance freshness vs performance. News: 1-5 mins, product catalog: 1 hour, session: hours/days.

✅ Use cache-aside (lazy loading) as default – Simple, only requested data cached.

✅ Add explicit invalidation for write-heavy data – On update, delete cache key (write-invalidate) or update (write-through).

✅ Use connection pooling for Redis – Reuse connections, avoid overhead.

✅ Monitor cache metrics – Hit rate, miss rate, memory usage, evicted keys. Alert if hit rate drops.

✅ Implement cache warmup on deployment – Preload popular keys to avoid cold start spikes.

✅ Handle cache failures gracefully – If Redis unreachable, fallback to database (but log alert).

✅ Use key naming convention – {service}:{entity}:{id} (e.g., catalog:product:123). Use prefix for easy invalidation.

✅ Avoid large values (>1MB) – Redis performs poorly; store pointers and fetch from object storage.

✅ Use Redis Pipelines for batch operations – Reduce round trips.

✅ Secure Redis – Set password, bind to private network, use TLS.

Personal Experience: One time we had a Redis server with no eviction policy and no TTL on keys. Memory filled up, Redis crashed, and all instances lost cache. Now we always set maxmemory-policy allkeys-lru and TTL on all keys. Also we added monitoring to alert when memory >80%.

14. Resources – Cheat Sheet & Practice Prompts

Redis Commands Cheat Sheet

TaskCommand
Set stringSET user:123 '{"name":"Rahul"}' EX 3600
Get stringGET user:123
Delete keyDEL user:123
Increment counterINCR page_views:home
Add to setSADD tags:product:123 "electronics"
Get set membersSMEMBERS tags:product:123
Add to sorted set (leaderboard)ZADD leaderboard 100 "user123"
Get top 10ZREVRANGE leaderboard 0 9 WITHSCORES
Set hashHSET user:123 name "Rahul" email "r@e.com"
Get hash fieldHGET user:123 name

Cache Strategy Decision Matrix

Read/write ratioConsistency needRecommended strategy
Mostly read (>90%)Low (news, catalog)Cache-aside + TTL
Read-write mixMediumWrite-through or write-invalidate
Write-heavyHigh (inventory)No cache (or short TTL)
Low readAnyDon’t cache

Practice Prompts

Beginner:

  • Node.js + Express app banayein जो Redis से product details fetch kare using cache-aside pattern। TTL set karein 60 seconds। Without Redis, test performance difference।

Intermediate:

  • Rate limiter implement karein using Redis INCR with TTL। Allow 10 requests per minute per IP। If limit exceeded, return 429 status।

Advanced:

  • Leaderboard system implement karein using Redis sorted sets (scores: points, member: user_id)। Support top 10, pagination, and real-time updates। Add Lua script for atomic score update and rank retrieval।

15. FAQ

Q1: Cache aside aur write-through mein kya antar hai?

Cache-aside: app checks cache, on miss reads DB, writes cache। Write-through: app writes to cache and DB together (synchronous), cache always up-to-date。

Q2: Redis aur Memcached mein main difference kya hai?

Redis supports data structures, persistence, replication; Memcached simple key-value, no persistence। Redis recommended for most use cases।

Q3: CDN caching kab use karein?

Static assets (images, CSS, JS) always। For API responses, use CDN only for public, cacheable GET endpoints (news, scores, product catalog) with short TTL。

Q4: Cache invalidation kyun hard hai?

Data changed होने पर पता करना mushkil hai ki कहाँ-कहाँ cached है (different keys, different caches, distributed systems)। Plus consistency vs performance trade-off।

Q5: TTL value kitni rakhein?

Depends on data freshness requirement: product catalog: 1-6 hours, news feed: 1-5 minutes, session: hours/days, user profile: 15-30 minutes।

Q6: Cache hit rate kitni honi chahiye?

Depends, but typically >80% is good। Monitor and adjust caching strategy, TTL, or eviction policy if hit rate low।

16. Conclusion – Ab Aapki Baari!

Bahut badhiya! Aapne aaj seekh liya:

✅ Caching strategies Hindi – complete guide with Redis, CDN, distributed caching
✅ Why cache – benefits, trade-offs, types
✅ Application cache – in-memory vs distributed
✅ Distributed caching – Redis, Memcached, comparison
✅ CDN caching – edge servers, headers, use cases
✅ Caching strategies – cache-aside, read-through, write-through, write-behind
✅ Eviction policies – LRU, LFU, TTL, FIFO
✅ Cache invalidation – hardest problem, strategies
✅ Real-world examples – Twitter, Instagram, e-commerce
✅ Best practices & common mistakes – TTL, monitoring, fallback

Caching performance improvement ka most effective tool hai। Redis aur CDN ke saath aap scalable, fast systems bana sakte ho।

Aapki challenge: Ek simple API implement karo (e.g., product catalog) with Redis cache-aside। Measure response time with and without cache। Then add CDN for static assets (e.g., using CloudFront)。 Share your results in comments!

Next topic kya chahiye?

  • API Gateway (Kong, NGINX, Traefik)?
  • Service Mesh (Istio, Linkerd)?
  • Chaos Engineering – Resilience Testing?

Comment mein batao!

The Easy Master ke saath caching seekhte raho। Happy caching! 🚀⚡

Resources

Additional Resources

Views: 352

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *