What drives ElastiCache cost, and why is it usually oversized?
Elasticache cost optimization means paying for the cache capacity your workload needs and no more. On a provisioned cluster, most of the bill comes from one multiplication:
monthly node cost = node-hour price × shards × (1 + replicas per shard) × hours in month
Two smaller items sit on top of that. Backup storage is charged once snapshots exceed the included allowance. Data transfer is charged when application clients in one Availability Zone read from or write to a node in another.
AZ-a AZ-b AZ-c
Shard 1 [Primary] ----> [Replica] [Replica]
Shard 2 [Replica] [Primary] ----> [Replica]
Shard 3 [Replica] [Replica] [Primary]
^ app clients in AZ-a calling shard 2's primary cross an AZ boundary
Every box in that diagram is billed for every hour it runs. Instance size changes the price of each box. Shard and replica counts change how many boxes there are.
Illustrative estimate (assumed numbers, not a benchmark): assume a price of P per node-hour, 3 shards, and 2 replicas per shard. That gives 3 × 3 = 9 billed nodes. Dropping to 1 replica per shard removes 3 nodes, a 33% cut, without touching instance size. Halving the shard count has a similar effect. Replica and shard decisions compound in a way that a single instance-size change does not.
Clusters usually end up oversized for three reasons:
- Teams size for a guessed peak memory figure, then add a safety margin.
- They provision replicas for read scaling that never arrives.
- Nobody revisits the layout after launch.
This section applies to teams running provisioned clusters with steady, predictable traffic.
AZ-a AZ-b AZ-c
+----------+ +----------+ +----------+
Shard 1 | PRIMARY |---->| replica | | replica |
+----+-----+ +----------+ +-----+----+
+------------- repl ------------->+
+----------+ +----------+ +----------+
Shard 2 | replica |<----| PRIMARY |---->| replica |
+----------+ +----------+ +----------+
+----------+ +----------+ +----------+
Shard 3 | replica | | replica |<----| PRIMARY |
+----+-----+ +----------+ +-----+----+
+<------------ repl --------------+
+----------+ +----------+
| App |== cross-AZ request =>| Shard 2 |
| clients | ($ data transfer) | PRIMARY |
| in AZ-a | | in AZ-b |
+----------+ +----------+
Snapshots ---> backup storage (billed beyond included allowance)
Legend: each box = one node billed for every hour it runs
9 nodes = 3 shards x (1 primary + 2 replicas)
----> replication from primary to replica
====> client request crossing an AZ boundary
A 3-shard cluster with 2 replicas per shard spread across three AZs bills 9 nodes per hour, adds cross-AZ data transfer when clients reach a node in another zone, and adds backup storage once snapshots exceed the included allowance.
How do you measure Redis memory and CPU headroom before resizing?
Start with the engine's own view of memory. Running redis-cli INFO memory on each primary returns three fields that matter most:
used_memoryis what the dataset and its overhead currently occupy.used_memory_peakis the high-water mark, which is what you must actually fit.mem_fragmentation_ratiocompares RSS toused_memory. Values well above 1 mean the allocator holds memory the dataset no longer uses.
Size against the peak, not the current reading.
In CloudWatch, DatabaseMemoryUsagePercentage reports usage relative to the memory available to data. That figure excludes what the reserved-memory-percent parameter sets aside. Keep that reservation in place. Replication buffers, copy-on-write pages during snapshots and full resyncs all need RAM outside the dataset, so a node that looks 70% full by nominal RAM may have little real slack.
For CPU, pull EngineCPUUtilization rather than host CPUUtilization, for example with aws cloudwatch get-metric-statistics --namespace AWS/ElastiCache --metric-name EngineCPUUtilization --dimensions Name=CacheClusterId,Value=<node-id> --statistics Maximum --period 60. Redis executes commands on largely one thread. A node with many vCPUs can show low host CPU while that thread is saturated. Adding vCPUs does not help a hot shard. Redistributing keys or adding shards does.
Treat headroom as a deliberate cost. Running near full memory invites evictions, failed snapshots and replicas that cannot complete a sync during failover.
#!/usr/bin/env bash
# Collect memory and CPU headroom data for one Redis primary before resizing.
set -euo pipefail
HOST="my-redis-0001-001.abc123.use1.cache.amazonaws.com" # placeholder endpoint
NODE_ID="my-redis-0001-001" # placeholder node id
START=$(date -u -d '14 days ago' +%Y-%m-%dT%H:%M:%SZ) # GNU date
END=$(date -u +%Y-%m-%dT%H:%M:%SZ)
# 1. Engine view of memory. Size against used_memory_peak, not used_memory.
# Add --tls if in-transit encryption is enabled on the cluster.
redis-cli -h "$HOST" -p 6379 INFO memory \
| tr -d '\r' \
| grep -E '^(used_memory|used_memory_peak|used_memory_rss|mem_fragmentation_ratio|maxmemory):'
# 2. Memory as a share of what is available to data
# (already excludes reserved-memory-percent). Use the maximum, not the average.
aws cloudwatch get-metric-statistics \
--namespace AWS/ElastiCache \
--metric-name DatabaseMemoryUsagePercentage \
--dimensions Name=CacheClusterId,Value="$NODE_ID" \
--start-time "$START" --end-time "$END" \
--period 3600 --statistics Maximum \
--query 'max(Datapoints[].Maximum)'
# 3. CPU of the Redis engine thread, not the host. A hot shard shows up here
# even when host CPUUtilization looks low on a large instance.
aws cloudwatch get-metric-statistics \
--namespace AWS/ElastiCache \
--metric-name EngineCPUUtilization \
--dimensions Name=CacheClusterId,Value="$NODE_ID" \
--start-time "$START" --end-time "$END" \
--period 3600 --statistics Maximum \
--query 'max(Datapoints[].Maximum)'
A script that reads the peak memory and fragmentation from INFO memory, then pulls the 14-day maximum of DatabaseMemoryUsagePercentage and EngineCPUUtilization from CloudWatch for one primary node.
How can you cut memory before cutting nodes?
Shrinking the dataset is cheaper than buying a larger node, and it makes every later sizing decision more accurate.
Find what is actually using memory
Run redis-cli --bigkeys and redis-cli --memkeys against a replica, not the primary. Both use SCAN, so they sample the keyspace without blocking it, but they still add load. Use MEMORY USAGE <key> to check specific candidates, and OBJECT IDLETIME <key> to see how long a key has gone without access. A large key that has been idle for weeks usually comes from an abandoned feature or a job that writes data nobody reads. OBJECT IDLETIME returns an error when the eviction policy is LFU-based, so check that first.
Bound growth
Add TTLs to every key pattern that can grow without limit, such as sessions, rate-limit counters and per-request caches. Then set maxmemory-policy in a custom parameter group, for example with aws elasticache modify-cache-parameter-group and ParameterName=maxmemory-policy,ParameterValue=allkeys-lru. The default volatile-lru only evicts keys that have a TTL. If most keys have no TTL, memory can still fill completely.
Use compact encodings
Many small hashes take less memory than one string key per field, because small hashes are stored in a compact encoding. The thresholds are set by the hash-max-*-entries and hash-max-*-value parameters. Their names vary by engine version, so check the names your engine uses.
The trade-off
Short TTLs and aggressive eviction raise the cache miss rate. Each miss becomes a query against your primary database, which can cost more than the cache memory you freed. Watch hit rate and database load together after every change.
Doing this work first saves engineering time. A node sized for a bounded dataset stays correctly sized, so you avoid resizing again every quarter as unbounded keys grow back.
#!/usr/bin/env bash
# Shrink the dataset before resizing: sample big keys, inspect candidates,
# bound growth with TTLs, then set an eviction policy via a parameter group.
set -euo pipefail
REPLICA="my-cache-ro.example.cache.amazonaws.com" # reader endpoint, not primary
PRIMARY="my-cache.example.cache.amazonaws.com"
PG="my-redis-params" # custom parameter group
# 1. Check the eviction policy first: OBJECT IDLETIME errors under LFU policies.
aws elasticache describe-cache-parameters --cache-parameter-group-name "$PG" \
--query "Parameters[?ParameterName=='maxmemory-policy'].ParameterValue"
# 2. Sample the keyspace with SCAN on a replica (non-blocking, but adds load).
redis-cli -h "$REPLICA" --bigkeys # largest key per type, by element count
redis-cli -h "$REPLICA" --memkeys # largest keys by bytes (redis-cli 6.0+)
# 3. Inspect one candidate: bytes used, seconds since last access, encoding.
KEY="report:2024:full-export"
redis-cli -h "$REPLICA" MEMORY USAGE "$KEY"
redis-cli -h "$REPLICA" OBJECT IDLETIME "$KEY" # weeks idle = likely unused
redis-cli -h "$REPLICA" OBJECT ENCODING "$KEY" # listpack/ziplist = compact
# 4. Bound an unbounded pattern: writes go to the primary.
redis-cli -h "$PRIMARY" EXPIRE "session:7f3a9c" 86400 # 24h session TTL
# Better: set the TTL at write time in application code, e.g. SET k v EX 86400.
# 5. Evict across all keys, not only keys with a TTL (volatile-lru default).
# The group must already be attached to the cluster for this to apply.
aws elasticache modify-cache-parameter-group \
--cache-parameter-group-name "$PG" \
--parameter-name-values "ParameterName=maxmemory-policy,ParameterValue=allkeys-lru"
# 6. After each change, watch the cache hit rate together with primary DB load:
# more evictions and misses mean more queries against the database.
A bash walkthrough that samples large and idle keys on a replica, adds a TTL to an unbounded key, and switches maxmemory-policy to allkeys-lru through a custom ElastiCache parameter group.
Which node family and cluster layout should you choose?
Memory-optimized nodes (the r family) give the most RAM per dollar and suit most caches, because Redis is usually bound by dataset size rather than CPU. General-purpose nodes (m) cost more per GB but add CPU headroom, which helps workloads heavy on Lua scripts, sorted-set operations or TLS. Graviton variants (a g in the type name) usually cost less for similar capacity. Spec sheets do not show how your command mix behaves, so replay production-like traffic in a load test before you switch.
| Option | Fits | Watch for |
|---|---|---|
| Memory-optimized | Large datasets, simple GET/SET | CPU saturation on complex commands |
| General-purpose | CPU-heavy commands, TLS | Higher cost per GB |
| Graviton | Most workloads | Confirm with your own load test |
Cluster mode with several smaller shards can cost less than one large node, because you add memory in smaller steps. The savings depend on even key distribution. A hot key, or a large key, pins its load to one shard, and you end up sizing every shard for the busiest one. Multi-key commands work only when all keys hash to the same slot, so group related keys with hash tags such as {user:42}.
Fewer replicas reduce cost, but they also reduce read capacity and leave less room to absorb a failure. Multi-AZ automatic failover requires at least one replica per shard.
Online resizing and resharding move data while the cluster serves traffic, which adds CPU and network load. Scaling down is riskier than scaling up because it leaves less headroom. Run these changes in a maintenance window.
When should you buy reserved nodes, and when should you avoid them?
…a maintenance window and watch the metrics for a full traffic cycle before you treat the new size as settled. Only then is it time to think about reservations.
A reserved node is a billing commitment, not a different kind of node. You commit to a node type in a region for a fixed term, and in exchange the hourly rate drops. The size of the discount depends on two choices: term length and how much you pay upfront. Longer terms and more upfront payment give deeper discounts but more lock-in. Where size flexibility applies, the discount can cover other sizes within the same node family and region, so a later resize inside that family doesn't waste the commitment. A move to a different family or region is not covered.
That is why you should reserve only the floor: the node count and family your cluster runs at during its quietest steady period after right-sizing. Run any capacity above that floor on demand. If you reserve your peak, you pay for idle commitment during every trough.
| Situation | Reserve? | Why |
|---|---|---|
| Right-sized, stable for months | Yes, the floor | Predictable usage turns the discount into real savings |
| Still tuning memory or shard count | Not yet | The final size is unknown |
| Planned move to a different node family | No | The reservation stays tied to the old family |
| Engine migration or move to Serverless | Check first | Coverage may not carry over |
Confirm current terms, payment options, size-flexibility rules and engine coverage on the AWS ElastiCache pricing pages before you buy.
What are the alternatives: Valkey and ElastiCache Serverless?
Valkey is the open-source fork of Redis OSS, and ElastiCache offers it as an engine alongside Redis OSS. AWS prices Valkey nodes below the equivalent Redis OSS nodes, so the same node count can cost less without any change to sizing. Valkey speaks the same protocol, so most applications reconnect without code changes. Check these before you switch:
- Client libraries: confirm your client and its cluster-mode handling are tested against Valkey, and run your integration tests against a Valkey endpoint.
- Modules and commands: list the commands your application actually issues, using command stats from production. Flag anything module-dependent or newer than the fork point, because those may behave differently or be missing.
- Behavior under load: replay production-like traffic. Compare latency percentiles, eviction behavior and replication lag, not just whether requests succeed.
Serverless changes the billing model. You stop paying for nodes and pay for data stored and for compute consumed, which is measured in ElastiCache Processing Units.
| Factor | Provisioned + reserved | Serverless |
|---|---|---|
| Best fit | Steady, high-throughput traffic | Spiky or unpredictable traffic |
| Cost at sustained load | Lower per unit once reserved | Usage charges add up quickly |
| Cost when idle | You pay for full nodes regardless | Scales down, with a minimum charge |
| Engineering effort | Sizing, resharding, reservation tracking | Little capacity planning |
| Cost predictability | High | Varies with request volume |
Serverless reduces operational cost because nobody spends time on capacity planning or resizing. Provisioned clusters with reserved nodes usually cost less for workloads that run hot around the clock, because the reservation discount applies to capacity you would use anyway.
Illustrative estimate: oversized vs right-sized vs reserved
Illustrative estimate (assumed numbers, not a benchmark). Every rate below is a placeholder chosen to keep the arithmetic readable. None of them is a published AWS price.
Assumed inputs:
- Hours per month: 730
- Large node rate: $0.60/hour
- Medium node rate: $0.30/hour, at half the memory of a large node
- Reservation discount: 35% off the on-demand rate, with no upfront amortization modeled
- Oversized cluster: 4 shards × 2 nodes (1 primary + 1 replica) on large nodes. Peak memory is assumed to sit near 35% of capacity.
- Right-sized cluster: 3 shards × 2 nodes on medium nodes. Peak memory is assumed to sit near 70%, which leaves headroom for failover and fragmentation.
Formula: monthly cost = shards × nodes per shard × hourly rate × hours × (1 − discount)
| Scenario | Nodes | Calculation | Monthly cost |
|---|---|---|---|
| Oversized, on-demand | 8 large | 8 × $0.60 × 730 | $3,504.00 |
| Oversized, reserved | 8 large | 8 × $0.60 × 730 × 0.65 | $2,277.60 |
| Right-sized, on-demand | 6 medium | 6 × $0.30 × 730 | $1,314.00 |
| Right-sized, reserved | 6 medium | 6 × $0.30 × 730 × 0.65 | $854.10 |
The second row explains the order of operations. Reserving the oversized cluster still costs more than running the right-sized cluster on-demand. It also commits you to that excess capacity for the full term. Right-sizing removes capacity you never needed. Reserving then discounts only the capacity you have confirmed you need.
In this example, right-sizing alone cuts cost by about 62%, and reserving cuts a further 35%. Your results depend on your own utilization data. Before deciding anything, replace the placeholder rates with current pricing for your region, node family and reservation term.
How do you keep ElastiCache right-sized over time?
Sizing drifts as traffic, key counts, and TTL policies change, so treat it as a scheduled review rather than a one-off project.
Monthly review per cluster
For each cluster, record three values over the past 30 days:
- Peak
DatabaseMemoryUsagePercentage: use the peak, not the average, because a cache that fills up during a nightly batch job is undersized even if it looks idle at noon. Evictions: a nonzero count on a cluster that should hold its full working set means it is too small or keys lack sensible TTLs.- Peak
EngineCPUUtilization: this reflects the single Redis or Valkey engine thread, which saturates long before host CPU does.
Write the numbers in a shared sheet next to the node type and any reservation end date. Comparing month to month shows trends you would miss in a single snapshot.
Alarms in both directions
Create CloudWatch alarms with aws cloudwatch put-metric-alarm, scoped by the CacheClusterId dimension. Use one set to catch under-provisioning: high memory percentage, any sustained evictions, and high engine CPU. Use a second set to catch waste: low peak memory and CPU across a long evaluation window, routed to a ticket queue rather than a pager. Tune the starting thresholds to your own workload.
Why this saves time
Resizing becomes a planned change made during business hours. Without these checks, it tends to happen as an emergency after an eviction storm, and oversized clusters go unnoticed until someone reads the bill.
Revisiting reservations
Review reservations about a quarter before they expire, and again whenever a resize or node-family migration is planned. Renew only for capacity that has stayed stable across several monthly reviews.
#!/usr/bin/env bash
# Two-direction sizing alarms for one ElastiCache node (CacheClusterId).
# Thresholds are starting points; tune them per workload.
set -euo pipefail
CLUSTER_ID="orders-cache-001" # node-level ID, e.g. a replication group member
PAGER_SNS="arn:aws:sns:us-east-1:123456789012:cache-oncall"
TICKET_SNS="arn:aws:sns:us-east-1:123456789012:cache-capacity-review"
# Under-provisioning: memory stays above 80% for 15 minutes. Routed to the pager.
aws cloudwatch put-metric-alarm \
--alarm-name "${CLUSTER_ID}-memory-high" \
--namespace AWS/ElastiCache \
--metric-name DatabaseMemoryUsagePercentage \
--dimensions Name=CacheClusterId,Value="${CLUSTER_ID}" \
--statistic Maximum \
--period 300 \
--evaluation-periods 3 \
--threshold 80 \
--comparison-operator GreaterThanThreshold \
--treat-missing-data missing \
--alarm-actions "${PAGER_SNS}"
# Idle capacity: memory never exceeds 30% in any hour across a full day.
# Routed to a ticket queue, not the pager, because waste is not an outage.
# 24 periods x 3600 s keeps the evaluation window at 86,400 seconds.
aws cloudwatch put-metric-alarm \
--alarm-name "${CLUSTER_ID}-memory-idle" \
--namespace AWS/ElastiCache \
--metric-name DatabaseMemoryUsagePercentage \
--dimensions Name=CacheClusterId,Value="${CLUSTER_ID}" \
--statistic Maximum \
--period 3600 \
--evaluation-periods 24 \
--threshold 30 \
--comparison-operator LessThanThreshold \
--treat-missing-data notBreaching \
--alarm-actions "${TICKET_SNS}"
Creates a high-memory alarm that pages on-call and a low-memory alarm that opens a capacity ticket for one ElastiCache node; the same pattern applies to Evictions and EngineCPUUtilization.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to elasticache cost optimization, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.