Caching interview question · Most asked

Explain the main caching patterns: cache-aside, read-through, write-through and write-behind.

Summary

Cache-aside: the application reads the cache, and on a miss loads from the database and populates the cache. Read-through: the cache itself loads missing data. Write-through: writes go to the cache and the store synchronously. Write-behind: writes go to the cache and are flushed to the store asynchronously.

Longer Answer

Cache-aside is the most common (Redis + app code) because it's simple and the cache only holds requested data; the app invalidates or updates the key on writes. Write-through keeps cache and store consistent at the cost of write latency. Write-behind gives fast writes but risks data loss if the cache fails before flushing, so it's used for counters or analytics, not money.

Code Example

def get_product(product_id: int) -> dict:
    key = f"product:v2:{product_id}"
    if (cached := redis.get(key)) is not None:
        return json.loads(cached)
    product = db.fetch_product(product_id)          # miss → source of truth
    redis.set(key, json.dumps(product), ex=300)      # populate with TTL
    return product

def update_product(product_id: int, data: dict) -> None:
    db.update_product(product_id, data)
    redis.delete(f"product:v2:{product_id}")         # invalidate after the write

Key Points

  • Cache-aside: app-managed, most common
  • Read-through: cache loads on miss
  • Write-through: synchronous dual write
  • Write-behind: async, risk of loss

Comparison / Tradeoffs

Pattern Consistency Write latency Typical use
Cache-aside Eventual (invalidate) Low General reads
Write-through Strong-ish Higher Read-after-write needs
Write-behind Weak Lowest Counters, analytics

More most-asked Caching questions

← All Caching questions