Appearance
Reference: Runbooks & Cheat Sheets
Tra cứu: xử lý sự cố từng DB, chọn DB theo use case, mô hình dữ liệu, index, consistency, lệnh hay dùng. Ngưỡng trong runbook là ví dụ khởi điểm, không phải số đo; đặt lại theo SLO của hệ thống.
Runbooks by Database
MongoDB: slow queries
- Symptoms: P99 tăng vọt, CPU cao, query timeout.
- Check:
db.currentOp(), slow log,db.collection.getIndexes(), chunk balance. Profiler chỉ có dữ liệu sau khi bật (mức 1, theo từng database). - Command:javascript
// mongosh db.currentOp({ "secs_running": { $gt: 5 } }) db.setProfilingLevel(1, { slowms: 100 }) db.system.profile.find({ millis: { $gt: 100 } }).limit(20) db.setProfilingLevel(0) // tắt khi xong - Threshold: P99 >50ms hoặc slow op >1% là dấu hiệu đáng lo.
- Mitigate: thêm/chỉnh index, chuyển đọc nặng sang secondary (chấp nhận đọc dữ liệu cũ), giới hạn tốc độ job nặng.
- Rollback: ẩn index mới trước (đảo ngược được), quan sát, rồi mới drop; hoàn lại query hint, khôi phục cấu hình shard trước đó.
- Command:javascript
// mongosh db.users.hideIndex("idx_new_slow") // lui: db.users.unhideIndex("idx_new_slow") db.users.dropIndex("idx_new_slow") - Prevent: rà soát shard key và index, giữ working set trong RAM.
DynamoDB: throttling / hot partition
- Symptoms:
ProvisionedThroughputExceededException, P99 >20ms. - Check: CloudWatch
ThrottledRequests,ReadThrottleEvents/WriteThrottleEvents; metricReadKeyRangeThroughputThrottleEvents/WriteKeyRangeThroughputThrottleEventsbáo request bị chặn do giới hạn partition (hot key), partition key skew. - Command:bash
# GNU date; thay YourTable bằng tên bảng thật aws cloudwatch get-metric-statistics --namespace AWS/DynamoDB \ --metric-name WriteKeyRangeThroughputThrottleEvents \ --dimensions Name=TableName,Value=YourTable \ --start-time "$(date -u -d '1 hour ago' +%FT%TZ)" --end-time "$(date -u +%FT%TZ)" \ --period 300 --statistics Sum - Threshold: throttle rate >0.1% sustained.
- Mitigate: tăng WCU/RCU, thêm hậu tố ngẫu nhiên vào PK (write sharding); adaptive capacity tự chạy nhưng không có bảo đảm, đừng coi là cách xử lý.
- Rollback: giảm đợt ghi dồn, tạm chuyển đọc sang cache; xoá GSI vừa thêm (không hoàn tác được, tạo lại phải backfill). PK không đổi tại chỗ: đổi PK nghĩa là bảng mới + migrate.
- Command:bash
aws dynamodb update-table --table-name YourTable --global-secondary-index-updates \ '[{"Delete":{"IndexName":"gsi_new"}}]' - Prevent: thiết kế PK phân bố đều, tránh hot key.
Redis: eviction storm / OOM
- Symptoms: cache miss tăng đột ngột, lỗi
OOM command not allowed(policynoeviction). - Check:
INFO memory,INFO stats(evicted_keys),MEMORY DOCTOR. - Command:bash
redis-cli INFO memory redis-cli INFO stats | grep evicted_keys redis-cli MEMORY DOCTOR - Threshold:
evicted_keystăng liên tục hoặc memory >80%maxmemory(ví dụ minh hoạ, đặt theo baseline). - Mitigate: tăng bộ nhớ, giảm TTL, đổi eviction policy chỉ khi dữ liệu là cache:
allkeys-*xoá cả key không có TTL. - Rollback: ghi lại giá trị cũ trước khi đổi, rồi đặt lại đúng giá trị đó; tắt các cache key mới, làm nóng lại cache cũ.
- Command:bash
redis-cli CONFIG GET maxmemory-policy redis-cli CONFIG SET maxmemory-policy allkeys-lru # lui: đặt lại giá trị đã ghi ở trên, ví dụ noeviction redis-cli CONFIG SET maxmemory-policy noeviction # chỉ khi muốn giữ qua restart: redis-cli CONFIG REWRITE - Prevent: định cỡ bộ nhớ theo hot set, rà soát TTL của key, tránh value lớn.
Cassandra: compaction / tombstone pain
- Symptoms: read latency tăng vọt, disk IO cao.
- Check:
nodetool compactionstats, tombstone warnings, SSTable count. Ví dụ dùng bảngshop.events_by_userở Cheat Sheet bên dưới. - Command:bash
nodetool compactionstats nodetool tablestats shop.events_by_user - Threshold: compaction backlog tăng dần kèm read timeout.
- Mitigate: chỉnh compaction strategy, chạy repair, giảm TTL churn.
- Rollback: hoàn lại thay đổi schema, drop index vừa thêm, tạm dừng các lần ghi TTL nặng.
- Command:cql
DROP INDEX IF EXISTS shop.idx_new; - Prevent: mô hình hoá query theo partition key, tránh partition quá rộng.
Neo4j: traversal slowdown
- Symptoms: query đồ thị chậm, GC cao, page cache miss.
- Check: metric
neo4j.page_cache.hit_ratio(bật metrics), supernode detection. - Command:cypher
CALL db.stats.retrieve('GRAPH COUNTS'); - Threshold: page cache hit <90% với workload nóng.
- Mitigate: thêm relationship index, tách lại supernode, tăng
server.memory.pagecache.size. - Rollback: hoàn lại thay đổi query, gỡ constraint/index mới, restart với cấu hình cũ.
- Command:cypher
DROP INDEX idx_new IF EXISTS; - Prevent: mô hình hoá để tránh supernode, giữ đồ thị nóng trong bộ nhớ.
Use Case → Database
| Use case | Database | Vì sao | Thay thế |
|---|---|---|---|
| User profiles, catalog, CMS | MongoDB | Schema linh hoạt, aggregation | DocumentDB, PostgreSQL JSONB |
| Serverless API, microservice data | DynamoDB | Tự scale, trả theo request | Aurora Serverless |
| Leaderboard | Redis sorted set / DynamoDB | Ghi và xếp hạng nhanh | |
| Session, cache, rate limit | Redis | Sub-ms, TTL, INCR nguyên tử | Memcached |
| Message queue nhẹ | Redis Streams / Lists | Consumer group | RabbitMQ, SQS, Kafka |
| IoT, event log | Cassandra | Ghi nối đuôi, scale ngang | InfluxDB, Timescale, Timestream for InfluxDB |
| Multi-region active-active | Cassandra / DynamoDB Global Tables | Không có master duy nhất | |
| Social graph, fraud, recommendation | Neo4j | Duyệt quan hệ nhiều tầng |
Data Modeling
| Database | Mô hình | Ý chính | Ví dụ |
|---|---|---|---|
| MongoDB | Document | Embed khi đọc cùng nhau và mảng có giới hạn; reference khi một-nhiều không giới hạn | { user: {...}, orders: [...] } |
| DynamoDB | Key-value, single-table | Liệt kê access pattern trước; overload PK/SK; GSI cho truy vấn ngược | PK=USER#123, SK=ORDER#456 |
| Redis | Data structures | Chọn đúng structure cho việc: String, Hash, List, Set, ZSet, Stream | ZADD leaderboard 100 player1 |
| Cassandra | Wide-column | Mỗi query một bảng; partition key + clustering key; chấp nhận nhân bản dữ liệu | PRIMARY KEY ((user_id), ts) |
| Neo4j | Graph | Quan hệ là dữ liệu hạng nhất; tránh supernode | (User)-[:FOLLOWS]->(User) |
Indexing by Database
| Database | Loại index | Lưu ý |
|---|---|---|
| MongoDB | Single, compound, text, geospatial, wildcard, partial, sparse | Compound theo prefix trái sang phải; mỗi index làm ghi chậm thêm |
| DynamoDB | Primary key (PK/SK), GSI, LSI | GSI nhân bản dữ liệu và WCU (quota mặc định 20 GSI/bảng); LSI chỉ tạo lúc tạo bảng, tối đa 5 |
| Redis | Không có index phụ kiểu truyền thống (không tính Query Engine) | Dùng structure làm index (Set, ZSet); Redis 8 có sẵn Query Engine (trước là module RediSearch) cho full-text, secondary index, vector |
| Cassandra | Primary (partition + clustering); SAI (Cassandra 5.0+); index phụ cũ; materialized view (tắt mặc định ở 5.0, bật bằng materialized_views_enabled) | Query phải đi theo partition key; index phụ không kèm partition key chạm nhiều nút, tránh trên đường nóng |
| Neo4j | Range (property), composite, full-text, relationship property | Dùng để tìm điểm bắt đầu; việc duyệt đi theo quan hệ, không cần index |
Consistency (CAP)
| Database | Mặc định | Tuỳ chỉnh | Đánh đổi |
|---|---|---|---|
| MongoDB | Primary nhận ghi; w: majority là mặc định từ 5.0 | w: 1, đọc từ secondary | Nhanh hơn nhưng có thể đọc dữ liệu cũ hoặc mất ghi khi failover |
| DynamoDB | Đọc eventually consistent | ConsistentRead=true | Đọc strong tốn gấp đôi RCU, không dùng được trên GSI |
| Redis | Replication bất đồng bộ | WAIT | Failover có thể mất ghi đã xác nhận; WAIT giảm chứ không loại bỏ |
| Cassandra | AP, chỉnh theo từng query | QUORUM cho cả đọc và ghi | Strong theo từng thao tác, đổi lại độ trễ và tính sẵn sàng |
| Neo4j | ACID trên một instance | Cluster: primary nhận ghi, secondary đọc | Đọc từ secondary có thể chậm hơn bản ghi mới nhất |
Command Cheat Sheet
MongoDB:
javascript
// mongosh (collection users tạo bằng dòng insertMany dưới đây, chạy trên database trống)
db.users.insertMany([{ email: "a@x.com", age: 20, status: "active" }, { email: "b@x.com", age: 15, status: "inactive" }])
// Query
db.users.find({ age: { $gte: 18 } }).explain("executionStats")
db.users.aggregate([{ $match: { status: "active" } }, { $group: { _id: "$status", n: { $sum: 1 } } }])
// Indexes
db.users.createIndex({ email: 1 }, { unique: true })
db.users.createIndex({ status: 1 }, { partialFilterExpression: { status: "active" }})
db.users.getIndexes()
// Admin
db.currentOp()
db.serverStatus()
db.stats()DynamoDB (AWS CLI):
bash
# Tạo bảng Users (thêm --endpoint-url http://localhost:8000 khi dùng DynamoDB Local)
aws dynamodb create-table --table-name Users \
--attribute-definitions AttributeName=PK,AttributeType=S AttributeName=SK,AttributeType=S \
--key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
--billing-mode PAY_PER_REQUEST
# Batch operations
cat > items.json <<'EOF'
{"Users":[{"PutRequest":{"Item":{"PK":{"S":"USER#123"},"SK":{"S":"PROFILE"},"age":{"N":"30"}}}}]}
EOF
aws dynamodb batch-write-item --request-items file://items.json
# Query (requires PK, optional SK)
aws dynamodb query --table-name Users \
--key-condition-expression "PK = :pk" \
--expression-attribute-values '{":pk":{"S":"USER#123"}}'
# Scan (avoid in production)
aws dynamodb scan --table-name Users --filter-expression "age > :age" \
--expression-attribute-values '{":age":{"N":"18"}}'
# Metrics (GNU date)
aws cloudwatch get-metric-statistics --namespace AWS/DynamoDB \
--metric-name ConsumedReadCapacityUnits --dimensions Name=TableName,Value=Users \
--start-time "$(date -u -d '1 hour ago' +%FT%TZ)" --end-time "$(date -u +%FT%TZ)" \
--period 300 --statistics SumRedis:
bash
# Strings
redis-cli SET user:123:name "John" EX 3600
redis-cli GET user:123:name
redis-cli INCR page:views
# Hashes (objects)
redis-cli HSET user:123 name "John" age 30
redis-cli HGETALL user:123
# Lists (queues)
redis-cli LPUSH queue:jobs job1
redis-cli BRPOP queue:jobs 5
# Sorted Sets (leaderboards)
redis-cli ZADD leaderboard 100 player1
redis-cli ZRANGE leaderboard 0 9 REV WITHSCORES
# Monitoring
redis-cli INFO stats
redis-cli SLOWLOG GET 10
redis-cli MEMORY DOCTORCassandra (CQL):
cql
-- chạy trong cqlsh; SimpleStrategy chỉ cho thử nghiệm một nút (production dùng NetworkTopologyStrategy)
CREATE KEYSPACE IF NOT EXISTS shop WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE shop;
-- Create table (query-first design)
CREATE TABLE events_by_user (
user_id UUID,
event_time TIMESTAMP,
event_type TEXT,
PRIMARY KEY ((user_id), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC);
INSERT INTO events_by_user (user_id, event_time, event_type)
VALUES (123e4567-e89b-12d3-a456-426614174000, '2026-11-24 10:00:00+0000', 'login');
-- Query (must use partition key)
SELECT * FROM events_by_user
WHERE user_id = 123e4567-e89b-12d3-a456-426614174000 AND event_time > '2026-11-01';bash
# Monitoring
nodetool status
nodetool tpstats
nodetool tablestats shop.events_by_userNeo4j (Cypher):
cypher
// Indexes và constraint tạo trước khi nạp dữ liệu
CREATE CONSTRAINT user_id IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE;
CREATE INDEX user_email IF NOT EXISTS FOR (u:User) ON (u.email);
// Create nodes and relationships
CREATE (:User {id: 123, name: 'John', email: 'john@x.com'});
CREATE (:User {id: 456, name: 'Mary', email: 'mary@x.com'});
CREATE (:User {id: 789, name: 'Ann', email: 'ann@x.com'});
MATCH (a:User {id: 123}), (b:User {id: 456}), (c:User {id: 789})
CREATE (a)-[:FOLLOWS]->(b)-[:FOLLOWS]->(c);
// Pattern matching
MATCH (u:User)-[:FOLLOWS]->(friend)
WHERE u.id = 123
RETURN friend.name;
// Shortest path (hai đầu có id, luôn chặn độ sâu)
MATCH path = shortestPath((u1:User {id: 123})-[:FOLLOWS*..6]-(u2:User {id: 789}))
RETURN length(path) AS hops;Versions & Lifecycle (soát 2026-11-17)
| Sản phẩm | Hiện hành | Điểm đáng nhớ (góc SA) |
|---|---|---|
| MongoDB | 8.x | w: majority mặc định từ 5.0; index build kiểu hybrid từ 4.2 |
| Redis | 8.x | Query Engine, JSON, TimeSeries có sẵn trong core. License đổi từ 7.4 (RSALv2/SSPL), Redis 8 thêm tuỳ chọn AGPLv3; Valkey là fork BSD, được AWS ElastiCache/MemoryDB hỗ trợ ⇒ cân nhắc license trước khi chọn. Đo 2026-11-25: redis:8 báo 8.10.3 |
| Cassandra | 5.0 | SAI là lựa chọn thay SASI; secondary index cũ vẫn tạo được; có vector search qua SAI. Mặc định 5.0 (đo cassandra:5 = 5.0.9): Java 17, num_tokens: 16, commitlog_sync: periodic, materialized view tắt (materialized_views_enabled: false), paxos_variant: v1 |
| Neo4j | 5.26 là LTS 5.x cuối (hotfix tới 06/2028; neo4j:5 = 5.26.33); sau đó đánh số theo lịch (2025.xx, 2026.xx). 4.4 LTS hết hỗ trợ 30/11/2025 | Cú pháp ON :Label(prop), ASSERT, db.indexes() đã bỏ ⇒ dùng FOR … ON, REQUIRE, SHOW INDEXES |
| DynamoDB | Dịch vụ quản lý | Quota mặc định 20 GSI/bảng (tăng được); đọc strong không dùng được trên GSI; giá on-demand giảm 50% từ 11/2024; transaction tối đa 100 item; global tables có chế độ strong consistency đa vùng (MRSC) |
| Amazon DocumentDB | Engine 5.0 / 8.0 | 8.0 có $merge, $graphLookup; retryable writes từ 8.0.2; $unionWith thêm ở 8.0.3 theo release notes; có bản Serverless (đơn vị DCU); 3.6 hết standard support 30/03/2026, Extended Support trả phí tới 30/03/2029; CA cũ rds-combined-ca-bundle đã hết hạn, dùng global-bundle.pem |
| AWS SDK cho JavaScript | v3 | v2 (aws-sdk, .promise()) hết hỗ trợ 09/2025 |
| InfluxDB | 3.x (đo influxdb:3-core: 3.12.3) | Dùng SQL và InfluxQL (doc Core liệt kê hai ngôn ngữ này, không liệt kê Flux); lưu Parquet trên object storage |
| TimescaleDB | 2.x (đo timescale/timescaledb:latest-pg17: 2.32.1) | Tạo hypertable bằng create_hypertable('m', by_range('t')) (đo, chạy OK) |
| pgvector | ≥ 0.8 (đo pgvector/pgvector:pg18: 0.8.7) | Có iterative index scan cho truy vấn ANN có lọc (đo: SET hnsw.iterative_scan = relaxed_order chạy OK) |
Soát lần cuối: 2026-11-25.
Các mục "war story" giữ phiên bản lúc xảy ra sự cố (ví dụ Neo4j 4.x); đó là lịch sử, không phải khuyến nghị phiên bản.
Phải nhớ (Runbooks & Cheat Sheets)
- Runbook đi theo triệu chứng → kiểm → sửa → lui: ghi giá trị cũ trước khi đổi (
CONFIG GET,hideIndextrướcdropIndex); xoá GSI hoặc index không hoàn tác được. - Ngưỡng trong runbook là ví dụ minh hoạ, đặt theo baseline của hệ thống; mỗi khối lệnh cần đủ bảng, keyspace, đối số (dòng đầu khối ghi fixture).
- Tên tham số đổi theo bản: đối chiếu bảng Versions trước khi dán (Neo4j 5 dùng
server.*, Cassandra 5.0 tắt materialized view mặc định).