Skip to content

PART 10: TROUBLESHOOTING & MONITORING ​

MongoDB Troubleshooting Workflow ​

text
Triệu chứng: query chậm
│
├─→ Xem thao tác đang chạy
│     db.currentOp({ secs_running: { $gt: 5 } })
│
├─→ Bật profiler, đọc system.profile
│     db.setProfilingLevel(1, { slowms: 100 })
│     db.system.profile.find().sort({ ts: -1 }).limit(10)
│
├─→ explain() query chậm
│     db.orders.find({ status: 'new' }).explain('executionStats')
│     Tìm: COLLSCAN (thiếu index), totalDocsExamined >> nReturned
│
├─→ Kiểm tra index có dùng không
│     db.orders.aggregate([{ $indexStats: {} }])
│     Tìm: accesses.ops = 0 tính từ accesses.since (bộ đếm reset khi mongod restart)
│
└─→ Sửa: tạo index hoặc viết lại query
      db.orders.createIndex({ status: 1 })

Lưu ý production: profiler level 1 ghi mỗi thao tác chậm vào system.profile (collection capped) nên tốn I/O; đặt slowms theo baseline đo được và db.setProfilingLevel(0) khi xong. createIndex trên collection lớn tốn I/O và CPU; chạy ở giờ thấp tải.

DynamoDB Troubleshooting Workflow ​

text
Triệu chứng: throttling (ProvisionedThroughputExceededException)
│
├─→ Xem metric CloudWatch
│     ConsumedRead/WriteCapacityUnits (Sum chia 60 = đơn vị mỗi giây)
│     ThrottledRequests (Dimensions: TableName, Operation)
│     Read/WriteThrottleEvents; Read/WriteKeyRangeThroughputThrottleEvents
│     (throttle vì giới hạn partition). Throttle không nằm trong UserErrors.
│
├─→ Tìm khoá nóng
│     Bật CloudWatch Contributor Insights cho DynamoDB
│     (khoá truy cập nhiều nhất và khoá bị throttle nhiều nhất)
│
├─→ Xem access pattern
│     Mọi request có đổ vào cùng một PK không? (ví dụ date = hôm nay)
│
└─→ Sửa: write sharding để rải PK
      PK = `${date}#${userId % 10}`  (10 giá trị PK; không bảo đảm 10 partition)
      Chuyển On-Demand không xoá giới hạn mỗi partition

Redis Troubleshooting Workflow ​

text
Triệu chứng: bộ nhớ cao
│
├─→ Xem INFO memory
│     redis-cli INFO memory
│     Tìm: used_memory_human, maxmemory_human, mem_fragmentation_ratio
│     (maxmemory_human = 0B nghĩa là chưa đặt giới hạn; ratio vô nghĩa khi used_memory nhỏ)
│
├─→ Xem phân bố khoá
│     redis-cli --bigkeys     (khoá lớn nhất theo từng kiểu, quét bằng SCAN)
│     redis-cli --memkeys     (đo theo byte)
│     Tìm: khoá lớn bất thường so với baseline (ví dụ minh hoạ: > 1 MB)
│
├─→ Xem evicted_keys
│     redis-cli INFO stats | grep evicted_keys
│     Tìm: evicted_keys tăng giữa hai lần đo (bộ đếm cộng dồn) = áp lực bộ nhớ
│
└─→ Sửa: tăng maxmemory, đặt TTL hoặc chia nhỏ giá trị lớn
      redis-cli CONFIG SET maxmemory 32gb
      redis-cli EXPIRE session:42 3600

Lưu ý production: --bigkeys và --memkeys quét toàn keyspace bằng SCAN, nên chạy trên replica hoặc giờ thấp tải. Đặt maxmemory nhỏ hơn RAM trống của host (chừa chỗ cho fork khi BGSAVE và buffer), nếu không kernel có thể OOM-kill Redis.

Cassandra Troubleshooting Workflow ​

text
Triệu chứng: read latency tăng đột ngột
│
├─→ nodetool tablestats <keyspace>.<table>
│     Tìm: Local read latency, Bloom filter false ratio, Average/Maximum tombstones per slice
│     (ngưỡng ví dụ minh hoạ: latency > 100 ms, false ratio > 0.05; đặt theo baseline)
│
├─→ nodetool compactionstats
│     Tìm: pending tasks tăng liên tục (ví dụ minh hoạ: > 100)
│
├─→ Tombstone
│     cassandra.yaml: tombstone_warn_threshold (1000), tombstone_failure_threshold (100000)
│     grep -i tombstone /var/log/cassandra/system.log
│
└─→ Sửa: xử lý nguyên nhân tìm được; nếu compaction tụt hậu thì nâng throughput
      nodetool getcompactionthroughput
      nodetool setcompactionthroughput 128

Đừng dùng nodetool repair -pr như cách chữa độ trễ đọc: repair tốn I/O và mạng, chạy theo lịch hoặc khi có dữ liệu lệch.

Neo4j Troubleshooting Workflow ​

text
Triệu chứng: query timeout
│
├─→ Xem transaction đang chạy
│     SHOW TRANSACTIONS YIELD transactionId, elapsedTime, status;
│     Tìm: elapsedTime lớn (ví dụ minh hoạ: > 10 s)
│
├─→ PROFILE query chậm
│     PROFILE MATCH ... RETURN ...
│     Tìm: CartesianProduct, db hits cao
│
├─→ Xem bộ nhớ
│     Enterprise: CALL dbms.listPools();  (Community 5.26 báo procedure không tồn tại)
│     Community: neo4j-admin server memory-recommendation và log GC
│
└─→ Sửa: thêm index, giới hạn traversal, chỉnh heap
      CREATE INDEX IF NOT EXISTS FOR (n:User) ON (n.email);
      MATCH ... LIMIT 100;
      server.memory.heap.max_size=31g    (neo4j.conf)

Production Failure Runbooks ​

