Thuta Learning
AWS Advanced
Data at ScaleDevOpsAdvanced

ElastiCache and Caching Strategies

AWS AdvancedLesson 2240 min

What you'll walk away with

  • Explain the trade-offs between cache-aside (lazy loading) and write-through
  • Combine TTLs, invalidation and an eviction policy correctly
  • Explain why cache stampedes happen and prevent them with jittered TTLs and locks
  • Choose between Valkey/Redis OSS and Memcached, cluster mode, Multi-AZ and ElastiCache Serverless

Explain it simply

Explain it simply

Think of the database as a restaurant kitchen: every dish is cooked from scratch, so it is slow. A cache is the counter where popular dishes wait already plated. Most customers grab their order from the counter instantly, and the kitchen only cooks what is missing from it.

Amazon ElastiCache gives you that counter as a managed service: it runs Valkey, Redis OSS or Memcached and returns data from memory in well under a millisecond. The hard part is not the cache itself but the rules: when to replace a dish on the counter and how to remove one that has gone cold.

Problem → Why → Solution

The problem: reading the same rows thousands of times a second

An online shop's product page reads the product row, price and review count from the database on every request. On sale day about a hundred products take most of the traffic and database CPU passes 90%, while the queries keep asking for exactly the same data.

As a quick fix the team adds a dictionary cache inside the application servers. Load drops, but two new problems appear: after a price change the old price shows for days, and every deploy wipes the cache, so all traffic lands on the database at the same moment.

naive_cache.py
cache = {}  # per-process dict: lost on every deploy, different on every server


def get_product(db, product_id):
    key = f"product:{product_id}"
    if key in cache:
        return cache[key]
    product = dict(db[product_id])
    cache[key] = product  # BAD: no TTL, so a stale entry lives forever
    return product


def update_price(db, product_id, price):
    db[product_id]["price"] = price  # BAD: the cached copy is never invalidated

Every cache needs freshness rules

A cache is a copy of data, and every copy can drift from the original. Unless you decide how long to trust it (TTL), what happens when the source changes (invalidation), and what to drop when memory fills up (eviction), the cache returns wrong answers quickly. An in-process cache also differs per server and vanishes on restart, which is why you want a shared cache.

Core concept: strategy, TTL, invalidation, eviction

Cache-aside (lazy loading)
The application checks the cache first. On a miss it reads the database and writes the result into the cache with a TTL. The cache never talks to the database directly.

Cache-aside is the most common pattern. Only data that is actually requested ends up cached, so memory is used well. If the cache node dies the application just gets slower, not broken, because it can still read the database. The cost is that the first request for each key misses and pays three round trips (cache, database, cache).

Write-through updates the cache every time the database is written. The cache is always fresh, but it also fills with data nobody reads, and every write gets slower. In practice most teams use cache-aside combined with invalidation at write time.

The TTL is your last line of defence for freshness: even if an invalidation is missed, stale data lives only until the TTL ends. When data changes, the safer order is to write the database first and then delete the cache key rather than update it. After the delete, the next read refills the key from the database.

Eviction happens when memory is full. In Valkey and Redis OSS, maxmemory-policy decides what goes; the ElastiCache default is volatile-lru (evict the least recently used key among keys that have a TTL). For a pure cache, allkeys-lru is usually the better fit. A rising Evictions metric means the nodes are too small.

StrategyHow it worksTrade-off
Cache-asideFill the cache on a read missLean memory; first read is slow; can go stale
Write-throughUpdate the cache on every writeAlways fresh; slower writes; caches unread data
TTL onlyKeys simply expireSimple; stale until the TTL ends
text
CACHE-ASIDE READ AND WRITE PATHS
--------------------------------
  READ PATH
  app --GET product:p1--> [ cache ]
          |
     hit? +--yes--> return value (no database call)
          |
          no
          v
  app --SELECT--> [ database ]
          |
          +--SET product:p1 EX 300 (+/- jitter)--> [ cache ]
          v
     return value

  WRITE PATH
  app --UPDATE--> [ database ]  then  app --DEL product:p1--> [ cache ]
Mental model: the cache is a copy with a TTL
  1. Read: try the cache first
  2. Miss: read DB, SET with jittered TTL
  3. Write: update DB, then DEL the key
  4. Full memory: eviction policy decides

The database is the source of truth. Design as if the cache could be wiped at any moment.

Pattern: create an ElastiCache Serverless cache

