90% request đọc cùng một dữ liệu → DynamoDB bill tăng, latency tăng. Giải pháp: Redis cache. ElastiCache = Redis managed: auto-failover, backup, scaling. Mình từng gặp trường hợp allkeys-lru evict nhầm session data, phải chuyển sang volatile-lru, mất 1 đêm debug.
import Redis from "ioredis";
const redis = new Redis({
host: "myapp-redis.xxxxxx.apse1.cache.amazonaws.com",
port: 6379,
tls: {},
retryStrategy: (times) => Math.min(times * 50, 2000),
});
// Cache-aside: check cache → miss → read DB → write cache
async function getProduct(id: string) {
const cached = await redis.get(`product:${id}`);
if (cached) return JSON.parse(cached);
const { Item } = await ddb.send(
new GetCommand({ TableName: "products", Key: { PK: `PRODUCT#${id}` } })
);
if (Item) await redis.setex(`product:${id}`, 300, JSON.stringify(Item));
return Item;
}
// Rate limiter
async function checkRateLimit(userId: string, limit = 100) {
const key = `ratelimit:${userId}:${new Date().getMinutes()}`;
const count = await redis.incr(key);
if (count === 1) await redis.expire(key, 60);
if (count > limit) throw new Error("Rate limit exceeded");
}
| Eviction Policy | Behavior |
|---|---|
| allkeys-lru | Evict any key, LRU order — dùng cho cache |
| volatile-lru | Evict key có TTL, LRU — cache + session |
| noeviction | Không evict, return error — session store |
Bài sau: Phần 37: Dự án 3-Tier App