Mỗi runbook là cây quyết định IF-THEN cho một sự cố production hay gặp. Mọi ngưỡng (10 s, 60 s, 24 giờ, 10 000 ops/s) là ví dụ minh hoạ: đặt theo baseline đo được của hệ thống bạn.

Cách dùng:

  1. Xác nhận sự cố bằng checklist DETECTION.
  2. Chạy INVESTIGATION theo thứ tự Step 1 → Step 2 → ...
  3. Mỗi điểm quyết định dẫn tới một thủ tục RESOLUTION.
  4. Làm POST-INCIDENT sau khi xử lý xong.

Runbook 1: MongoDB Replication Lag > 10 seconds ​

INCIDENT: MongoDB Replication Lag > 10 seconds

DETECTION:

javascript
// mongosh
rs.printSecondaryReplicationInfo()
// Mỗi secondary in: "<n> secs (<h> hrs) behind the primary"
// Ngưỡng ví dụ minh hoạ, đặt theo baseline đo được:
// P1 nếu lag > 60 s, P2 nếu lag > 10 s

INVESTIGATION CHECKLIST:

Step 1: Check oplog window

javascript
// mongosh
const ri = db.getReplicationInfo()
printjson({ logSizeMB: ri.logSizeMB, usedMB: ri.usedMB, timeDiffHours: ri.timeDiffHours })
// timeDiffHours = cửa sổ oplog (từ entry cũ nhất tới entry mới nhất)

// Quyết định (ngưỡng ví dụ minh hoạ):
// IF timeDiffHours < 24
//   → oplog quá nhỏ so với tải ghi → Step A
// ELSE
//   → Step 2

Step 2: Check secondary resources

javascript
// mongosh — chạy trên secondary đang trễ
const wt = db.serverStatus().wiredTiger.cache
const GB = 1024 ** 3
printjson({
  usedGB: wt['bytes currently in the cache'] / GB,
  maxGB: wt['maximum bytes configured'] / GB,
  dirtyGB: wt['tracked dirty bytes in the cache'] / GB
})

// Thao tác chạy lâu
db.currentOp({ secs_running: { $gt: 60 } }).inprog
  .map(o => ({ opid: o.opid, op: o.op, ns: o.ns, secs: o.secs_running }))

// Quyết định (ngưỡng ví dụ minh hoạ):
// IF cache gần đầy (used ≈ max) và dirtyGB cao
//   → Step B
// ELSE IF currentOp có thao tác > 60 s
//   → Step C
// ELSE
//   → Step 3

Step 3: Check network connectivity

bash
# minh hoạ: thay <secondary-host> bằng tên máy secondary
ping -c 20 <secondary-host>

# Decision (ngưỡng ví dụ minh hoạ):
# IF network latency > 100 ms kéo dài
#   → Step D
# ELSE
#   → Step 4

Step 4: Check write load

javascript
// mongosh
const a = db.serverStatus().opcounters
sleep(1000)
const b = db.serverStatus().opcounters
const writesPerSec = (Number(b.insert) + Number(b.update) + Number(b.delete) -
  Number(a.insert) - Number(a.update) - Number(a.delete))
print(`Write rate: ${writesPerSec} ops/s`)
// opcounters là bộ đếm cộng dồn từ lúc khởi động: phải lấy hiệu hai lần đo

// Quyết định (ngưỡng ví dụ minh hoạ):
// IF writesPerSec vượt baseline (ví dụ > 10 000 ops/s)
//   → Step E
// ELSE
//   → chuyển DBA (chưa rõ nguyên nhân)

RESOLUTION PROCEDURES:

Step A: Resize Oplog (online, không downtime)

javascript
// mongosh — chạy trên TỪNG member
// 1. Cỡ oplog và cửa sổ hiện tại
const ri = db.getReplicationInfo()

// 2. Cỡ đích để giữ 72 giờ: tỉ lệ theo cửa sổ đã đo
//    (timeDiffHours = 0 khi oplog gần rỗng: đo lại sau khi có tải ghi)
//    Sàn của replSetResizeOplog là 990 MB
if (!(ri.timeDiffHours > 0)) throw new Error('timeDiffHours = 0: oplog chưa đủ dữ liệu, đo lại sau khi có tải ghi')
const targetMB = Math.max(990, Math.ceil(ri.usedMB * 72 / ri.timeDiffHours))
print(`logSizeMB=${ri.logSizeMB} usedMB=${ri.usedMB} window=${ri.timeDiffHours}h -> target=${targetMB} MB`)

// 3. Đổi cỡ (online, không downtime)
db.adminCommand({ replSetResizeOplog: 1, size: targetMB })

// 4. Kiểm tra
db.getReplicationInfo().logSizeMB

// 5. Giữ oplog tối thiểu theo giờ (4.4+): storage.oplogMinRetentionHours

Phòng ngừa: theo dõi cửa sổ oplog (với replica set tự quản là timeDiffHours), cảnh báo khi dưới ngưỡng đặt theo baseline (ví dụ 48 giờ) và đổi cỡ trước khi chạm 24 giờ.

Step B: Secondary thiếu RAM / cache đầy

javascript
// mongosh
const wt = db.serverStatus().wiredTiger.cache
const GB = 1024 ** 3
printjson({
  usedGB: wt['bytes currently in the cache'] / GB,
  maxGB: wt['maximum bytes configured'] / GB,
  dirtyGB: wt['tracked dirty bytes in the cache'] / GB
})
// serverStatus().mem không có trường phân mảnh (đo trên mongo:8); đọc cache WiredTiger
  • Cache WiredTiger mặc định = 50% của (RAM − 1 GB), tối thiểu 256 MB; giữ mặc định trừ khi đo được lợi ích khi đổi.
  • Working set lớn hơn cache: tăng RAM, thêm index để bớt quét tài liệu, chạy explain() cho query phổ biến.
  • Đừng restart secondary để "giảm phân mảnh bộ nhớ": serverStatus().mem không có trường phân mảnh (đo trên mongo:8); đọc cache WiredTiger.

