Lets assume a toy store web site has cache system that has cahced the product catalog
If the product catalog is cached, you must ensure cache consistency when the catalog is updated. This is known as cache invalidation or cache update, and it’s one of the hardest problems in caching.
✅ Ways to Keep Cache in Sync When Product Catalog Updates:
🔄 1. Write-through Cache
How it works: Write to both the database and the cache simultaneously.
Pros: Always in sync.
Cons: Slightly slower write operations.
function updateProduct(productId, data):
database.update(productId, data)
cache.set("product:" + productId, data)
🧹 2. Cache Invalidation (on Update/Delete)
How it works: Invalidate (delete) the cache entry when the DB is updated.
Pros: Ensures fresh data on next read.
Cons: Next read will have to re-fetch from DB (cache miss).
function updateProduct(productId, data):
database.update(productId, data)
cache.delete("product:" + productId) // Invalidate
📦 3. Event-based Cache Update
How it works: Emit an event when products are updated. A listener updates or invalidates the cache.
Pros: Decouples logic; scales better in distributed systems.
Cons: More complex (needs message broker like Kafka, RabbitMQ)
⏱️ 4. Time-based Expiry (TTL)
How it works: Let cache entries expire after a short time (e.g., 5 minutes).
Pros: Simple to implement.
Cons: Might serve stale data for a short while.
🧠 Best Practice: Combine Methods
For a toy store, you might:
Use write-through cache for product edits via admin panel.
Use TTL for less critical items like "top 10 products."
Invalidate cache for specific product IDs when updates happen.
Rebuild full catalog cache periodically or via admin trigger.
No comments:
Post a Comment