Choosing Caching Strategies and Engines for Amazon ElastiCache
This lesson explains how Amazon ElastiCache provides managed in-memory caches that reduce database load and latency, and the trade-offs between caching strategies and the problems caches can cause.
Learning outcomes
After completing this lesson, you will be able to:
- Distinguish lazy loading from write-through caching.
- Explain how TTLs limit stale data.
- Describe how a thundering herd and stale data occur and how to prevent them.
- Choose between the Valkey, Redis OSS and Memcached engines.
Lazy loading vs write-through
Lazy loading and write-through are the two principal caching strategies. They differ in when data is written to the cache.
With lazy loading, also called cache-aside, the application reads from the cache first. On a cache hit, it uses the cached value. On a miss, it reads from the database, writes the result to the cache and returns it. Only data that is actually requested is cached, and if the cache fails, the application still works, only more slowly, by reading from the database. The drawbacks are that the first request for each item is slow, and that a cached value does not change when the database does, so it can become stale.
With write-through, the application updates the cache every time it writes to the database, so cached data is always current and reads rarely miss. The drawbacks are that every write does extra work, and the cache fills with data that may never be read. Items added to the database before the cache existed, or after a cache node was replaced, are still missing, which is why write-through is usually combined with lazy loading. The following table summarises the differences.
The two are often combined, and a TTL on cached items limits both staleness and memory use.
Example. Lazy loading with a 5-minute TTL:
import json, redis
cache = redis.Redis(host=CACHE_ENDPOINT, port=6379, ssl=True)
def get_product(product_id):
key = f"product:{product_id}"
cached = cache.get(key)
if cached:
return json.loads(cached) # cache hit
product = db.fetch_product(product_id) # cache miss: read from the database
cache.setex(key, 300, json.dumps(product)) # keep for 5 minutes
return productProblems caches can cause
Caches can introduce problems of their own if they are not designed carefully. The following list describes two common problems.
- Thundering herd: many requests miss at once, for example when a popular entry expires, and all hit the database. Prevent it with random jitter on TTLs, locking, or pre-warming the cache.
- Eviction: when memory is full, items are removed according to the eviction policy.
Choosing an engine
ElastiCache offers several engines, and the choice depends on whether the cache must survive failures and on the data structures the application needs.
Valkey, an open-source fork of Redis, and Redis OSS are feature-rich in-memory data stores. Each shard has a primary node and up to five replicas, with automatic failover to a replica in another Availability Zone, so the cache stays available when a node fails. Data can be persisted with snapshots. Besides simple keys and values, they provide data structures such as hashes, lists, sets and sorted sets, which make leaderboards and rate limiters straightforward, and publish-subscribe messaging. Cluster mode shards data across several primaries to scale beyond one node.
Memcached is a simpler engine that stores only keys and values. It is multi-threaded and scales out by adding nodes, but it has no replication or persistence, so the data on a failed node is lost. It suits a plain cache whose contents can always be rebuilt from the database. ElastiCache Serverless, available for Valkey, Redis OSS and Memcached, removes node selection entirely and scales capacity automatically. The following table summarises the options.
| Engine | Features | Use for |
|---|---|---|
| Valkey / Redis OSS | Persistence, replication, Multi-AZ failover, sorted sets, pub/sub; cluster mode shards data | Sessions, leaderboards, rich data types, high availability |
| Memcached | Simple, multi-threaded; no persistence or replication | Simple caching that scales out |
| ElastiCache Serverless | Scales automatically with no node types to choose | Caching without managing capacity |
Common uses include caching database query results and storing user sessions, so any application instance can serve any user.
Stale prices after an update
A product service uses lazy loading with a 1-hour TTL. When prices change, customers see old prices for up to an hour.
| Option | Trade-off |
|---|---|
| Shorten the TTL to 1 minute | Fresher data, more cache misses and database load |
| Write-through: update the cache when a price changes | Fresh data; every write touches the cache |
| Invalidate: delete the cache key on update | Next read reloads; simple and fresh |
The team combines lazy loading with invalidation on update and keeps a 1-hour TTL as a safety net. When a flash sale makes one product extremely popular, its key expiring could send thousands of requests to the database at once, so a short random jitter on TTLs spreads expiries out.
Which caching strategy updates the cache on every write but may fill it with data that is never read?
Show answer
Write-through. Lazy loading caches only data that is requested, but it can serve stale data until the entry expires.
Exam Tips
Remember for the exam
- To store user sessions so any instance can serve the user, use ElastiCache (or DynamoDB).
- A real-time leaderboard points to sorted sets in Valkey or Redis OSS.
- Stale data with lazy loading is fixed by adding a TTL or using write-through.
- If the database is overloaded when popular entries expire together, add jitter to the TTLs.
- To cache without managing nodes, use ElastiCache Serverless.