ElastiCache & caching strategies
Add a cache layer and choose between Redis and Memcached.
By Invicly Tech, , in AWS Solutions Architect – Associate. About 12 minutes to read.
In short
ElastiCache provides managed in-memory caches using Valkey, Redis OSS or Memcached. Caching cuts database load and latency for repeated reads. Lazy loading fills the cache on misses, while write-through updates the cache on every write.
Explained simply
A cache is a small, very fast store that keeps copies of data you read often. Reading from memory takes well under a millisecond, while a database query might take 5 to 50 milliseconds and uses database CPU. If 90 percent of reads come from the cache, the database sees only one read in ten.
Amazon ElastiCache runs in-memory caches for you. You choose an engine: Valkey or Redis OSS (feature-rich, can replicate and fail over) or Memcached (simple and multi-threaded). AWS handles the servers, patching, monitoring and replacing failed nodes.
The hard part of caching is not speed but freshness. When data changes in the database, the cached copy is now old, or stale. Every caching strategy is an answer to one question: when do we put data into the cache, and when do we throw it away?
Caches work best for data that is read far more often than it changes: product pages, user profiles, settings, results of expensive queries, and login sessions. They help less for data that changes on every request or must always be exactly current, like a bank balance during a transfer.
Press Play on a diagram to walk through it one step at a time.
- Application to ElastiCache: GET user:421GET user:42
- ElastiCache to Application: Cache miss2Cache miss
- Application to Database: SELECT user 423SELECT user 42
- Database to Application: Row returned4Row returned
- Application to ElastiCache: SET user:42 with TTL5SET user:42 with TTL
- Replication and Multi-AZ failover
- Persistence and backups
- Rich data types, sorted sets
- Pub/sub, leaderboards, sessions
- Simple key-value strings
- Multi-threaded
- No replication or persistence
- Easy horizontal sharding
- Serverless
- No nodes to size
- Pay per GB stored and requests
- Valkey or Redis OSS, cluster mode off
- One shard
- Primary plus up to 5 replicas
- Valkey or Redis OSS, cluster mode on
- Many shards by hash slot
- Scales memory and writes
- Memcached
- Independent nodes
- Client spreads the keys
- No replication
- App to Database: UPDATE price of product 71UPDATE price of product 7
- Database to App: OK2OK
- App to Cache: SET product:7 new value, TTL 3003SET product:7 new value, TTL 300
- App to Cache: Later: GET product:74Later: GET product:7
- Cache to App: Hit: fresh value5Hit: fresh value
In depth
Lazy loading vs write-through in practice
With lazy loading (cache-aside), the app checks the cache first and only on a miss reads the database and stores the result. Only data someone asked for gets cached, and losing a cache node just means more misses for a while. The cost: every miss takes three trips (cache, database, cache), and data can be stale until its TTL ends.
With write-through, the app writes to the database and then updates the cache in the same code path. Reads are nearly always fresh hits, but you also cache data nobody reads, and a new or replaced node starts empty until writes refill it. Real systems usually combine them: write-through for data read soon after it is written, lazy loading for everything else, and a TTL on every key as a safety net. A simple, popular variant is to delete the key on every write and let the next read reload it.
- Filled on a read miss
- Only requested data is cached
- Can be stale until the TTL ends
- An empty cache only means misses
- Filled on every write
- Cache stays fresh
- Also caches data nobody reads
- A new node starts empty
TTLs, eviction and the thundering herd
A TTL (time to live) makes a key expire after a set time, for example 300 seconds for a product page. Short TTLs mean fresher data but more misses. Add some random jitter, such as 300 seconds plus up to 60 more, so thousands of keys written together do not all expire at the same moment.
When memory is full, the engine evicts keys according to the maxmemory-policy setting. In ElastiCache for Valkey and Redis OSS the default is volatile-lru, which removes the least recently used keys that have a TTL. If a very popular key expires, hundreds of requests can miss together and all hit the database; this is called a thundering herd or cache stampede. Fixes include a short lock so only one request rebuilds the value, refreshing hot keys before they expire, or serving the old value while one worker refreshes it.
Valkey and Redis OSS features that matter
Valkey is an open-source fork of Redis, and ElastiCache offers both as compatible engines, with Valkey priced lower. Beyond plain strings they offer hashes, lists, sets, sorted sets for leaderboards, streams, pub/sub, and atomic counters with INCR. That makes them useful for sessions, rate limiters and simple queues, not only caching.
For availability, each shard has one primary and up to 5 replicas, with Multi-AZ automatic failover to a replica. Cluster mode enabled splits data across many shards by hash slot, so memory and write capacity can grow beyond one node. ElastiCache Serverless removes node sizing and bills for data stored and requests processed. Turn on encryption in transit and authentication (AUTH tokens, user-based access control or IAM). The default port is 6379 for Valkey and Redis OSS and 11211 for Memcached.
Memcached: when simple wins
Memcached stores only strings (blobs) by key, with no replication, no persistence and no backups. Each node is independent, and the client library spreads keys across nodes, so adding nodes adds memory and throughput. It is multi-threaded, so one large node can use many CPU cores well.
If a node fails, its keys are simply gone and the app refills them from the database. That is fine for a pure cache of easily rebuilt data, such as rendered HTML fragments or query results. It is not fine for sessions, counters or anything you cannot lose. On the exam, words like sorted sets, pub/sub, persistence, Multi-AZ failover or backups point to Valkey or Redis OSS; a plain, multi-threaded, simple object cache points to Memcached.
Where else to cache on AWS
ElastiCache is only one layer. CloudFront caches whole HTTP responses at edge locations near users, which is often the biggest win for static files and public API responses. API Gateway REST APIs can cache responses per stage. DAX caches DynamoDB reads in microseconds. RDS read replicas are not a cache, but they absorb read load in a similar way.
Pick the layer closest to the user that still gives correct results. A product image belongs in CloudFront, a user's cart belongs in Valkey, and a hot DynamoDB item may only need DAX. Be careful caching personal data at the edge: if the cache key is wrong, one user's page can be shown to another.
- 1Browser cache
Cache-Control headers, nothing leaves the device
- 2CloudFront edge
Static files and public responses near users
- 3API Gateway cache
Per-stage response cache for REST APIs
- 4ElastiCache
Sessions, query results, computed objects
- 5DAX or read replicas
Take read load off the main database
- 6Database
The source of truth
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Compare Redis and Memcached~40m
- 2Apply lazy loading and write-through caching~40m
- 3Choose ElastiCache for a scenario~40m
Key points
- Lazy loading caches only requested data but serves stale data until TTL expires.
- Write-through keeps the cache fresh but writes data that may never be read.
- Always set a TTL to bound staleness and memory use.
- Pick Valkey or Redis when you need HA, persistence or sorted sets.
Key terms
Tap a card to flip it. 0/5 known
Examples
Cache-aside for product pages in Python
Product pages are read thousands of times per minute but prices change a few times a day. Step 1: on each read, try the cache; on a miss, load from the database and store the result with a TTL of 5 minutes plus random jitter. Step 2: when a price changes, update the database and delete the cached key, so the next read loads the new price. Here db stands for your own database access code, and CACHE_ENDPOINT is the cluster's primary endpoint.
import json, random, redis
r = redis.Redis(host="CACHE_ENDPOINT", port=6379, ssl=True)
def get_product(pid, db):
key = f"product:{pid}"
cached = r.get(key)
if cached:
return json.loads(cached) # hit
row = db.fetch_product(pid) # miss: ask the database
r.set(key, json.dumps(row), ex=300 + random.randint(0, 60))
return row
def update_price(pid, price, db):
db.update_price(pid, price)
r.delete(f"product:{pid}") # next read reloads itA game leaderboard with sorted sets
A game needs a live top-3 list and each player's rank. A sorted set keeps members ordered by score, so updates and rank lookups are fast even with millions of players. Step 1: add players with ZADD. Step 2: ZINCRBY adds points after each match. Step 3: ZRANGE with REV reads the top players, and ZREVRANK returns a player's position counting from 0 at the top. These commands work the same in Valkey and Redis OSS (REV needs version 6.2 or later).
ZADD leaderboard 1500 alice 2300 bob 1800 carol
ZINCRBY leaderboard 400 alice # alice now has 1900
ZRANGE leaderboard 0 2 REV WITHSCORES # bob 2300, alice 1900, carol 1800
ZREVRANK leaderboard alice # 1 (second place)Quick reference
- Lazy loading: read cache; on a miss read the DB and SET with a TTL
- Write-through: update the cache every time you write the database
- Always set a TTL, and add random jitter so keys don't expire together
- ElastiCache default eviction for Valkey and Redis OSS: volatile-lru
- Ports: 6379 for Valkey and Redis OSS, 11211 for Memcached
- Need failover, backups, sorted sets or pub/sub? Valkey or Redis OSS, not Memcached
- One Valkey or Redis OSS shard: one primary plus up to 5 replicas
- Cache static content in CloudFront first; use ElastiCache for app data
Common mistakes
- Caching without TTLs and serving stale data forever.
- Choosing Memcached for session data that must survive a node failure.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run Valkey locally in Docker and try SET with a TTL, GET and TTL.
- Exercise 2medium
Measure the speedup of caching: time 100 calls of a slow function with a lazy-loading cache in front of it.
- Exercise 3hard
Create an ElastiCache for Valkey replication group with one replica and Multi-AZ, then trigger a failover and watch the roles change.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between Valkey and Redis on ElastiCache?
- Valkey is an open-source fork of Redis created in 2024 after Redis changed its license. ElastiCache supports both with the same common commands, and Valkey costs less, so it is the usual choice for new clusters.
- Should I cache everything?
- No. Cache data that is read often and changes rarely, and watch the hit rate. A cache with a low hit rate adds cost and complexity without helping.
- Can I connect to ElastiCache from the internet?
- Not directly. ElastiCache nodes live in your VPC with private IP addresses, so clients must run in the VPC or connect through VPN, Direct Connect or peering.
- Is ElastiCache a database?
- It can hold data like one, but it lives in memory and is mainly designed as a cache. If you need Redis-compatible data that must never be lost, look at Amazon MemoryDB, which stores data durably across AZs.