TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท caching ยท redis ยท valkey ยท memcached ยท spring

Amazon ElastiCache

AWS's managed in-memory cache, running Valkey, Redis OSS or Memcached inside your VPC, either as node-based clusters you size (with shards, replicas and Multi-AZ failover) or as ElastiCache Serverless that scales itself. MemoryDB is the durable sibling for when the data must not be lost.

16 min6 animations

๐Ÿ“š Builds on๐Ÿ“‹ Distributed caching๐Ÿ˜๏ธ Amazon VPC: subnets, route tables and security groups๐ŸŽฝ Redis and Valkey๐Ÿซ Redis Cluster

๐Ÿ–จ๏ธ Cheat sheet

An agency runs the express counter

Omar runs a busy hardware shop. Everything lives in the big storeroom at the back, and every trip there takes a while. So he wants an express counter at the front, with the things people ask for most within arm's reach.

He could hire clerks, build the counter and cover for sick days himself. Instead he hires an agency that runs express counters for shops. A service like that is called a managed cache.

When a customer wants blue paint, Omar looks at the counter first. If it's not there, he walks to the storeroom, brings it back and leaves some on the counter for the next customer. Most customers are then served in a blink.

The agency does the staffing: it sets the counter up, swaps in better tills at a quiet hour Omar picked, and sends a fresh clerk the moment one drops out. Omar still decides what goes on the counter and for how long.

The counter is only ever a quick copy. If a clerk drops out and nobody else had their shelf, that shelf starts empty, and Omar walks to the storeroom again until it fills back up. Nothing is really lost, because the storeroom still has everything.

The agency offers two styles of counter. On the usual plan, a plain grab-and-go shelf is simple and quick, and one clerk can serve many customers at once, but there is no standby and no photo of the shelf. A full counter can also keep lists and tallies, have a standby clerk and be photographed each night. Most shops pick the full counter.

A managed in-memory cache

Amazon ElastiCache runs an in-memory key-value engine for you. You get an endpoint inside your VPC and talk to it with the engine's normal protocol and client library. AWS provisions the nodes, patches the engine in a maintenance window you choose, detects failed nodes and replaces them. You still choose what to cache, the keys and TTLs, and how the app behaves on a miss (see Distributed caching, and Redis and Valkey for the engine itself).

Three engines are available:

EngineWhat you get
ValkeyThe Linux Foundation's open-source fork of Redis. Same protocol and commands, so Redis clients work. AWS prices it lower than the other engines
Redis OSSThe open-source Redis engine, with the same data structures, replication and cluster mode
MemcachedA simple, multithreaded key-value cache. Node-based Memcached clusters have no replicas, no failover and no backups; nodes are independent and the client spreads keys across them

Pick node-based Memcached only when you need plain get/set caching of opaque values, want to use many cores per node, and can lose any node's data at any time. Pick Valkey (or Redis OSS) when you need data structures (hashes, sorted sets, streams), replication with automatic failover, backups, or pub/sub. (Serverless Memcached does replicate across AZs and take snapshots, but still has no data structures.) At its launch AWS priced Valkey 20% lower than the other node-based engines and 33% lower on Serverless, so new Redis-style caches usually start on Valkey.

Treat the cache as disposable. A node replaced without a replica comes back empty, so every read path must fall back to the source of truth, and the database must survive the extra load while the cache warms up.

The agency runs the counter5 steps
๐Ÿง”Omar๐Ÿง‘โ€๐Ÿ’ผExpress counter๐Ÿ—„๏ธ Storeroom๐ŸขThe agency
Press play and watch it happen!

Choose the clerks, or let the agency decide

With the usual plan, Omar tells the agency how many clerks he wants and how big each one's shelf is. He pays for them by the hour, busy or not. If a crowd arrives, he must ask for more clerks, and in a quiet week he pays for clerks standing around.

The agency also has an "as many as needed" plan, called serverless. Omar talks to one front desk. Behind it, the agency watches the queue and adds clerks when a crowd arrives and sends them home when it's quiet. It also keeps copies of every shelf in three separate halls, so one hall losing power doesn't empty the counter. Omar pays for the shelf space he uses and for each item handed over, not for clerks.

Node-based clusters or ElastiCache Serverless