Step C: Kill Blocking Operations

javascript
// mongosh
db.currentOp({
  secs_running: { $gte: 60 },
  op: { $in: ['query', 'update', 'remove'] }
}).inprog
javascript
// mongosh — chạy sau khối trên; thay 12345 bằng opid thật
db.killOp(12345)

RISK: killOp chỉ dừng được thao tác của client; không kill thread nội bộ như áp oplog trên secondary. update/remove nhiều tài liệu bị kill giữa chừng để lại thay đổi một phần (không tự rollback). Xác nhận ns và client của opid trước khi kill; kill ở production cần người có quyền duyệt.

Root cause và phòng ngừa:

  • Thiếu index → tạo index. Quét toàn collection → thêm bộ lọc. Thao tác hàng loạt → chia lô nhỏ hơn.
javascript
// mongosh
db.orders.find({ status: 'new' }).maxTimeMS(30000)   // giới hạn thời gian mỗi query
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find({ millis: { $gt: 100 } }).limit(20)

Step D: Network Issue

bash
# minh hoạ: thay <secondary-host> bằng tên máy secondary
ping -c 100 <secondary-host>
iperf3 -c <secondary-host>   # cần chạy iperf3 -s trên máy kia
  • Đo độ trễ và băng thông; so với baseline cùng AZ/region của chính hệ thống (ngưỡng ví dụ minh hoạ: trễ > 100 ms kéo dài là bất thường).
  • Chuyển secondary về cùng AZ/region; kiểm tra security group và giới hạn băng thông.
  • Phòng ngừa: giám sát lag cùng độ trễ mạng.

Step E: Write Overload

  • Đo write rate bằng hiệu hai lần opcounters như Step 4.
  • Giảm khối lượng ghi hoặc gộp lô.
  • wtimeout chỉ tránh client treo, không giảm lag. Đừng hạ về w:1 cho dữ liệu cần bền: ghi đã ack có thể bị rollback khi failover.
  • Dài hạn: shard theo khoá phân tán ghi (cardinality cao), giảm số index trên đường ghi, lưu trữ dữ liệu cũ ra kho lạnh. Đổi khoá shard sau này cần reshardCollection (5.0+).
javascript
// mongosh — minh hoạ, cần sharded cluster (kết nối mongos); không chạy trên replica set
sh.shardCollection('mydb.events', { userId: 1, timestamp: 1 })

POST-INCIDENT:

  • Document timeline in incident log
  • Update monitoring thresholds if needed
  • Schedule post-mortem if P1 severity
  • Test mitigation in staging environment

Runbook 2: DynamoDB Hot Partition Throttling ​

INCIDENT: ProvisionedThroughputExceededException dù capacity của bảng còn dư

DETECTION:

bash
# Linux (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 \
  --statistics Sum \
  --start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%S) \
  --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \
  --period 60
  • Báo động (ví dụ minh hoạ): Read/WriteKeyRangeThroughputThrottleEvents > 0 trong khi ConsumedWriteCapacityUnits (Sum chia 60) thấp hơn WCU đã cấp. Doc: metric này đếm request bị throttle "due to partition limits".
  • Throttle không nằm trong UserErrors: đừng đặt alarm hot partition trên UserErrors.
  • Severity: P2 (ảnh hưởng availability).

INVESTIGATION:

Step 1: Identify hot partition key

  • Bật CloudWatch Contributor Insights cho bảng: xem khoá bị truy cập và bị throttle nhiều nhất; hoặc đọc log ứng dụng của các request bị throttle.
  • Ví dụ: 90% ghi vào PK="2026-01-10" → khoá nóng theo ngày.

Step 2: So với giới hạn partition

  • DynamoDB không công bố số partition; mỗi partition tối đa 3 000 RCU / 1 000 WCU.
  • Một khoá vượt giới hạn đó thì bị throttle dù capacity của cả bảng còn dư.
  • Adaptive capacity có thể tách item collection của bảng có sort key (không có LSI) để giảm nóng; AWS không bảo đảm.

RESOLUTION:

Option A: Add shard suffix (immediate)

javascript
// Node.js — AWS SDK v3; tạo bảng Orders (PK, SK), ghi rải 10 shard, đọc lại cả 10 shard
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'

const client = new DynamoDBClient({})   // DynamoDB Local: thêm endpoint: 'http://localhost:8000'
const dynamodb = DynamoDBDocumentClient.from(client)

await client.send(new CreateTableCommand({
  TableName: 'Orders',
  BillingMode: 'PAY_PER_REQUEST',
  AttributeDefinitions: [
    { AttributeName: 'PK', AttributeType: 'S' },
    { AttributeName: 'SK', AttributeType: 'S' }
  ],
  KeySchema: [
    { AttributeName: 'PK', KeyType: 'HASH' },
    { AttributeName: 'SK', KeyType: 'RANGE' }
  ]
}))

// BAD: mọi ghi của ngày 2026-01-10 vào cùng một PK
await dynamodb.send(new PutCommand({ TableName: 'Orders', Item: { PK: '2026-01-10', SK: 'ORDER#123' } }))

// GOOD: rải ra 10 giá trị PK
for (let n = 0; n < 50; n++) {
  const shard = Math.floor(Math.random() * 10)
  await dynamodb.send(new PutCommand({
    TableName: 'Orders',
    Item: { PK: `2026-01-10#${shard}`, SK: `ORDER#${1000 + n}` }
  }))
}

// Đọc: phải Query cả 10 shard
const promises = Array.from({ length: 10 }, (_, i) =>
  dynamodb.send(new QueryCommand({
    TableName: 'Orders',
    KeyConditionExpression: 'PK = :pk',
    ExpressionAttributeValues: { ':pk': `2026-01-10#${i}` }
  }))
)
const allResults = await Promise.all(promises)
console.log(allResults.flatMap(r => r.Items).length)   // 50

Đọc phải Query cả 10 shard; PK dạng ngày#shard chỉ tăng số giá trị khoá, không bảo đảm số partition.

