๐น Lazy Loading in ElastiCache
Lazy loading is a caching pattern where data is loaded into the cache only when it is requested for the first time.
Hereโs how it works in Amazon ElastiCache (Redis or Memcached):
- App requests data โ Check cache first.
- If data is in cache (cache hit) โ return it immediately.
- If data is NOT in cache (cache miss) โ
- Fetch it from the database (or another backend).
- Store it in the cache for next time.
- Return it to the application.
๐น Example
Imagine youโre caching user profiles in ElastiCache Redis.
- Request for
user:123
profile โ not in cache โ app queries RDS MySQL โ stores result in Redis โ returns profile. - Next request for
user:123
โ found in Redis (cache hit) โ super fast, no DB query.
๐น Pros & Cons
โ Pros
- Easy to implement.
- Reduces DB load after first access.
- Data is only cached if itโs actually used (no wasted cache space).
โ Cons
- First request = cache miss โ slower, since it hits the DB.
- If cached data expires/evicts โ youโll get another cache miss (but then re-cached).
- Doesnโt proactively refresh cache โ may serve stale data until itโs invalidated.
๐น Related Patterns
- Write-through cache โ Data is written to cache and DB at the same time. Ensures cache is always warm, but writes are slower.
- Lazy loading (cache-aside) โ Cache filled only on reads (what you asked about).
- Write-behind โ App writes only to cache, and cache writes back to DB asynchronously.
โ Lazy loading = Cache-aside pattern โ fetch on demand, populate cache only when needed.
Other loading types
๐น 1. Lazy Loading (Cache-Aside)
- Data loaded into cache only on demand (read).
- If not in cache โ fetch from DB โ put in cache โ return.
- Pros: Only stores whatโs used.
- Cons: First request = slow (cache miss).
๐น 2. Write-Through Caching
- Every time data is written to DB, itโs also written to the cache immediately.
- Cache is always warm, so reads are fast.
- Pros: No cache miss for fresh data.
- Cons: More write latency (every write goes to cache + DB), cache may store rarely used data.
๐น 3. Write-Behind (Write-Back) Caching
- App writes only to cache first.
- Cache writes back to the DB asynchronously later.
- Pros: Super-fast writes, reduced DB load.
- Cons: Risk of data loss if cache node fails before writing to DB; more complex.
๐ Quick Comparison Table
Strategy | Reads | Writes | Cache Warm? | Cons |
---|---|---|---|---|
Lazy Loading | Cache miss โ DB | Normal DB writes | No (loaded on demand) | First request is slow, possible stale data |
Write-Through | Always fast | DB + cache write each time | Yes (always updated) | Higher write latency, may cache unused data |
Write-Behind | Always fast | Cache first, DB async later | Yes (recent writes in cache) | Risk of data loss if cache crashes before DB sync |
Top comments (0)