Appearance
PART 9: REAL-WORLD CASE STUDIES
Ba kịch bản minh hoạ (MongoDB, DynamoDB + Redis, Cassandra); không phải sự cố có nguồn, số liệu là giả định.
Case Study 1: E-commerce Platform (MongoDB)
Kịch bản minh hoạ, không phải sự cố có nguồn. Mọi số trong mục này là giả định, không phải số đo.
System: Online retail with 5M users, 2M products, 500K orders/day
Architecture:
text
┌─────────────┐
│ Web/Mobile │
└──────┬──────┘
│
┌───┴────────────────────┐
│ Node.js API (50 servers) │
└───┬────────────────────┘
│
┌───┴───────────────────┐
│ MongoDB Replica Set │
│ Primary + 2 Secondary│
│ Sharded (6 shards) │
└───┬───────────────────┘
│
┌───┴───────────────────┐
│ Redis Cache (2 nodes)│
└───────────────────────┘Data model:
javascript
// mongosh, minh hoạ hình dạng tài liệu, không chạy độc lập
// products collection (5GB, sharded by productId)
{
_id: ObjectId("..."),
productId: "PROD-12345",
name: "Wireless Headphones",
category: "Electronics",
price: 79.99,
inventory: 247,
specs: {
brand: "TechBrand",
color: "Black",
weight: "250g"
},
reviews: {
count: 1247,
avgRating: 4.5
},
tags: ["wireless", "bluetooth", "headphones"]
}
// orders collection (120GB, sharded by userId)
{
_id: ObjectId("..."),
orderId: "ORD-67890",
userId: "USR-123",
status: "shipped",
total: 159.98,
createdAt: ISODate("2025-01-09T10:30:00Z"),
items: [
{
productId: "PROD-12345",
name: "Wireless Headphones", // Denormalized
quantity: 2,
price: 79.99
}
],
shipping: {
address: "123 Main St",
city: "San Francisco",
tracking: "TRK-ABC123"
}
}Query patterns:
javascript
// mongosh, MongoDB 8: chạy sau khi có dữ liệu mẫu theo hình dạng ở khối Data model trên
// 1. Product search (with index)
db.products.createIndex({ name: "text", tags: "text" })
db.products.find({ $text: { $search: "wireless headphones" } })
.sort({ "reviews.avgRating": -1 })
.limit(20)
// 2. Order history (sharded by userId)
db.orders.find({ userId: "USR-123" })
.sort({ createdAt: -1 })
.limit(50)
// Query routes to single shard (fast!)
// 3. Inventory update (findAndModify - atomic)
db.products.findOneAndUpdate(
{ productId: "PROD-12345", inventory: { $gte: 2 } },
{ $inc: { inventory: -2 } },
{ returnDocument: 'after' }
)Performance optimizations:
javascript
// Node.js (ioredis + driver mongodb), minh hoạ, không chạy độc lập
// Cache product pages (Redis)
const cacheKey = `product:${productId}`
const cached = await redis.get(cacheKey)
let product = cached ? JSON.parse(cached) : null
if (!product) {
product = await mongodb.collection('products').findOne({ productId })
await redis.setex(cacheKey, 3600, JSON.stringify(product))
}
// Đo tỉ lệ cache hit bằng redis-cli INFO stats (keyspace_hits / keyspace_misses), không dùng số ví dụKết quả (giả định, không đo):
- Tải: 500 000 đơn/ngày ≈ 5,8 đơn/giây trung bình (500 000 / 86 400). Tải đỉnh phải đo từ log, không suy từ số trung bình.
- Độ trễ, độ sẵn sàng, chi phí: đo bằng workload thật và bảng giá hiện hành của Atlas; không lập kế hoạch từ số trong ví dụ này.
Bài học: Shard orders theo userId để lịch sử đơn của một user nằm ở một shard, rồi kiểm bằng explain() trước khi tin; số tải mở đầu bài phải khớp số kết quả cuối bài.
Case Study 2: Gaming Leaderboard (DynamoDB + Redis)
Kịch bản minh hoạ, không phải sự cố có nguồn. Mọi số trong mục này là giả định, không phải số đo.
System: Real-time game leaderboard with 10M players, 50K updates/sec
Architecture:
text
DynamoDB (persistent):
- Table: player_scores
- PK: gameId, SK: playerId
- GSI: gameId + score (chỉ giữ nếu cần đọc top từ DynamoDB; mọi ghi của một game cùng một khoá của GSI, dễ bị throttle khi tải cao)
Redis (real-time):
- Sorted Set: leaderboard:{gameId} → {score: playerId}
- Updates: 50K/sec (in-memory, fast)
- Sync to DynamoDB: Every 60 seconds (batch write, chỉ người chơi đổi điểm)Implementation:
javascript
// Node.js (ioredis + AWS SDK v3), đã chạy trên redis:8 + amazon/dynamodb-local (đặt REDIS_URL, AWS_REGION, AWS_ENDPOINT_URL_DYNAMODB)
// Gọi flushToDynamo() mỗi 60 giây (setInterval); BatchWriteItem tối đa 25 item mỗi lượt, phải thử lại UnprocessedItems (thực tế kèm backoff)
import Redis from 'ioredis'
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, BatchWriteCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'
const redis = new Redis(process.env.REDIS_URL)
const base = new DynamoDBClient({})
const ddb = DynamoDBDocumentClient.from(base)
await base.send(new CreateTableCommand({
TableName: 'player_scores',
BillingMode: 'PAY_PER_REQUEST',
AttributeDefinitions: [
{ AttributeName: 'gameId', AttributeType: 'S' },
{ AttributeName: 'playerId', AttributeType: 'S' },
{ AttributeName: 'score', AttributeType: 'N' }
],
KeySchema: [
{ AttributeName: 'gameId', KeyType: 'HASH' },
{ AttributeName: 'playerId', KeyType: 'RANGE' }
],
GlobalSecondaryIndexes: [{
IndexName: 'gameId-score-index',
KeySchema: [
{ AttributeName: 'gameId', KeyType: 'HASH' },
{ AttributeName: 'score', KeyType: 'RANGE' }
],
Projection: { ProjectionType: 'ALL' }
}]
}))
const dirty = new Map()
async function updateScore(gameId, playerId, score) {
await redis.zadd(`leaderboard:${gameId}`, score, playerId)
dirty.set(`${gameId}#${playerId}`, { gameId, playerId, score })
}
async function flushToDynamo() {
const items = [...dirty.values()]
dirty.clear()
for (let i = 0; i < items.length; i += 25) {
let requests = items.slice(i, i + 25).map(it => ({
PutRequest: { Item: { ...it, updatedAt: Date.now() } }
}))
while (requests.length > 0) {
const out = await ddb.send(new BatchWriteCommand({ RequestItems: { player_scores: requests } }))
requests = out.UnprocessedItems?.player_scores ?? []
}
}
}
async function getTopPlayers(gameId, limit = 10) {
const flat = await redis.zrange(`leaderboard:${gameId}`, 0, limit - 1, 'REV', 'WITHSCORES')
const leaderboard = []
for (let i = 0; i < flat.length; i += 2) {
leaderboard.push({ playerId: flat[i], score: Number(flat[i + 1]), rank: i / 2 + 1 })
}
return leaderboard
}
async function getPlayerRank(gameId, playerId) {
const rank = await redis.zrevrank(`leaderboard:${gameId}`, playerId)
const score = await redis.zscore(`leaderboard:${gameId}`, playerId)
if (rank === null) return null
return { rank: rank + 1, score: Number(score) }
}Kết quả (giả định, không đo):
- Chi phí ghi DynamoDB: 50 000 ghi/giây × 2 592 000 giây/tháng = 1,296 × 10^11 ghi; on-demand $0,625/triệu write (us-east-1, 2026-11-20) ≈ $81 000/tháng nếu ghi từng cập nhật (item ≤ 1 KB). Gom theo 60 giây và chỉ ghi người chơi đổi điểm kéo số ghi về số người chơi hoạt động, không còn theo số cập nhật.
- Độ trễ và throughput: đo bằng
redis-cli --latencyvàredis-benchmarktrên máy thật; không dùng số trong ví dụ này.
Bài học: Tính chi phí ghi bằng công thức trước khi chọn "ghi mỗi cập nhật"; DynamoDB tính tiền theo ghi, Redis tính theo bộ nhớ, nên Redis hấp thụ cập nhật nóng và DynamoDB chỉ nhận bản gom.
Case Study 3: IoT Time-Series (Cassandra)
Kịch bản minh hoạ, không phải sự cố có nguồn. Mọi số trong mục này là giả định, không phải số đo.
System: IoT sensor data from 500K devices, mỗi thiết bị 1 mẫu/giây ⇒ 500 000 ghi/giây
Architecture:
text
Devices → Kafka (buffer) → Cassandra (3 datacenters, 30 nodes)Data model:
cql
-- Cassandra 5.0, một nút dev (production dùng NetworkTopologyStrategy)
CREATE KEYSPACE IF NOT EXISTS iot WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE iot;
CREATE TABLE sensor_data (
device_id text,
date text, -- Partition bucket (e.g., '2025-01-09')
timestamp timestamp,
temperature decimal,
humidity decimal,
PRIMARY KEY ((device_id, date), timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)
AND compaction = {'class': 'TimeWindowCompactionStrategy', 'compaction_window_unit': 'DAYS', 'compaction_window_size': 1};
INSERT INTO sensor_data (device_id, date, timestamp, temperature, humidity) VALUES ('DEVICE-123', '2025-01-09', '2025-01-09 10:00:00+0000', 21.5, 40.1);
INSERT INTO sensor_data (device_id, date, timestamp, temperature, humidity) VALUES ('DEVICE-123', '2025-01-09', '2025-01-09 10:00:01+0000', 21.6, 40.0);
-- Kích thước partition ước tính: 86 400 mẫu/ngày × 50 byte ≈ 4,3 MB; đo thật bằng nodetool tablestats (dòng Compacted partition maximum bytes)Query patterns:
cql
-- Chạy sau khối tạo sensor_data và INSERT mẫu ở mục Data model trên
-- Get latest readings (single partition)
SELECT * FROM sensor_data
WHERE device_id = 'DEVICE-123'
AND date = '2025-01-09'
ORDER BY timestamp DESC
LIMIT 100;
-- Đọc một partition (đủ device_id và date); đo độ trễ bằng nodetool tablehistogramsKết quả (giả định, không đo):
- Tải ghi: 500 000 thiết bị × 1 mẫu/giây = 500 000 ghi/giây, chia cho 30 nút ≈ 16 700 ghi/giây/nút trước khi nhân hệ số sao chép; số thật đo bằng
nodetool tablestatsvànodetool proxyhistograms. - Dung lượng và chi phí: tính từ 500 000 × 86 400 = 4,32 × 10^10 mẫu/ngày × kích thước dòng đo thật × hệ số sao chép, và giá giờ EC2 hiện hành của loại máy chọn; không lấy số trong ví dụ này.
Bài học: Bucket partition theo thời gian ((device_id, date)) giữ partition nhỏ và để TimeWindowCompactionStrategy bỏ nguyên cửa sổ cũ; tính tải ghi từ số thiết bị × tần suất, không từ con số có sẵn.
Phải nhớ (PART 9):
- Ba kịch bản là giả định; chi phí ghi tính bằng công thức (số ghi × đơn giá), tải đỉnh đo từ log.
- Redis + DynamoDB: gom ghi theo lô tối đa 25 item và thử lại
UnprocessedItems; top-N đọc từ Redis (ZRANGE ... REV WITHSCORES). - Cassandra: bucket partition theo thời gian, đo kích thước bằng
nodetool tablestats.