create-cache.sh
# A Valkey serverless cache in two private subnets, with usage limits as a cost guard
aws elasticache create-serverless-cache \
  --serverless-cache-name product-cache \
  --engine valkey \
  --cache-usage-limits 'DataStorage={Maximum=10,Unit=GB},ECPUPerSecond={Maximum=5000}' \
  --subnet-ids subnet-0a1b2c3d4e5f67890 subnet-0f9e8d7c6b5a43210 \
  --security-group-ids sg-0cac4e1a2b3c4d5e6

# Wait for status "available", then read the single endpoint
aws elasticache describe-serverless-caches \
  --serverless-cache-name product-cache \
  --query "ServerlessCaches[0].[Status,Endpoint.Address,Endpoint.Port]"

A serverless cache scales with load without you picking a node type or shard count. --cache-usage-limits caps data storage and ECPUs per second, which keeps the bill bounded. In the security group, allow port 6379 only from the application's security group. Serverless caches always use in-transit encryption, so enable TLS in the client.

A deterministic cache-aside with visible hits and misses

In this example the InMemoryCache class imitates the get, set(ex=..., nx=...) and delete calls of a Valkey/Redis client. In production you swap in redis-py or a valkey-glide client and the pattern stays the same. FakeClock lets us move time by hand, so you can watch a TTL expire without waiting 400 seconds.

The jitter uses a random generator seeded with 42 only so the output is always identical. Do not seed it in production code: the whole point of jitter is that keys expire at different moments.

cache_aside.py
import json
import random


class FakeClock:
    """Simulated time so TTL expiry is deterministic in this demo."""

    def __init__(self):
        self.now = 0


class InMemoryCache:
    """Stand-in for a Valkey/Redis client: get, set(ex=, nx=), delete."""

    def __init__(self, clock):
        self.clock, self.data = clock, {}

    def get(self, key):
        item = self.data.get(key)
        if item is None or item[1] <= self.clock.now:
            self.data.pop(key, None)  # expired keys behave like misses
            return None
        return item[0]

    def set(self, key, value, ex, nx=False):
        if nx and self.get(key) is not None:
            return False
        self.data[key] = (value, self.clock.now + ex)
        return True

    def delete(self, key):
        self.data.pop(key, None)


clock = FakeClock()
cache = InMemoryCache(clock)
rng = random.Random(42)  # seeded only so this demo prints the same numbers
DB = {"p1": {"name": "Mohinga kit", "price": 12}}
stats = {"hit": 0, "miss": 0, "db_reads": 0}
BASE_TTL = 300


def ttl_with_jitter():
    # +/- 10% spreads expiry so hot keys do not all expire together
    return int(BASE_TTL * rng.uniform(0.9, 1.1))


def get_product(product_id):
    key = f"product:{product_id}"
    cached = cache.get(key)
    if cached is not None:
        stats["hit"] += 1
        return json.loads(cached), "HIT"
    stats["miss"] += 1
    stats["db_reads"] += 1
    product = DB[product_id]  # the slow database read
    ttl = ttl_with_jitter()
    cache.set(key, json.dumps(product), ex=ttl)
    return product, f"MISS (cached for {ttl}s)"


def update_price(product_id, price):
    DB[product_id]["price"] = price  # 1. write the database first
    cache.delete(f"product:{product_id}")  # 2. then invalidate the key


def show(t, note=""):
    clock.now = t
    product, status = get_product("p1")
    print(f"t={t:>3}s price={product['price']} {status}{note}")


if __name__ == "__main__":
    show(0)
    show(5)
    show(10)
    update_price("p1", 15)
    show(20, " <- after update")
    show(400, " <- TTL expired")
    print("stats:", stats)

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. Read pathcached = cache.get(key)

    The cache is checked first. On a HIT the value is returned without touching the database.

  2. Fill on miss with jittered TTLcache.set(key, json.dumps(product), ex=ttl)

    On a miss the row is read from the database and stored with a 300-second TTL plus or minus 10%, which is why the output shows different TTLs such as 308s, 271s and 286s.

  3. Invalidate on writecache.delete(f"product:{product_id}")

    When the price changes, the database is written first and then the key is deleted. That is why t=20 immediately returns the new price of 15.

  4. Expiryif item is None or item[1] <= self.clock.now:

    At t=400 the entry's TTL (t=20 + 271s = 291) has passed, so it is a miss and the key is refilled from the database.

You should see
t=  0s price=12 MISS (cached for 308s)
t=  5s price=12 HIT
t= 10s price=12 HIT
t= 20s price=15 MISS (cached for 271s) <- after update
t=400s price=15 MISS (cached for 286s) <- TTL expired
stats: {'hit': 2, 'miss': 3, 'db_reads': 3}
Stampede lock when a hot key expires
  1. Hot key expires; 500 requests miss
  2. Each tries SET lock NX EX 10
  3. One request wins the lock
  4. Winner reads DB and refills the key
  5. Others wait briefly, re-read cache

