DEV Community

Wakeup Flower
Wakeup Flower

Posted on

Lazy Loading in ElastiCache

๐Ÿ”น 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):

  1. App requests data โ†’ Check cache first.
  2. If data is in cache (cache hit) โ†’ return it immediately.
  3. 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)