Option B: Switch to On-Demand mode

bash
# Giới hạn mỗi partition (3 000 RRU / 1 000 WRU) vẫn áp dụng: On-Demand không chữa khoá nóng
aws dynamodb update-table \
  --table-name YourTable \
  --billing-mode PAY_PER_REQUEST

# Đánh đổi: giá mỗi request cao hơn
# Hợp với: traffic khó đoán

Option C: Increase provisioned capacity

bash
# Ví dụ minh hoạ: bảng đang 1000 WCU, tăng thêm 50%
aws dynamodb update-table \
  --table-name YourTable \
  --provisioned-throughput ReadCapacityUnits=1000,WriteCapacityUnits=1500
  • Tăng capacity của bảng không nâng giới hạn 1 000 WCU của một partition.
  • Adaptive capacity luôn bật cho mọi bảng (không bật/tắt được) và có thể cho khoá nóng vượt phân bổ cơ bản; không bảo đảm.

POST-INCIDENT:

  • Review partition key design (cardinality cao)
  • Theo dõi CloudWatch: ThrottledRequests (Dimensions TableName, Operation) và Read/WriteKeyRangeThroughputThrottleEvents, không phải UserErrors
  • Consider single-table design with composite PK

Runbook 3: Redis Eviction Storm (OOM) ​

INCIDENT: Sudden spike in cache misses due to memory eviction

DETECTION:

bash
redis-cli INFO stats | grep evicted_keys
# evicted_keys là bộ đếm cộng dồn: lấy hiệu hai lần đo
# (ngưỡng ví dụ minh hoạ: tăng > 1000 khoá/giây)

redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human'
# used_memory chạm maxmemory = áp lực bộ nhớ
# maxmemory_human:0B = chưa đặt giới hạn, Redis không evict

INVESTIGATION:

Step 1: Check memory usage

bash
redis-cli INFO memory
# used_memory_human: bộ nhớ đang dùng
# maxmemory_human: giới hạn đã cấu hình
# mem_fragmentation_ratio: phân mảnh (ví dụ minh hoạ: 1.0-1.5 là bình thường;
#   vô nghĩa khi used_memory nhỏ)

# Decision (ngưỡng ví dụ minh hoạ):
# IF mem_fragmentation_ratio > 2.0 và used_memory đủ lớn
#   → Memory fragmentation (Step A)
# ELSE IF used_memory >= maxmemory * 0.95
#   → Memory full (Step B)

Step 2: Identify large keys

bash
redis-cli --bigkeys
# Khoá lớn nhất theo từng kiểu (quét bằng SCAN: chạy trên replica hoặc giờ thấp tải)

# Decision (ngưỡng ví dụ minh hoạ):
# IF có khoá > 10 MB
#   → Large key problem (Step C)
# ELSE
#   → Check key count and TTLs (Step D)

RESOLUTION:

Step A: Fix memory fragmentation

bash
redis-cli INFO memory | grep mem_fragmentation_ratio

# Bật active defrag (cần jemalloc, là allocator mặc định của image redis)
redis-cli CONFIG SET activedefrag yes
redis-cli CONFIG GET activedefrag

RISK: active defrag tốn CPU của luồng chính khi chạy; bật rồi theo dõi độ trễ và mem_fragmentation_ratio, tắt lại nếu độ trễ tăng. Restart để giải phân mảnh là phương án cuối: redis-cli SHUTDOWN SAVE dừng server, mọi request lỗi tới khi khởi động lại; chỉ làm sau khi promote replica hoặc trong cửa sổ bảo trì. Đừng giả định systemd tự khởi động lại.

Step B: Increase maxmemory (immediate)

bash
redis-cli CONFIG GET maxmemory

# Ví dụ minh hoạ: đặt theo RAM trống của host, chừa chỗ cho fork khi BGSAVE và buffer
redis-cli CONFIG SET maxmemory 64gb

# Giữ sau restart: sửa redis.conf, dòng riêng "maxmemory 64gb",
# hoặc redis-cli CONFIG REWRITE (lỗi nếu server chạy không có file cấu hình)

Step C: Chunk large keys

javascript
// Node.js — ioredis; ghi và đọc lại session lớn theo đoạn 100 KB
import Redis from 'ioredis'

const redis = new Redis()   // mặc định localhost:6379
const userId = 42
const largeSession = JSON.stringify({ items: Array.from({ length: 20000 }, (_, i) => ({ id: i, name: `item-${i}` })) })

// Cắt chuỗi thành các đoạn tối đa 100 KB ký tự
const chunkData = (s, size) => s.match(new RegExp(`[\\s\\S]{1,${size}}`, 'g'))
const chunks = chunkData(largeSession, 1024 * 100)

// Ghi: MULTI để count và các đoạn cùng hết hạn sau 1 giờ
const tx = redis.multi()
chunks.forEach((c, i) => tx.set(`session:${userId}:chunk:${i}`, c, 'EX', 3600))
tx.set(`session:${userId}:count`, chunks.length, 'EX', 3600)
await tx.exec()

// Đọc: thiếu một đoạn (null) nghĩa là session hỏng, phải xoá và tạo lại
const count = Number(await redis.get(`session:${userId}:count`))
const parts = await redis.mget(Array.from({ length: count }, (_, i) => `session:${userId}:chunk:${i}`))
console.log(count, parts.every(p => p !== null), parts.join('') === largeSession)
redis.disconnect()

Step D: Audit TTLs

bash
redis-cli INFO keyspace
# Kết quả minh hoạ: db0:keys=13,expires=9,avg_ttl=...  → keys - expires = số khoá không có TTL

# Liệt kê khoá không có TTL trong một nhóm (SCAN, không dùng KEYS); lấy tối đa 1000 khoá để đỡ tải
redis-cli --scan --pattern 'session:*' | head -1000 | while read -r k; do
  [ "$(redis-cli TTL "$k")" = "-1" ] && echo "$k"
