Amazon ElastiCache
Amazon ElastiCache runs managed in-memory data stores: Valkey, Redis OSS and Memcached. Reading from memory takes microseconds instead of the milliseconds a disk-based database needs, so a cache in front of a database makes applications faster and takes load off the database.
Typical uses: caching database query results, user sessions, leaderboards (sorted sets), rate limiting, and pub/sub messaging.
| Valkey / Redis OSS | Memcached | |
|---|---|---|
| Data types | Strings, hashes, lists, sets, sorted sets, streams | Strings only |
| Replication and Multi-AZ failover | Yes | No |
| Persistence / backups | Snapshots | No |
| Multi-threaded | Partially | Yes |
| Typical choice | Most new projects | Simple, horizontally scaled cache |
There is also ElastiCache Serverless, which scales capacity automatically, and Amazon MemoryDB, a Redis-compatible durable database (not just a cache).
aws elasticache create-serverless-cache --serverless-cache-name shop-cache --engine valkey
aws elasticache describe-serverless-caches --serverless-cache-name shop-cache \
--query "ServerlessCaches[0].[Status,Endpoint.Address,Endpoint.Port]"Sample output:
[
"available",
"shop-cache-abc123.serverless.euw1.cache.amazonaws.com",
6379
]Caching strategies
Lazy loading (cache-aside): read from the cache; on a miss, read the database and store the result. Only requested data is cached, but the first read is slow and data can be stale.
Write-through: every database write also updates the cache. Cached data is always fresh, but you cache data that may never be read.
TTL (time to live): give each key an expiry, so stale data disappears on its own. Usually combined with both strategies.
Model: cache-aside with TTL
The clock is simulated (a counter) so the output is deterministic:
class Database:
def __init__(self):
self.rows = {"product:1": "Espresso Beans 24.50", "product:2": "Green Tea 8.90"}
self.queries = 0
def get(self, key):
self.queries += 1
return self.rows.get(key)
class Cache:
def __init__(self):
self.data = {} # key -> (value, expires_at)
def get(self, key, now):
item = self.data.get(key)
if item and item[1] > now:
return item[0]
self.data.pop(key, None)
return None
def set(self, key, value, now, ttl):
self.data[key] = (value, now + ttl)
db, cache = Database(), Cache()
def get_product(key, now, ttl=60):
value = cache.get(key, now)
if value is not None:
return value, "HIT"
value = db.get(key)
cache.set(key, value, now, ttl)
return value, "MISS"
for now, key in [(0, "product:1"), (5, "product:1"), (10, "product:2"), (30, "product:1"),
(61, "product:1"), (62, "product:1")]:
value, status = get_product(key, now)
print(f"t={now:>2}s {key} {status:<4} {value}")
print("database queries:", db.queries, "of 6 requests")t= 0s product:1 MISS Espresso Beans 24.50
t= 5s product:1 HIT Espresso Beans 24.50
t=10s product:2 MISS Green Tea 8.90
t=30s product:1 HIT Espresso Beans 24.50
t=61s product:1 MISS Espresso Beans 24.50
t=62s product:1 HIT Espresso Beans 24.50
database queries: 3 of 6 requests
At t=61 the entry has expired (it was stored at t=0 with a 60-second TTL), so the next read goes to the database again.
Model: what a cache does to latency
With a hit ratio h, average latency is h × cache_latency + (1 − h) × (cache_latency + db_latency) (a miss checks the cache first). Example latencies:
cache_ms, db_ms = 0.5, 12.0
for hit_ratio in (0.0, 0.5, 0.8, 0.95, 0.99):
avg = hit_ratio * cache_ms + (1 - hit_ratio) * (cache_ms + db_ms)
db_load = 1 - hit_ratio
print(f"hit ratio {hit_ratio:>4.0%}: average {avg:5.2f} ms, database handles {db_load:>4.0%} of reads")hit ratio 0%: average 12.50 ms, database handles 100% of reads
hit ratio 50%: average 6.50 ms, database handles 50% of reads
hit ratio 80%: average 2.90 ms, database handles 20% of reads
hit ratio 95%: average 1.10 ms, database handles 5% of reads
hit ratio 99%: average 0.62 ms, database handles 1% of reads
The cache only pays off when the hit ratio is high. With no hits it even adds a little latency (the useless cache check). Cache data that is read often and changes rarely.
Model: a leaderboard with sorted sets
Redis/Valkey sorted sets keep members ordered by score. In Redis you'd write ZINCRBY leaderboard 50 ada and ZREVRANGE leaderboard 0 2 WITHSCORES; here is the same idea in Python:
scores = {}
def zincrby(member, amount):
scores[member] = scores.get(member, 0) + amount
def zrevrange(start, stop):
ranked = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
return ranked[start:stop + 1]
for player, points in [("ada", 50), ("linus", 70), ("grace", 65), ("ada", 30), ("mia", 10)]:
zincrby(player, points)
for rank, (player, score) in enumerate(zrevrange(0, 2), start=1):
print(rank, player, score)1 ada 80
2 linus 70
3 grace 65
Test yourself
Which caching strategy only loads data into the cache when it is requested and missing?
- Write-through
- Lazy loading (cache-aside)
- Write-behind
- Read replicas
Which engine supports replication, Multi-AZ failover and sorted sets?
- Memcached
- Valkey / Redis OSS
- Both
- Neither
What does a TTL on a cache key do?
- Encrypts it
- Makes it expire after a time, limiting staleness
- Replicates it
- Locks it