Node-based clusters are the classic model. You pick a node type (memory, vCPUs, network), the number of shards and replicas, the engine version and the subnets, and pay per node-hour whether the nodes are busy or idle. You scale by changing the node type (vertical) or adding shards and replicas (horizontal); ElastiCache can also auto-scale shards and replicas on cluster-mode-enabled clusters.

ElastiCache Serverless (Valkey, Redis OSS, Memcached) has no nodes to size. You create a cache, get an endpoint, and AWS adds and removes capacity as traffic and data grow and shrink. Data is stored redundantly across three Availability Zones with a 99.99% availability SLA, and connections require TLS. You pay for data stored (GB-hours) and for ECPUs (ElastiCache Processing Units): a simple GET or SET costs about 1 ECPU per kilobyte transferred, and heavier commands cost more. You can set maximum limits on storage and ECPUs to cap the bill. Serverless Valkey has a minimum billed storage of 100 MB per cache, against 1 GB for the other engines.

Node-basedServerless
CapacityYou choose node types, shards and replicasAWS scales it
BillingPer node-hourGB-hours stored plus ECPUs
Multi-AZIf you place replicas in other AZsAlways
FitsSteady, predictable load; full control of settingsSpiky or unknown load; least operations

A steady, heavy workload is often cheaper on right-sized (or reserved) nodes; spiky or new workloads are usually simpler and cheaper on Serverless.

The "as many as needed" plan4 steps
๐Ÿข The agency's clerks๐Ÿง”Omar๐Ÿ›Ž๏ธFront desk๐Ÿง‘โ€๐Ÿ’ผClerk 1
Press play and watch it happen!

Splitting the counter into sections

One clerk's shelf only holds so much. When Omar's counter gets too full, the agency splits it into sections, and each section is called a shard. Every item gets a fixed number worked out from its name, and each section looks after a range of those numbers.

A board at the door lists which section has which numbers. Omar reads the board once, keeps a copy in his pocket, and then goes straight to the right section each time.

When the shop grows, the agency opens a new section and moves some numbers over to it while the shop stays open. If Omar goes to the old section for something that moved, the clerk says "that's moved to section 3". Omar updates his copy of the board and goes there.

Cluster mode disabled or enabled

Valkey and Redis OSS node-based clusters come in two shapes:

  • Cluster mode disabled: one shard. One primary node holds all the data and up to five read replicas copy it. You scale up by choosing a bigger node type. Clients use the primary endpoint for writes and the reader endpoint for reads spread over the replicas.
  • Cluster mode enabled: the keyspace is split across shards (node groups), from 1 up to 500 (500 needs Valkey 7.2 or later, or Redis OSS 5.0.6 or later). Each shard has a primary and 0 to 5 replicas, and the default quota is 90 nodes per cluster, which you can ask AWS to raise. Every key maps to one of 16,384 hash slots (CRC16 of the key), and each shard owns a range of slots (see Redis Cluster).

With cluster mode enabled, clients connect to the configuration endpoint, fetch the slot map and then talk to each shard's primary directly, so they must speak the cluster protocol (Lettuce, Jedis's cluster client, Valkey GLIDE). Adding or removing shards is online resharding: ElastiCache migrates slots while the cluster serves traffic. A client that asks the old shard for a moved key gets a MOVED reply and refreshes its map.

Multi-key commands (MGET, transactions, Lua scripts) only work when all keys are in the same slot. Put a hash tag in the key, such as cart:{ana}:items and cart:{ana}:total, to force related keys together.

Shards and the configuration endpoint5 steps
๐Ÿง”Omar๐ŸชงBoard at the door๐Ÿง‘โ€๐Ÿ’ผSection 1๐Ÿ‘ฉโ€๐Ÿ’ผSection 2
Press play and watch it happen!

A standby clerk in the other hall

Each section has a main clerk who takes every change ("we now have red paint here"). Next to them, ideally in the shop's other hall with its own power, stands a replica: a standby clerk who copies each change a moment after the main clerk has said "done".

Two signs hang at the door. The main sign always points at whoever is the main clerk now. The pick-up sign sends customers who only want to look something up to a standby clerk, which spreads out the crowd.

