Placing Caches at Each Layer of an Architecture
This lesson explains how caching serves repeated requests from a faster, closer store at several layers of an architecture, each with its own service and consistency trade-off.
Learning outcomes
After completing this lesson, you will be able to:
- Choose where to cache.
- Distinguish lazy loading from write-through.
- Explain how TTLs and invalidation manage staleness.
- Identify the metrics that measure cache effectiveness.
Where to cache
Caches can sit at several layers, each removing load from the layers behind it. At the edge, CloudFront caches content close to users. Origin Shield adds a further caching layer in one Region, so requests from many edge locations are combined before they reach the origin. At the API layer, API Gateway can cache responses for each REST API stage. An in-memory cache such as ElastiCache, running Valkey, Redis OSS or Memcached, in cluster mode or as ElastiCache Serverless, holds frequently read data for the application.
For DynamoDB, DAX is a write-through cache that is API-compatible with DynamoDB, giving microsecond reads with little code change. The following table summarises the layers.
| Layer | Service |
|---|---|
| Edge | CloudFront, with Origin Shield as an extra layer reducing origin load |
| API | API Gateway caching per REST stage |
| In-memory | ElastiCache (Valkey, Redis OSS, Memcached), cluster mode, ElastiCache Serverless |
| DynamoDB | DAX: write-through cache with microsecond reads, API-compatible with DynamoDB |
Caching strategies
The two caching strategies differ in when data enters the cache. With lazy loading, also called cache-aside, the application reads the cache first and, on a miss, reads the database and stores the result. Only data that is actually requested is cached, but cached data can be stale until its TTL expires, and every miss costs an extra round trip. With write-through, the application updates the cache whenever it writes to the database, so cached data is fresh. The cost is that the cache fills with data that may never be read. The following table summarises the strategies.
| Strategy | Behaviour |
|---|---|
| Lazy loading (cache-aside) | Load on a miss; only requested data is cached, but data may be stale until its TTL expires and each miss costs a round trip |
| Write-through | Update on every write; fresher, but caches data that may never be read |
Most designs combine them: write-through for data that is read soon after being written, lazy loading for the rest, and a TTL on everything as a safety net.
Staleness and invalidation
Every cache serves data that may have changed since it was cached, so the design decides how stale each kind of data may be. A time to live (TTL) set from that tolerance bounds staleness: seconds for prices or stock levels, hours for product descriptions. Reads that must always be current, such as an account balance after a payment, go to the primary data store; with DAX, strongly consistent reads pass straight through to DynamoDB.
For CloudFront, versioned object names, such as a content hash in a file name, are preferred to invalidations: a new name is a new cache entry, whereas invalidations take time to propagate and are charged beyond a free allowance. A popular item that expires can cause a thundering herd, in which many requests miss at once and all hit the database; request coalescing, which lets one request refresh the item while others wait, and staggered TTLs prevent it.
Cache effectiveness
A cache is only valuable if requests are served from it. The cache hit ratio, reported by CloudFront and by ElastiCache as CacheHitRate, shows how much load the cache removes, and evictions show whether it is too small. For CloudFront, cache policies should include only the headers, cookies and query strings that actually change the response, because each additional key splits one cache entry into many and lowers the hit ratio; values the origin needs but that do not change the response are forwarded through an origin request policy instead.
Cache-aside for a product catalogue
Product pages query an Aurora database thousands of times a second, mostly for the same popular items, and the database CPU is at 85%. A cache-aside layer in ElastiCache serves repeated reads and leaves the database for misses and writes:
import json, redis
cache = redis.Redis(host=CACHE_ENDPOINT, port=6379, ssl=True)
TTL_SECONDS = 300
def get_product(product_id):
key = f"product:{product_id}"
cached = cache.get(key)
if cached:
return json.loads(cached) # hit: no database call
product = db.query_one("SELECT * FROM products WHERE id = %s", product_id)
cache.setex(key, TTL_SECONDS, json.dumps(product)) # miss: load and cache with a TTL
return product
def update_price(product_id, price):
db.execute("UPDATE products SET price = %s WHERE id = %s", price, product_id)
cache.delete(f"product:{product_id}") # invalidate so the next read is freshWith a 95% hit rate, the database sees one in twenty of the original reads. The TTL bounds staleness if an invalidation is missed. In front of this, CloudFront caches the rendered pages for anonymous users for 60 seconds, with a cache policy that includes only the query strings that change the page, so most requests never reach the application at all.
How can stale cached data be limited without invalidating the cache on every write?
Show answer
Give entries a TTL so they expire and are reloaded. Write-through or event-driven invalidation keeps critical data fresher.
Exam Tips
Remember for the exam
- For microsecond DynamoDB reads with minimal code changes, use DAX.
- To reduce load on the origin behind CloudFront, enable Origin Shield.
- Lazy loading caches only what is read; write-through keeps the cache fresh on writes.
- Include only necessary keys in CloudFront cache policies to raise the hit ratio.