Skip to main content

Amazon ElastiCache

Core concept: ElastiCache is a managed in-memory data store โ€” dramatically reduces database load and latency.


Redis vs Memcachedโ€‹

FeatureRedisMemcached
Data structuresStrings, Lists, Sets, Sorted Sets, Hashes, StreamsStrings only
Persistenceโœ… RDB snapshots + AOFโŒ
Replicationโœ… Multi-AZ with failoverโŒ
Cluster modeโœ… Sharding across 500 nodesโœ… Multi-threaded
Pub/Subโœ…โŒ
Sorted Setsโœ… (leaderboards)โŒ
Sessionsโœ…โœ…
Use caseMost use casesSimple horizontal scaling
Exam rule

Redis = exam's preferred answer for almost everything:

  • Need persistence โ†’ Redis
  • Need replication/Multi-AZ โ†’ Redis
  • Need session store with HA โ†’ Redis
  • Need leaderboard / sorted data โ†’ Redis
  • Need pub/sub โ†’ Redis

Memcached = simple, multi-threaded, pure caching, no persistence


Caching Strategiesโ€‹

1. Lazy Loading (Cache-Aside)โ€‹

App โ†’ Cache?
โ”œโ”€โ”€ HIT โ†’ Return data โœ…
โ””โ”€โ”€ MISS โ†’ Query DB โ†’ Write to Cache โ†’ Return data
// Spring Boot with Redis (Spring Data Redis)
@Service
public class ProductService {

@Autowired
private StringRedisTemplate redis;
@Autowired
private ProductRepository db;

public Product getProduct(String id) {
String cached = redis.opsForValue().get("product:" + id);
if (cached != null) {
return objectMapper.readValue(cached, Product.class); // Cache HIT
}

Product product = db.findById(id); // Cache MISS โ†’ DB
redis.opsForValue().set( // Populate cache
"product:" + id,
objectMapper.writeValueAsString(product),
Duration.ofMinutes(10)
);
return product;
}
}

Pros: Only caches requested data, resilient to cache failures
Cons: Cache miss penalty (3 round trips), possible stale data

2. Write-Throughโ€‹

Write โ†’ Update DB โ†’ Update Cache

Pros: Cache always fresh, no stale reads
Cons: Write penalty, unused data wastes cache memory

3. Session Storeโ€‹

// Spring Session with Redis โ€” distributed sessions
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800)
public class SessionConfig {}

// In application.properties:
// spring.session.store-type=redis
// spring.data.redis.host=your-elasticache-endpoint

All sessions stored in Redis โ†’ horizontally scalable stateless app servers.


TTL (Time-To-Live)โ€‹

// Set key with 5-minute TTL
redis.opsForValue().set("rate-limit:user-123", "100", Duration.ofMinutes(5));

// TTL expires โ†’ key deleted โ†’ no memory leak

Cluster Modesโ€‹

ModeDescription
Redis StandaloneSingle node, no HA
Redis with ReplicasPrimary + up to 5 read replicas, Multi-AZ
Redis Cluster ModeSharding โ€” data split across multiple shards, each with replicas

Securityโ€‹

  • Encryption in-transit: TLS
  • Encryption at-rest: KMS
  • AUTH: Redis token-based auth
  • VPC: Deploy inside VPC โ€” not publicly accessible

DAX vs ElastiCacheโ€‹

DAXElastiCache
Works withDynamoDB onlyAny database/API
SetupReplace DynamoDB client with DAX clientManual caching logic
ConsistencyEventually consistent for readsYou control
Use caseDrop-in DynamoDB cacheGeneral-purpose cache

๐Ÿงช Practice Questionsโ€‹

Q1. An application needs a caching layer with automatic failover across Availability Zones. Which ElastiCache option provides this?

A) Memcached with multiple nodes
B) Redis with a primary node only
C) Redis with Multi-AZ and at least one replica
D) Memcached with Multi-AZ

โœ… Answer & Explanation

C โ€” Redis supports Multi-AZ with automatic failover. When the primary fails, a replica is promoted. Memcached doesn't support replication or failover.


Q2. A gaming app needs a real-time leaderboard sorted by score. Which cache data structure is ideal?

A) Redis String
B) Redis List
C) Redis Sorted Set
D) Memcached

โœ… Answer & Explanation

C โ€” Redis Sorted Sets (ZADD, ZRANGE, ZRANK) are purpose-built for leaderboards โ€” elements sorted by score, O(log N) inserts and range queries.


Q3. An application's RDS database is under heavy read load. The team adds ElastiCache with lazy loading. A user updates their profile and reads it โ€” they get the old data. What happened?

A) ElastiCache replication lag
B) Stale cache โ€” lazy loading doesn't update cache on writes
C) RDS Multi-AZ failover
D) Cache TTL expired

โœ… Answer & Explanation

B โ€” Lazy loading only populates the cache on reads โ€” writes go directly to the database. The cache has the old value until TTL expires or the key is explicitly invalidated. Fix: also update/invalidate the cache key on writes, or use write-through.


๐Ÿ”— Resourcesโ€‹