πΉ 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:123profile β 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)