done

# Đặt TTL cho một khoá
redis-cli EXPIRE session:42 3600
javascript
// Node.js — minh hoạ, cần client ioredis đã tạo (redis) và biến value
await redis.setex('session:42', 3600, value)   // đặt TTL ngay lúc ghi

POST-INCIDENT:

  • Audit all keys for appropriate TTLs
  • Đặt giới hạn kích thước khoá (ví dụ minh hoạ: < 1 MB mỗi khoá)
  • Monitor: used_memory, evicted_keys metrics

Runbook 4: Cassandra Compaction Stall (High Disk I/O) ​

INCIDENT: Cassandra compaction backlog grows, read latency increases (ví dụ minh hoạ: > 100 ms)

DETECTION:

bash
nodetool compactionstats
# Ngưỡng ví dụ minh hoạ, đặt theo baseline đo được:
# pending tasks > 10; Local read latency > 100 ms (nodetool tablestats <keyspace>.<table>)
# Severity: P1 nếu pending > 50 (cluster có rủi ro), P2 nếu pending > 10 (hiệu năng giảm)

INVESTIGATION CHECKLIST:

Step 1: Check compaction status

bash
nodetool compactionstats
# Decision (ngưỡng ví dụ minh hoạ):
# IF pending tasks = 0
#   → Compaction đã bắt kịp, kiểm tra xem sự cố có thoáng qua không
# ELSE IF pending > 50
#   → CRITICAL: compaction tụt hậu (Resolution Step A)
# ELSE IF pending 10-50
#   → Kiểm tra I/O đĩa (Investigation Step 3)

Step 2: Check garbage collection (GC)

bash
nodetool gcstats
grep GCInspector /var/log/cassandra/system.log | tail -20

# Decision (ngưỡng ví dụ minh hoạ):
# IF GC pause > 5 s lặp lại sau vài phút
#   → GC pressure (Resolution Step C)
# ELSE
#   → Kiểm tra đĩa (Investigation Step 3)

Step 3: Check disk performance

bash
iostat -x 1 10
# Tìm: await cao, %util cao (ngưỡng ví dụ minh hoạ: await > 50 ms, %util > 80%)

# Decision:
# IF %util liên tục > 80% và await > 50 ms
#   → Đĩa là nút thắt (Resolution Step D)
# ELSE IF CPU cao khi compaction
#   → Nén tốn CPU (Resolution Step F)
# ELSE
#   → Compaction bị throttle bởi throughput (Resolution Step A để nâng ngay, Step E để giữ sau restart)

RESOLUTION PROCEDURES:

Step A: Raise compaction throughput first, do not disable autocompaction

bash
nodetool getcompactionthroughput
nodetool setcompactionthroughput 128
nodetool compactionstats
  • Đổi bằng nodetool có hiệu lực ngay, không restart. Mặc định 5.0 là 64 MB/s (đo: Current compaction throughput: 64 MB/s).
  • Đừng tắt autocompaction khi backlog tăng: số SSTable và độ trễ đọc chỉ tệ thêm.
  • Compaction cạnh tranh I/O với đọc: nâng từng bước và theo dõi độ trễ.

Step B: Adjust compaction strategy

cql
-- Chạy trong cqlsh. Bảng minh hoạ shop.orders (bỏ qua hai dòng CREATE nếu đã có bảng thật)
CREATE KEYSPACE IF NOT EXISTS shop WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
CREATE TABLE IF NOT EXISTS shop.orders (user_id int, order_id int, total int, PRIMARY KEY (user_id, order_id));

-- Đổi sang STCS (Size-tiered) nếu tải ghi nặng
ALTER TABLE shop.orders WITH compaction = {
  'class': 'SizeTieredCompactionStrategy',
  'min_threshold': 8,
  'max_threshold': 32
};

-- Kiểm tra
SELECT compaction FROM system_schema.tables WHERE keyspace_name = 'shop' AND table_name = 'orders';

RISK: đổi strategy trên bảng lớn có thể kéo theo compaction lại nhiều SSTable (I/O tăng): thử trên một bảng ở giờ thấp tải trước.

Step C: Tune GC

text
# jvm-server.options (hoặc jvm17-server.options theo bản Java), mỗi dòng một tuỳ chọn
-Xms8G
-Xmx8G
bash
# Từng node một: drain rồi restart; chờ node UN (nodetool status) rồi mới sang node kế
nodetool drain
systemctl restart cassandra

Tăng heap chỉ khi GC log cho thấy thiếu heap, và chừa RAM cho page cache của SSTable.

Step D: Add SSD storage

bash
# Kiểm tra đĩa hiện tại
df -h /var/lib/cassandra/
  1. Mount SSD vào /mnt/ssd.
  2. Thêm đường dẫn mới vào data_file_directories trong cassandra.yaml (danh sách); đổi commitlog_directory (một đường dẫn) thì nodetool drain trước.
  3. Restart Cassandra từng node và theo dõi I/O.

Step E: Persist the compaction throughput

bash
# Giữ sau restart: dòng riêng trong cassandra.yaml (4.1+/5.0; tên cũ compaction_throughput_mb_per_sec)
# compaction_throughput: 128MiB/s

watch 'nodetool compactionstats'

Step F: Check compression

cql
-- Chạy sau khối tạo shop.orders ở Step B
SELECT compression FROM system_schema.tables WHERE keyspace_name = 'shop' AND table_name = 'orders';

-- Nén nặng tốn CPU khi compaction: đổi sang LZ4
ALTER TABLE shop.orders WITH compression = {
  'class': 'org.apache.cassandra.io.compress.LZ4Compressor',
  'chunk_length_in_kb': 64
};

SSTable đã ghi giữ cách nén cũ tới khi bị compaction ghi lại; nodetool upgradesstables -a shop orders ép ghi lại toàn bộ, tốn I/O: chỉ làm khi cần, giờ thấp tải.