If the main clerk drops out, the agency turns the standby into the new main clerk within seconds, and turns the main sign to point at them. Omar follows the same sign as before. But anything the old clerk said "done" to and hadn't yet passed on is gone, so Omar fetches it from the storeroom again. Then the agency sends a new standby to the hall that lost its clerk.

Replicas and Multi-AZ failover

Each shard has one primary (reads and writes) and up to five read replicas. Replication is asynchronous: the primary acknowledges a write before the replicas have it, so replicas can lag slightly, and a failover can lose the last writes that hadn't replicated yet.

With Multi-AZ enabled and replicas in other Availability Zones, ElastiCache detects a failed primary and promotes the replica with the least replication lag, usually within seconds. It then moves the primary endpoint's DNS name to the new primary, so apps using that endpoint don't change their configuration, and it creates a replacement replica in the failed node's AZ. Clients must reconnect and re-resolve DNS, and in-flight commands fail.

EndpointShapeUse
Primary endpointCluster mode disabledAll writes; reads that must see the latest write
Reader endpointCluster mode disabledReads spread across replicas (may be slightly stale)
Configuration endpointCluster mode enabledDiscover the slot map; the client then picks nodes
Node endpointsBothSpecific nodes; these don't move on failover, so avoid them in app config

Replicas are not backups: a FLUSHALL or a bad DEL replicates within milliseconds. For recovery from mistakes, ElastiCache can take daily automatic backups (Valkey and Redis OSS node-based clusters, and Serverless caches) kept in S3 for a retention period of up to 35 days, plus manual snapshots. A restore creates a new cache.

Replicas and Multi-AZ failover5 steps
๐Ÿฌ North hall๐Ÿฌ South hall๐Ÿง”Omar๐ŸชงMain sign๐ŸชงPick-up sign๐Ÿง‘โ€๐Ÿ’ผMain clerk๐Ÿ‘ฉโ€๐Ÿ’ผStandby clerk
Press play and watch it happen!

When the counter is the only record

Some shops start keeping things only at the counter, with no copy in the storeroom: loyalty-card points, say. Then a lost "done" isn't a small delay any more. Ana's five new points would simply vanish.

For that, the agency has a sister service called MemoryDB. Its clerks write every change into a logbook, and copies of the logbook sit in several halls. Only when the change is in the logbooks does the clerk say "done". It's a little slower to change things, but just as quick to look things up.

If the main clerk drops out, the standby reads the logbook and carries on with every single change, so nothing anyone was told "done" about is ever lost.

Durability: backups, and MemoryDB

ElastiCache is a cache: it assumes the data also lives somewhere else. Asynchronous replication and daily backups mean acknowledged writes can be lost in a failover or a restore, which is fine for cached copies and wrong for a system of record.

Amazon MemoryDB is the durable alternative, compatible with Valkey and Redis OSS. It keeps the whole dataset in memory but writes every change to a distributed Multi-AZ transaction log before acknowledging it. Reads stay in the microseconds; writes take single-digit milliseconds because they wait for the log. On failover, a replica replays the log, so no acknowledged write is lost. AWS positions it as a primary database (sessions, carts, leaderboards, counters that must not reset), and sometimes as a replacement for a database plus a separate cache.

ElastiCacheMemoryDB
RoleCache in front of a databasePrimary database
Write acknowledgedWhen the primary has it in memoryWhen the Multi-AZ log has it
FailoverCan lose recent writesNo acknowledged writes lost
Write latencySub-millisecondSingle-digit milliseconds

If losing the last moments of writes is unacceptable, use MemoryDB, or keep the data in a database and cache it.

MemoryDB's Multi-AZ transaction log4 steps
๐Ÿ“’ The logbooksLogbook, north hall012Logbook, south hall012Logbook, east hall012๐Ÿง”Omar๐Ÿง‘โ€๐Ÿ’ผMain clerk๐Ÿ‘ฉโ€๐Ÿ’ผStandby clerk
Press play and watch it happen!

Locked doors and a password

The agency puts Omar's counter in the shop's staff-only back room, not out on the street, so strangers can't even reach it. A door guard holds a list of who may come in, called a security group: Omar and his helpers are on it, nobody else is.

Every word between a helper and the counter goes in a sealed envelope, so nobody on the way can read it, and the shelves are locked at night. At the counter, each helper must give the right password, or show a staff badge from head office, before the clerk hands anything over.