Request that wins the lock

One database query, cache refilled

Requests that lose the lock

Short sleep, then read the new value

Preventing a cache stampede (thundering herd)

When a hot key expires, hundreds of requests miss at the same moment and send the same query to the database together. The slower the database gets, the longer the key stays empty and the more requests miss, so it feeds on itself. The same thing happens after a deploy or on a new cache node (a cold cache).

  • Jittered TTL: randomise the TTL by about plus or minus 10% so keys filled together do not expire together.
  • Lock (single flight): use SET lock:key value NX EX 10 so only one request reads the database while the rest wait briefly and re-read the cache. Always give the lock an expiry, or a crashed worker leaves the key locked forever.
  • Early refresh: refill hot keys in the background before the TTL ends (for example at 90%), so they are never empty.
  • Cache warming: after a deploy or failover, pre-fill the hot keys before traffic arrives.

Choosing an engine and topology

NeedValkey / Redis OSSMemcached
Data structuresHashes, lists, sets, sorted sets, streamsPlain string key-value
Replication and failoverYes (replicas, Multi-AZ)No; a lost node loses its data
Persistence and backupSnapshotsNone
Scaling outCluster mode shardsAdd nodes; the client spreads keys

Valkey is the open-source fork maintained under the Linux Foundation after the Redis licence change. It is compatible with Redis OSS clients and commands, and ElastiCache prices it lower than Redis OSS, so most new projects choose it. Memcached is multi-threaded and good for a simple object cache, but only pick it if you can live without replication.

In a node-based cluster with cluster mode disabled there is a single shard (one primary plus up to five replicas), so all data must fit in one node's memory. Cluster mode enabled splits the key space across many shards using hash slots, scaling memory and write capacity horizontally; the client must be cluster-aware, and multi-key commands only work on keys in the same shard. With replicas and Multi-AZ enabled, a replica is promoted automatically when the primary fails.

ElastiCache Serverless hands these topology decisions to AWS and replicates data across multiple AZs. You pay for data stored (GB-hours) and ElastiCache Processing Units (ECPUs), which suits spiky traffic, while a steady, heavy load can be cheaper on a node-based cluster.

create-node-based.sh
# Cluster mode enabled: 2 shards x (1 primary + 1 replica), Multi-AZ failover
aws elasticache create-replication-group \
  --replication-group-id sessions \
  --replication-group-description "Session store, 2 shards" \
  --engine valkey \
  --cache-node-type cache.t4g.small \
  --cache-parameter-group-name default.valkey8.cluster.on \
  --num-node-groups 2 \
  --replicas-per-node-group 1 \
  --automatic-failover-enabled \
  --multi-az-enabled \
  --transit-encryption-enabled \
  --at-rest-encryption-enabled \
  --cache-subnet-group-name app-cache-subnets \
  --security-group-ids sg-0cac4e1a2b3c4d5e6
text
CLUSTER MODE ENABLED: 2 SHARDS, MULTI-AZ
----------------------------------------
        cluster-aware client (knows the slot map)
            |                         |
   slots 0-8191                slots 8192-16383
            v                         v
  +-------------------+     +-------------------+
  | shard 1           |     | shard 2           |
  | primary   (AZ-a)  |     | primary   (AZ-b)  |
  | replica   (AZ-b)  |     | replica   (AZ-a)  |
  +-------------------+     +-------------------+
  primary fails -> its replica is promoted automatically

In production

How teams use it in production

A typical e-commerce team keeps the product catalog, prices and session data in a Valkey cache. Keys carry a version prefix such as product:v3:p1. When the cached data format changes, they bump the prefix to v4; old keys are simply never read again and expire through their TTL.

The cache sits in private subnets next to the database, with in-transit encryption on. Lambda functions that use it must run in the VPC and create the client outside the handler. Teams usually aim for a hit rate somewhere around 80-95%, and a falling hit rate tends to mean TTLs are too short or memory is too small.

  • CloudWatch alarms on CacheHitRate, Evictions, CurrConnections, EngineCPUUtilization and DatabaseMemoryUsagePercentage.
  • Failover testing: trigger test-failover and confirm the client reconnects to the new primary.
  • Capacity: on node-based clusters, leave roughly 25% of memory as headroom for replication buffers and snapshots.

Common mistakes

Common mistakes

Caching without a TTL