POST-INCIDENT:

  • Xem lại chiến lược compaction theo tải (Cassandra 5.0: cân nhắc UnifiedCompactionStrategy; chiến lược cũ: nhiều đọc → LCS, nhiều ghi → STCS, chuỗi thời gian → TWCS)
  • Monitor compaction metrics daily (pending tasks, compaction latency)
  • Capacity plan to prevent disk fill (ví dụ minh hoạ: giữ < 70% utilization; STCS cần chừa chỗ trống cho compaction)
  • Consider upgrading to NVMe SSDs if disk-bound

Runbook 5: Neo4j Supernode Traversal Slowdown ​

INCIDENT: Graph traversal queries timeout or run >10 seconds, GC pressure increases

DETECTION:

cypher
// Số liệu đồ thị
CALL db.stats.retrieve('GRAPH COUNTS');

// Tìm supernode (quét mọi node User: trên graph lớn chạy ngoài giờ cao điểm)
MATCH (n:User) RETURN n.id, COUNT { (n)--() } AS deg ORDER BY deg DESC LIMIT 10;
  • Ngưỡng cảnh báo (ví dụ minh hoạ, đặt theo baseline): page cache hit ratio < 90% ở query nóng; GC pause > 500 ms.
  • Severity: P1 nếu traversal > 60 s (sắp timeout), P2 nếu > 10 s (user thấy chậm).

INVESTIGATION CHECKLIST:

Step 1: Check page cache hit ratio

text
Metric: <prefix>.page_cache.hit_ratio (endpoint metrics của Enterprise)

Decision (ngưỡng ví dụ minh hoạ):
IF page cache hit ratio < 90%
  → Hot graph không vừa bộ nhớ (Resolution Step A)
ELSE
  → Kiểm tra supernode (Investigation Step 2)

Step 2: Check supernode size

cypher
MATCH (n:User)
WITH n, COUNT { (n)--() } AS degree
WHERE degree > 10000
RETURN n.id, degree ORDER BY degree DESC LIMIT 10;
text
Decision (ngưỡng ví dụ minh hoạ):
IF max degree > 100000
  → Supernode exists (Resolution Step C)
ELSE IF max degree > 10000
  → Potential supernode (Resolution Step D)
ELSE
  → Query plan issue (Resolution Step E)

Step 3: Check query plan

cypher
PROFILE MATCH (a:User {id: 'user123'})-[:FOLLOWS]->(b:User)-[:LIKES]->(p:Post)
RETURN count(p);
text
Decision (ngưỡng ví dụ minh hoạ):
IF CartesianProduct trong plan
  → Query inefficient (Resolution Step F)
ELSE IF db hits > 1M
  → Traversal too broad (Resolution Step G)

RESOLUTION PROCEDURES:

Step A: Increase page cache

conf
# neo4j.conf (hoặc bỏ trống để Neo4j tự tính mặc định)
server.memory.pagecache.size=16g
bash
# Gợi ý cỡ heap và page cache theo RAM của máy (ví dụ 32g)
neo4j-admin server memory-recommendation --memory=32g

# Đổi neo4j.conf cần restart: downtime với một server; cluster thì restart từng server
systemctl restart neo4j
cypher
// Kiểm tra giá trị đang áp dụng
SHOW SETTINGS YIELD name, value WHERE name = 'server.memory.pagecache.size' RETURN name, value;

Step B (tuỳ chọn): Create relationship indexes

cypher
// Index thuộc tính quan hệ khi query lọc theo r.created_at
CREATE INDEX idx_follows_date IF NOT EXISTS
FOR ()-[r:FOLLOWS]-()
ON (r.created_at);

// Hoặc composite
CREATE INDEX idx_follows_composite IF NOT EXISTS
FOR ()-[r:FOLLOWS]-()
ON (r.created_at, r.weight);

// Kiểm tra
SHOW INDEXES;

Step C: Decompose supernode

cypher
// Chia follower của celebrity thành các nhóm; chạy lặp lại tới khi remaining = 0
// BEFORE: (follower)-[:FOLLOWS]->(celebrity)
// AFTER:  (follower)-[:MEMBER_OF]->(fg)<-[:HAS_FOLLOWER_GROUP]-(celebrity), mỗi nhóm một bucket
MATCH (u:User {id: 'celebrity'})
MATCH (follower:User)-[f:FOLLOWS]->(u)
WITH u, f, follower LIMIT 1000
WITH u, f, follower, toInteger(replace(follower.id, 'user', '')) % 3 AS bucket
MERGE (u)-[:HAS_FOLLOWER_GROUP]->(fg:FollowerGroup {id: 'celebrity_fg_' + bucket})
DELETE f
CREATE (follower)-[:MEMBER_OF]->(fg);

// Còn bao nhiêu quan hệ chưa chuyển
MATCH (:User {id: 'celebrity'})<-[r:FOLLOWS]-() RETURN count(r) AS remaining;

RISK: lệnh xoá quan hệ FOLLOWS và không hoàn tác được: sao lưu trước, thử trên bản sao, chạy ngoài giờ cao điểm; mọi query đọc FOLLOWS tới celebrity phải viết lại theo mô hình mới. Bucket ở ví dụ lấy từ phần số của id (mod 3): dùng khoá phân nhóm thật của bạn, một nhóm quá lớn lại thành supernode mới.

Step D: Add limiting to queries

cypher
// Thay vì:
MATCH (a:User {id: 'user123'})-[*1..5]->(x)
RETURN x;

// Dùng:
MATCH (a:User {id: 'user123'})-[*1..3]->(x)
RETURN x LIMIT 1000;

// Hoặc dừng sớm
MATCH (a:User {id: 'user123'})-[:FOLLOWS]->(b:User)
WHERE b.created_at > '2024-01-01'
RETURN b LIMIT 100;

Step E: Optimize query plan

cypher
// Gợi ý index (cần index trên User.id: constraint unique cũng tạo index)
MATCH (a:User) USING INDEX a:User(id)
WHERE a.id = 'user123'
MATCH (a)-[:FOLLOWS]->(b:User)
RETURN b;