Omar's helpers keep a card that names the board at the door (or the main sign), never a particular clerk, and says "always use sealed envelopes". Then they never have to change it when a clerk is swapped.

Network, encryption, auth and Spring

ElastiCache nodes live in subnets of your VPC (picked with a subnet group) and have no public IP addresses (see Amazon VPC). A security group on the cache allows inbound TCP 6379 for Valkey and Redis OSS (plus 6380 for a Serverless cache's reader port, or 11211 for Memcached) only from your application's security group.

  • Encryption in transit (TLS) protects traffic between clients and nodes and between nodes. Serverless always requires it; on node-based clusters you turn it on, and the client must connect with TLS.
  • Encryption at rest covers data on disk during sync, swap and backup, and backups in S3, using ElastiCache's default key or your own customer managed KMS key. It is always on for Serverless.
  • Authentication for Valkey and Redis OSS, with TLS on: a single AUTH token (a shared password), or role-based access control (users and user groups, each user with an access string limiting its commands and keys), or IAM authentication (Valkey 7.2+ or Redis OSS 7.0+), where the client signs a token with its IAM credentials that's valid for 15 minutes and the connection is closed after 12 hours unless re-authenticated.

From Spring Boot with Lettuce, point at the configuration endpoint for cluster mode enabled, turn on TLS and let Lettuce refresh its slot map after resharding and failover:

1spring:2  data:3    redis:4      cluster:5        nodes: orders-cache.abc123.clustercfg.euw1.cache.amazonaws.com:63796      ssl:7        enabled: true8      username: orders-app          # an RBAC user9      password: ${CACHE_PASSWORD}   # from Secrets Manager, never in the repo10      timeout: 500ms11      lettuce:12        cluster:13          refresh:14            adaptive: true          # refresh the slot map on MOVED and reconnects15            period: 30s16  cache:17    redis:18      time-to-live: 10m

For cluster mode disabled, set spring.data.redis.host to the primary endpoint instead of cluster.nodes. To send reads to replicas, use a RedisStaticMasterReplicaConfiguration with the primary endpoint and the reader endpoint, plus ReadFrom.REPLICA_PREFERRED (for cluster mode enabled, the customizer below is enough):

1@Bean2LettuceClientConfigurationBuilderCustomizer readFromReplicas() {3    return builder -> builder.readFrom(ReadFrom.REPLICA_PREFERRED);4}5 6@Service7class PriceService {8    private final PriceRepository repository;9 10    PriceService(PriceRepository repository) {11        this.repository = repository;12    }13 14    @Cacheable(cacheNames = "prices", key = "#sku")   // runs only on a cache miss15    public Price priceFor(String sku) {16        return repository.findBySku(sku).orElseThrow();17    }18}

Keep the command timeout short and treat cache errors as misses (a CacheErrorHandler that logs and carries on), so a failover or a slow node degrades to database reads instead of failing requests.

Inside the VPC, with TLS and auth4 steps
๐Ÿšช Staff-only back room๐Ÿ•ต๏ธStranger๐Ÿง”Omar๐Ÿ’‚Door guard๐Ÿง‘โ€๐Ÿ’ผExpress counter
Press play and watch it happen!

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐Ÿ”—Design a URL shortenerShort codes for long links, and billions of redirects.practice problem

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Amazon ElastiCache, told the same way as the story.
  1. The counter clerk drops out and the agency sends a fresh one with an empty shelf. What should Omar do?
  2. Omar's main clerk says done to the glue, then drops out before the standby copied it. What happens after the standby takes over?
  3. Omar wants to keep loyalty points only at the counter, with no copy anywhere else. Which service fits?
  4. The agency opens a new section and moves the nails there. Omar asks the old section with his old copy of the board. What happens?
  5. Omar's helpers can't reach the counter at all; their requests just hang. What is the likely cause?
Answer every question to check.Passing marks Amazon ElastiCache as done.
Got the hang of Amazon ElastiCache? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿงฐ Caching with Redis, Valkey and HazelcastStep 7 of 8

โ† Previous on the path๐Ÿ“ป Redis Streams and pub/subNext on the path โ†’๐Ÿ Hazelcast