Invalidation code always misses some path: an admin tool, a batch job, someone fixing a row directly in the database. Without a TTL that stale data stays forever. Give every key a TTL, even if it is hours or days for data that rarely changes.

Updating the cache instead of deleting the key

With two concurrent writes, the database can end up with write B while the cache receives write A last, and the wrong value stays until the TTL ends. Deleting the key makes the next read fetch the correct value from the database.

Using the cache as the primary database

Eviction, node replacement, or asynchronous replication during failover can lose writes. Never keep data you cannot lose, such as orders or payments, only in ElastiCache; keep a durable database as the source of truth. (If you need a durable in-memory database, Amazon MemoryDB is a separate service.)

Giving every key the same TTL

A warm-up script that fills thousands of keys at once with TTL 3600 makes them all expire together an hour later, causing a stampede. Add jitter.

💰 Cost & Cleanup

Node-based clusters are billed per node-hour by node type, and every replica is another node (2 shards x 2 nodes = 4 nodes). ElastiCache Serverless is billed for data stored (GB-hours) and ECPUs, with a minimum data-storage charge. Cross-AZ data transfer can add cost too. Some accounts on the classic free tier get limited micro-node hours, but check your own account's free-tier terms. Delete the caches as soon as the lab is done.

Clean up when you are done

cleanup.sh
aws elasticache delete-serverless-cache --serverless-cache-name product-cache

aws elasticache delete-replication-group \
  --replication-group-id sessions \
  --no-retain-primary-cluster

Mini challenge

Add a stampede lock

Five requests miss product:p1 at the same moment. Add a lock so the database is read only once.

  • The lock key is lock:product:<id>, taken with set(..., ex=10, nx=True)
  • Only the request that wins the lock reads the database and refills the cache
  • Delete the lock after the refill; all five requests must then be served from the cache

Expected: It prints lock winners: ['req-1'], served from cache: 5 of 5, and db reads: 1.

Show hint

NX sets the key only if it does not exist yet and returns False otherwise. Let every request try the lock first, and only the one that got True does the refill.

Show solution
stampede_lock.py
class InMemoryCache:
    """Same stand-in as the lesson example (no clock needed here)."""

    def __init__(self):
        self.data = {}

    def get(self, key):
        return self.data.get(key)

    def set(self, key, value, ex, nx=False):
        if nx and key in self.data:
            return False  # SET ... NX fails when the key already exists
        self.data[key] = value  # (expiry ignored in this short demo)
        return True

    def delete(self, key):
        self.data.pop(key, None)


cache = InMemoryCache()
DB = {"p1": "Mohinga kit"}
db_reads = 0


def try_lock(product_id, caller):
    # Valkey/Redis: SET lock:product:p1 req-1 NX EX 10
    return cache.set(f"lock:product:{product_id}", caller, ex=10, nx=True)


def refill(product_id):
    global db_reads
    db_reads += 1
    cache.set(f"product:{product_id}", DB[product_id], ex=300)
    cache.delete(f"lock:product:{product_id}")


if __name__ == "__main__":
    callers = ["req-1", "req-2", "req-3", "req-4", "req-5"]
    # All five miss at the same moment and race for the lock first.
    winners = [c for c in callers if try_lock("p1", c)]
    print("lock winners:", winners)
    for caller in winners:
        refill("p1")
    # The losers wait briefly, then simply re-read the cache.
    served = [cache.get("product:p1") for _ in callers]
    print("served from cache:", served.count("Mohinga kit"), "of", len(callers))
    print("db reads:", db_reads)

Quick quiz 1 / 3

In a cache-aside app, a product's price changes. Which order of operations is safest?

Quick quiz 2 / 3

Every time a hot homepage key expires, database CPU spikes to 100%. What directly addresses this?

Quick quiz 3 / 3

You need sorted sets for a leaderboard and automatic failover if the primary fails. What do you pick on ElastiCache?

What to remember

  • Cache-aside fills on a miss and write-through updates on every write; most teams combine cache-aside with a delete at write time.
  • Give every key a TTL, and on changes write the database first, then delete the key.
  • Prevent stampedes with jittered TTLs, a lock (SET NX EX) and early refresh.
  • Choose Valkey/Redis OSS for data structures, replication and failover; Memcached for a simple object cache.
  • Cluster mode scales across shards and Serverless hands topology to AWS; never treat the cache as the source of truth.

What is Amazon ElastiCache? — AWS Documentation

Caching strategies (ElastiCache) — AWS Documentation

Caching best practices — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

ElastiCache and Caching Strategies | Thuta Learning