// Hoặc lọc sớm
MATCH (a:User {id: 'user123'})-[:FOLLOWS]->(b:User)
WHERE b.active = true
RETURN b;

Step F: Rewrite complex query

cypher
// BEFORE: a và p không nối với nhau → CartesianProduct
MATCH (a:User {id: 'user1'}), (p:Post)
WHERE p.author = 'user2'
RETURN a.id, p.id;

// AFTER: nối a với p bằng quan hệ
MATCH (a:User {id: 'user1'})-[:LIKES]->(p:Post)
WHERE p.author = 'user2'
RETURN a.id, p.id;

Step G: Reduce traversal scope

cypher
// Giới hạn độ sâu, lọc thuộc tính sớm
MATCH (a:User {id: 'user1'})-[:FOLLOWS|LIKES*1..2]->(x)
WHERE x.created_at > '2024-01-01'
RETURN x LIMIT 100;
cypher
// minh hoạ, không chạy độc lập: cần plugin APOC (image neo4j:5 không có sẵn procedure apoc.*)
MATCH (a:User {id: 'user1'})
CALL apoc.path.expandConfig(a, {
  relationshipFilter: 'FOLLOWS|LIKES',
  maxLevel: 2,
  limit: 100
})
YIELD path
RETURN path;

POST-INCIDENT:

  • Review graph modeling for supernodes (ví dụ minh hoạ: decompose if degree > 10000)
  • Add indexes on hot relationship properties
  • Đặt giới hạn thời gian query: db.transaction.timeout (đo: mặc định 0s = không giới hạn); ví dụ minh hoạ 30s
  • Monitor page cache hit ratio (ví dụ minh hoạ: > 95% cho tải nóng)
  • Consider query caching for frequently run paths

Consolidated Alert Configuration Templates ​

Mẫu minh hoạ cho Prometheus, Grafana, CloudWatch: tên metric Prometheus phụ thuộc exporter và cấu hình, đối chiếu với endpoint đang chạy trước khi dùng. Đặt ngưỡng theo SLO và baseline đo được.

MongoDB Alerts (Prometheus + Grafana) ​

yaml
groups:
  - name: mongodb_alerts
    interval: 30s
    rules:
      # CRITICAL Alerts (P1)
      - alert: MongoDBReplicationLagCritical
        expr: mongodb_replset_member_replication_lag > 60
        for: 2m
        labels:
          severity: critical
          component: mongodb
        annotations:
          summary: "MongoDB replication lag critical on {{ $labels.instance }}"
          description: "Replication lag is {{ $value }}s (threshold: 60s). Risk of full resync."
          runbook: "See PART 10 Runbook 1: MongoDB Replication Lag"

      - alert: MongoDBOplogWindowLow
        # tên metric minh hoạ: exporter Percona không nêu metric cửa sổ oplog (cần --compatible-mode để có oplog_head/tail_timestamp); đối chiếu /metrics
        expr: mongodb_replset_oplog_window_seconds < 86400  # 24 hours
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "MongoDB oplog window below 24 hours"
          description: "Oplog window is {{ $value | humanizeDuration }}. Resize NOW."

      - alert: MongoDBConnectionsHigh
        expr: mongodb_connections{state="current"} / (mongodb_connections{state="current"} + mongodb_connections{state="available"}) > 0.8
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "MongoDB connections near limit"
          description: "{{ $value | humanizePercentage }} of connections (current + available) in use"

      # HIGH Alerts (P2)
      - alert: MongoDBSlowQuery
        # app_query_duration_seconds là histogram của ứng dụng (ví dụ minh hoạ, tên do ứng dụng đặt)
        expr: histogram_quantile(0.99, sum by (le) (rate(app_query_duration_seconds_bucket[5m]))) > 0.05
        for: 2m
        labels:
          severity: warning
        annotations:
          summary: "Slow query detected"
          description: "Query P99 latency > 50ms"

DynamoDB Alerts (CloudWatch) ​

bash
# Tạo CloudWatch alarm bằng AWS CLI. Thay Orders, REGION, ACCOUNT bằng giá trị thật.

# Alert 1: Throttling. ThrottledRequests có Dimensions TableName, Operation
# (thiếu dimension thì alarm không khớp dữ liệu): mỗi Operation một alarm
aws cloudwatch put-metric-alarm \
  --alarm-name dynamodb-orders-putitem-throttled \
  --metric-name ThrottledRequests \
  --namespace AWS/DynamoDB \
  --dimensions Name=TableName,Value=Orders Name=Operation,Value=PutItem \
  --statistic Sum \
  --period 60 \
  --evaluation-periods 1 \
  --threshold 10 \
  --comparison-operator GreaterThanThreshold \
  --alarm-actions arn:aws:sns:REGION:ACCOUNT:AlertTopic

# Alert 2: RCU tiêu thụ cao (bảng provisioned)
# Ngưỡng = 80% x RCU đã cấp x 300 giây; ví dụ minh hoạ: 1000 RCU -> 240000
aws cloudwatch put-metric-alarm \
  --alarm-name dynamodb-orders-high-rcu \
  --metric-name ConsumedReadCapacityUnits \
  --namespace AWS/DynamoDB \
  --dimensions Name=TableName,Value=Orders \
  --statistic Sum \
  --period 300 \
  --evaluation-periods 2 \
  --threshold 240000 \
  --comparison-operator GreaterThanThreshold \
  --alarm-actions arn:aws:sns:REGION:ACCOUNT:AlertTopic

# Alert 3: User Errors (HTTP 400, không gồm throttle và ConditionalCheckFailed)
# UserErrors là tổng theo Region và tài khoản: không cần dimension
aws cloudwatch put-metric-alarm \
  --alarm-name dynamodb-user-errors \
  --metric-name UserErrors \
  --namespace AWS/DynamoDB \
  --statistic Sum \
  --period 60 \
  --evaluation-periods 3 \
  --threshold 50 \
  --comparison-operator GreaterThanThreshold \
  --alarm-actions arn:aws:sns:REGION:ACCOUNT:AlertTopic

