Skip to content

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; metric ReadKeyRangeThroughputThrottleEvents/WriteKeyRangeThroughputThrottleEvents bá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 (policy noeviction).
  • 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_keys tă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ảng shop.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 caseDatabaseVì saoThay thế
User profiles, catalog, CMSMongoDBSchema linh hoạt, aggregationDocumentDB, PostgreSQL JSONB
Serverless API, microservice dataDynamoDBTự scale, trả theo requestAurora Serverless
LeaderboardRedis sorted set / DynamoDBGhi và xếp hạng nhanh
Session, cache, rate limitRedisSub-ms, TTL, INCR nguyên tửMemcached
Message queue nhẹRedis Streams / ListsConsumer groupRabbitMQ, SQS, Kafka
IoT, event logCassandraGhi nối đuôi, scale ngangInfluxDB, Timescale, Timestream for InfluxDB
Multi-region active-activeCassandra / DynamoDB Global TablesKhông có master duy nhất
Social graph, fraud, recommendationNeo4jDuyệt quan hệ nhiều tầng

Data Modeling ​

DatabaseMô hìnhÝ chínhVí dụ
MongoDBDocumentEmbed 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: [...] }
DynamoDBKey-value, single-tableLiệt kê access pattern trước; overload PK/SK; GSI cho truy vấn ngượcPK=USER#123, SK=ORDER#456
RedisData structuresChọn đúng structure cho việc: String, Hash, List, Set, ZSet, StreamZADD leaderboard 100 player1
CassandraWide-columnMỗi query một bảng; partition key + clustering key; chấp nhận nhân bản dữ liệuPRIMARY KEY ((user_id), ts)
Neo4jGraphQuan hệ là dữ liệu hạng nhất; tránh supernode(User)-[:FOLLOWS]->(User)

Indexing by Database ​

DatabaseLoại indexLưu ý
MongoDBSingle, compound, text, geospatial, wildcard, partial, sparseCompound theo prefix trái sang phải; mỗi index làm ghi chậm thêm
DynamoDBPrimary key (PK/SK), GSI, LSIGSI 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
RedisKhô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
CassandraPrimary (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
Neo4jRange (property), composite, full-text, relationship propertyDùng để tìm điểm bắt đầu; việc duyệt đi theo quan hệ, không cần index

Consistency (CAP) ​

DatabaseMặc địnhTuỳ chỉnhĐánh đổi
MongoDBPrimary nhận ghi; w: majority là mặc định từ 5.0w: 1, đọc từ secondaryNhanh hơn nhưng có thể đọc dữ liệu cũ hoặc mất ghi khi failover
DynamoDBĐọc eventually consistentConsistentRead=trueĐọc strong tốn gấp đôi RCU, không dùng được trên GSI
RedisReplication bất đồng bộWAITFailover có thể mất ghi đã xác nhận; WAIT giảm chứ không loại bỏ
CassandraAP, chỉnh theo từng queryQUORUM cho cả đọc và ghiStrong theo từng thao tác, đổi lại độ trễ và tính sẵn sàng
Neo4jACID trên một instanceCluster: 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 Sum

Redis:

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 DOCTOR

Cassandra (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_user

Neo4j (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ẩmHiện hànhĐiểm đáng nhớ (góc SA)
MongoDB8.xw: majority mặc định từ 5.0; index build kiểu hybrid từ 4.2
Redis8.xQuery 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
Cassandra5.0SAI 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
Neo4j5.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/2025Cú pháp ON :Label(prop), ASSERT, db.indexes() đã bỏ ⇒ dùng FOR … ON, REQUIRE, SHOW INDEXES
DynamoDBDị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 DocumentDBEngine 5.0 / 8.08.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 JavaScriptv3v2 (aws-sdk, .promise()) hết hỗ trợ 09/2025
InfluxDB3.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
TimescaleDB2.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, hideIndex trước dropIndex); 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).