Redis Alerts (Prometheus) ​

yaml
groups:
  - name: redis_alerts
    interval: 30s
    rules:
      # CRITICAL
      - alert: RedisMemoryExceeded
        expr: redis_memory_used_bytes / redis_memory_max_bytes > 0.9 and redis_memory_max_bytes > 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Redis memory usage critical"
          description: "Memory {{ $value | humanizePercentage }} of max"

      - alert: RedisEvictionsHigh
        expr: rate(redis_evicted_keys_total[5m]) > 100
        for: 2m
        labels:
          severity: warning
        annotations:
          summary: "Redis key evictions detected"
          description: "{{ $value }} keys/sec being evicted"

      - alert: RedisMissingMaster
        # redis_up không có nhãn role (README redis_exporter không nêu); cờ --append-instance-role-label thêm nhãn instance_role
        expr: redis_up{instance_role="master"} == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Redis master unavailable"
          description: "Master instance is down or unreachable"

      # HIGH
      - alert: RedisFragmentationHigh
        expr: redis_memory_fragmentation_ratio > 1.5
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Redis memory fragmentation high"
          description: "Fragmentation ratio {{ $value }}. Xem Runbook 3 Step A (active defrag); restart là phương án cuối."

Cassandra Alerts (Prometheus) ​

yaml
groups:
  - name: cassandra_alerts
    interval: 30s
    rules:
      # CRITICAL
      - alert: CassandraCompactionBacklog
        expr: cassandra_compaction_pending_tasks > 50
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "Cassandra compaction backlog critical"
          description: "{{ $value }} pending compactions"

      - alert: CassandraNodeDown
        expr: cassandra_up == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Cassandra node down"
          description: "Node {{ $labels.instance }} is not responding"

      - alert: CassandraHighReadLatency
        expr: cassandra_read_latency > 100000  # microseconds
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Cassandra read latency high"
          description: "P99 read latency {{ $value }}μs (threshold: 100ms)"

      # HIGH
      - alert: CassandraCommitLogUsage
        expr: cassandra_commitlog_disk_used_bytes / cassandra_commitlog_disk_total_bytes > 0.9
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Cassandra commitlog disk usage high"
          description: "{{ $value | humanizePercentage }} disk used"

Neo4j Alerts (JMX via Prometheus) ​

Tên metric Prometheus dưới đây là ví dụ minh hoạ: đối chiếu với endpoint đang chạy. Tên gốc theo doc: <prefix>.page_cache.hit_ratio, <prefix>.vm.heap.used, <prefix>.vm.heap.max, <prefix>.vm.gc.time.<gc>. Doc không liệt kê metric "query timeout" (gần nhất: <prefix>.transaction.terminated, <prefix>.db.query.execution.failure), nên neo4j_query_timeout_count chỉ là tên minh hoạ.

yaml
groups:
  - name: neo4j_alerts
    interval: 30s
    rules:
      # CRITICAL
      - alert: Neo4jPageCacheHitRatioLow
        expr: neo4j_page_cache_hit_ratio < 0.90
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Neo4j page cache hit ratio below 90%"
          description: "Cache hit ratio: {{ $value | humanizePercentage }}"

      - alert: Neo4jHeapUsageHigh
        expr: neo4j_heap_used_bytes / neo4j_heap_max_bytes > 0.85
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Neo4j heap usage high"
          description: "Heap {{ $value | humanizePercentage }} in use"

      - alert: Neo4jGCPauseTimeLong
        expr: neo4j_gc_pause_time_seconds > 0.5
        for: 3m
        labels:
          severity: warning
        annotations:
          summary: "Neo4j GC pause time high"
          description: "GC pausing {{ $value }}s (threshold: 500ms)"

      # HIGH
      - alert: Neo4jQueryTimeoutHigh
        expr: rate(neo4j_query_timeout_count[5m]) > 10
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "Neo4j query timeouts increasing"
          description: "{{ $value }} timeouts/sec"

Quick Alert Thresholds Reference:

Cơ sở dữ liệuMetricNgưỡng P2Ngưỡng P1Hành động
MongoDBReplication Lag>10s>60sXem Runbook 1
MongoDBOplog Window<48h<24hĐổi cỡ oplog
DynamoDBThrottled Requests>10/min>50/minXem Runbook 2 (khoá nóng) trước khi tăng capacity
DynamoDBConsumedRCU>80%>95%Tăng capacity
RedisMemory Used>70%>90%Tăng bộ nhớ
RedisEvictions>100/s>1000/sGiảm TTL hoặc số khoá
CassandraCompaction Pending>10>50Xem Runbook 4
CassandraRead Latency>50ms>100msKiểm tra I/O đĩa
Neo4jPage Cache Hit<92%<90%Tăng page cache
Neo4jHeap Usage>75%>85%Tăng heap JVM

Mọi ngưỡng trong bảng là ví dụ minh hoạ: đặt theo baseline và SLO đo được.

Phải nhớ (Troubleshooting & Monitoring) ​

  • Đo trước, kết luận sau: đọc đúng trường và metric mà hệ thống in ra (ví dụ db.getReplicationInfo().timeDiffHours, opcounters là bộ đếm cộng dồn), ngưỡng đặt theo baseline.
  • Lệnh chẩn đoán nặng (--bigkeys, quét toàn collection, PROFILE trên graph lớn) chạy trên replica hoặc giờ thấp tải; kill, restart, đổi cấu hình cần người duyệt và đường lui.
  • Throttle DynamoDB không nằm trong UserErrors, và khoá nóng không chữa bằng On-Demand hay tăng capacity của bảng.

PART 10 gồm: 5 runbook sự cố (MongoDB, DynamoDB, Redis, Cassandra, Neo4j), mẫu cảnh báo và workflow chẩn đoán.