Appearance
PART 7: ANTI-PATTERNS & PITFALLS
MongoDB Anti-Patterns
1. Unbounded array
Mảng nằm trong tài liệu chỉ lớn thêm, tới khi chạm giới hạn 16 MiB của một tài liệu BSON thì ghi bị từ chối.
javascript
// mongosh. Chạy trên DB sạch. Mỗi $push dưới đây thêm ~9 MiB chỉ để chạm giới hạn 16 MiB nhanh.
// ❌ SAI: bình luận nằm trong mảng của tài liệu bài viết, mảng chỉ lớn thêm
db = db.getSiblingDB("n15")
db.posts.insertOne({ _id: "post123", title: "My Post", comments: [] })
db.posts.updateOne({ _id: "post123" }, { $push: { comments: { user: "alice", text: "x".repeat(9 * 1024 * 1024) } } })
db.posts.updateOne({ _id: "post123" }, { $push: { comments: { user: "bob", text: "x".repeat(9 * 1024 * 1024) } } })Kết quả mẫu (mongo:8, lệnh $push thứ hai):
text
MongoServerError: Plan executor error during update :: caused by :: Resulting document after update is larger than 16777216javascript
// mongosh. Chạy trên DB sạch (độc lập với khối SAI ở trên).
// ✓ ĐÚNG: collection comments riêng, phân trang theo createdAt
db = db.getSiblingDB("n15")
db.posts.insertOne({ _id: "post123", title: "My Post", commentCount: 0 })
db.comments.createIndex({ postId: 1, createdAt: -1 })
for (let i = 0; i < 50; i++) {
db.comments.insertOne({ postId: "post123", user: "alice", text: "Nice " + i, createdAt: new Date(Date.UTC(2026, 10, 1, 0, i)) })
db.posts.updateOne({ _id: "post123" }, { $inc: { commentCount: 1 } })
}
// Trang 1: 20 bình luận mới nhất
const page1 = db.comments.find({ postId: "post123" }).sort({ createdAt: -1 }).limit(20).toArray()
// Trang kế: bình luận cũ hơn bình luận cuối của trang trước (tránh skip phải duyệt bỏ N tài liệu)
const last = page1[page1.length - 1].createdAt
db.comments.find({ postId: "post123", createdAt: { $lt: last } }).sort({ createdAt: -1 }).limit(20)Dùng khi: danh sách con tăng theo thời gian (bình luận, log, sự kiện). Đừng dùng khi: danh sách có chặn trên nhỏ và luôn đọc cùng cha. skip(N) phải duyệt bỏ N tài liệu nên chậm dần ở trang sâu; dùng điều kiện createdAt < trang trước như trên. Xem War Story 3 (16MB Document Size Trap) ở PART 1.
2. Using ObjectId as business identifier
ObjectId có 4 byte đầu là timestamp tính theo giây, nên định danh công khai lộ thời điểm tạo và các tài liệu tạo cùng lúc có giá trị gần nhau. Giữ làm _id nội bộ, đừng coi là bí mật hay là kiểm soát truy cập.
javascript
// mongosh. Chạy trên DB sạch.
db = db.getSiblingDB("n15")
// ❌ SAI: đưa ObjectId ra làm định danh công khai (ví dụ GET /api/users/507f1f77bcf86cd799439011)
// 4 byte đầu của ObjectId là timestamp nên định danh lộ thời điểm tạo:
ObjectId("507f1f77bcf86cd799439011").getTimestamp()
// ✓ ĐÚNG: giữ _id nội bộ, thêm định danh công khai ngẫu nhiên có unique index
db.users.createIndex({ userId: 1 }, { unique: true })
db.users.insertOne({ userId: UUID().toString("hex"), email: "user@example.com" })
const user = db.users.findOne({ email: "user@example.com" })
db.users.findOne({ userId: user.userId })Định danh công khai ngẫu nhiên khó đoán hơn mã tuần tự như USR-2847; vẫn phải kiểm tra quyền truy cập ở mỗi request.
3. Not using projection
Lấy cả tài liệu làm tăng byte truyền qua mạng và số việc giải mã ở client, kể cả khi chỉ cần hai trường.
javascript
// mongosh. Chạy trên DB sạch.
db = db.getSiblingDB("n15")
db.users.insertMany(Array.from({ length: 1000 }, (_, i) => ({
name: "user" + i, email: "user" + i + "@example.com", status: "active", bio: "x".repeat(50000)
})))
// ❌ SAI: lấy mọi trường
const full = db.users.find({ status: "active" }).toArray()
bsonsize(full[0]) // byte của một tài liệu đầy đủ
// ✓ ĐÚNG: chỉ lấy trường cần dùng
const slim = db.users.find({ status: "active" }, { name: 1, email: 1, _id: 0 }).toArray()
bsonsize(slim[0]) // byte của một tài liệu đã projectKết quả đo (mongo:8, tài liệu có bio 50 000 ký tự): bsonsize(full[0]) = 50096 byte, bsonsize(slim[0]) = 50 byte, tức khoảng 1000 lần nhỏ hơn (đổi theo dữ liệu của bạn).
DynamoDB Anti-Patterns
1. Using Scan in production
FilterExpression lọc SAU khi đọc: Scan đọc và tính tiền toàn bộ item đã duyệt, không phải chỉ item khớp.
javascript
// Node.js (AWS SDK v3, ESM). Chạy với dynamodb-local: AWS_ENDPOINT_URL=http://localhost:8000 AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID=local AWS_SECRET_ACCESS_KEY=local
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand, QueryCommand, ScanCommand } from '@aws-sdk/lib-dynamodb'
const dynamodb = DynamoDBDocumentClient.from(new DynamoDBClient({}))
// Fixture: bảng Users có GSI email-index, 200 item, mỗi item khoảng 2 KB
await dynamodb.send(new CreateTableCommand({
TableName: 'Users',
BillingMode: 'PAY_PER_REQUEST',
AttributeDefinitions: [
{ AttributeName: 'userId', AttributeType: 'S' },
{ AttributeName: 'email', AttributeType: 'S' }
],
KeySchema: [{ AttributeName: 'userId', KeyType: 'HASH' }],
GlobalSecondaryIndexes: [{
IndexName: 'email-index',
KeySchema: [{ AttributeName: 'email', KeyType: 'HASH' }],
Projection: { ProjectionType: 'ALL' }
}]
}))
for (let i = 0; i < 200; i++) {
await dynamodb.send(new PutCommand({
TableName: 'Users',
Item: { userId: `u${i}`, email: `user${i}@example.com`, bio: 'x'.repeat(2000) }
}))
}
// ❌ SAI: Scan đọc mọi item, FilterExpression chỉ lọc SAU khi đọc nên vẫn tính tiền đọc
const scan = await dynamodb.send(new ScanCommand({
TableName: 'Users',
FilterExpression: 'email = :email',
ExpressionAttributeValues: { ':email': 'user42@example.com' },
ReturnConsumedCapacity: 'TOTAL'
}))
console.log('Scan', scan.ScannedCount, scan.Count, scan.ConsumedCapacity.CapacityUnits)
// ✓ ĐÚNG: Query theo GSI email-index
const query = await dynamodb.send(new QueryCommand({
TableName: 'Users',
IndexName: 'email-index',
KeyConditionExpression: 'email = :email',
ExpressionAttributeValues: { ':email': 'user42@example.com' },
ReturnConsumedCapacity: 'TOTAL'
}))
console.log('Query', query.ScannedCount, query.Count, query.ConsumedCapacity.CapacityUnits)Kết quả đo (dynamodb-local, 200 item x ~2 KB):
text
Scan ScannedCount=200 Count=1 CapacityUnits=50
Query ScannedCount=1 Count=1 CapacityUnits=0.5Phép tính cho bảng 10 triệu item x 2 KB = 20 GB: 5 triệu đơn vị 4 KB; Scan mặc định eventually consistent tính 0,5 RRU mỗi đơn vị, tức 2,5 triệu RRU = $0,3125 mỗi lần quét (on-demand us-east-1, kiểm 2026-11-20: $0,125 mỗi triệu RRU, trang giá); ConsistentRead: true gấp đôi, $0,625. Mỗi trang Scan tối đa 1 MB nên phải lặp theo LastEvaluatedKey. Xem War Story 1 (Scan trên dashboard) ở PART 1.
2. Over-normalized data
Chuẩn hoá kiểu SQL buộc nhiều lần gọi để dựng một màn hình. Khi access pattern đã biết, đặt dữ liệu đọc chung vào cùng một item collection.
javascript
// Node.js (AWS SDK v3, ESM). Chạy trên dynamodb-local, như khối Scan/Query ở trên.
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'
const dynamodb = DynamoDBDocumentClient.from(new DynamoDBClient({}))
// ❌ Chuẩn hoá kiểu SQL: ba bảng Users, Posts, Comments => GetItem + GetItem + Query = 3 lần gọi
// ✓ Denormalize: một bảng, tên tác giả chép vào item bài viết, đọc cả bài và bình luận bằng 1 Query
await dynamodb.send(new CreateTableCommand({
TableName: 'App',
BillingMode: 'PAY_PER_REQUEST',
AttributeDefinitions: [
{ AttributeName: 'PK', AttributeType: 'S' },
{ AttributeName: 'SK', AttributeType: 'S' }
],
KeySchema: [
{ AttributeName: 'PK', KeyType: 'HASH' },
{ AttributeName: 'SK', KeyType: 'RANGE' }
]
}))
const items = [
{ PK: 'USER#123', SK: 'PROFILE', name: 'Alice' },
{ PK: 'POST#456', SK: 'METADATA', title: 'My Post', authorName: 'Alice' },
{ PK: 'POST#456', SK: 'COMMENT#001', text: 'Nice!' },
{ PK: 'POST#456', SK: 'COMMENT#002', text: 'Great!' }
]
for (const Item of items) await dynamodb.send(new PutCommand({ TableName: 'App', Item }))
const result = await dynamodb.send(new QueryCommand({
TableName: 'App',
KeyConditionExpression: 'PK = :pk',
ExpressionAttributeValues: { ':pk': 'POST#456' }
}))
console.log(result.Items.map(i => i.SK))Kết quả mẫu: [ 'COMMENT#001', 'COMMENT#002', 'METADATA' ]. Đánh đổi: tên tác giả bị chép (denormalize), đổi tên thì phải cập nhật mọi nơi chép; đo độ trễ từng cách bằng chính dữ liệu của bạn. Single-table không bắt buộc cho mọi ứng dụng.
3. Hot partitions
Một giá trị PK nhận mọi ghi trong ngày dồn tải vào một partition. Mỗi partition thiết kế cho tối đa 3 000 read unit và 1 000 write unit mỗi giây (write unit = 1 ghi/giây cho item tới 1 KB). Adaptive capacity có thể tách item collection của bảng có sort key (không có LSI) khi tải lệch, nhưng AWS không bảo đảm; đừng dựa vào nó thay cho thiết kế key. Theo dõi bằng metric WriteKeyRangeThroughputThrottleEvents / ReadKeyRangeThroughputThrottleEvents và CloudWatch Contributor Insights.
javascript
// Node.js (AWS SDK v3, ESM). Chạy trên dynamodb-local, như khối Scan/Query ở trên.
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, PutCommand, QueryCommand } from '@aws-sdk/lib-dynamodb'
const dynamodb = DynamoDBDocumentClient.from(new DynamoDBClient({}))
await dynamodb.send(new CreateTableCommand({
TableName: 'Events',
BillingMode: 'PAY_PER_REQUEST',
AttributeDefinitions: [
{ AttributeName: 'PK', AttributeType: 'S' },
{ AttributeName: 'SK', AttributeType: 'S' }
],
KeySchema: [
{ AttributeName: 'PK', KeyType: 'HASH' },
{ AttributeName: 'SK', KeyType: 'RANGE' }
]
}))
// ❌ SAI: mọi ghi trong ngày dùng chung một giá trị PK
// PK = '2025-01-09'
// ✓ ĐÚNG: write sharding, chia PK thành 10 giá trị bằng hậu tố tính từ userId (số nguyên)
const SHARDS = 10
for (let userId = 1; userId <= 30; userId++) {
await dynamodb.send(new PutCommand({
TableName: 'Events',
Item: { PK: `2025-01-09#${userId % SHARDS}`, SK: `${Date.now()}#${userId}`, userId }
}))
}
// Đọc: Query từng shard song song rồi gộp
const results = await Promise.all(Array.from({ length: SHARDS }, (_, i) =>
dynamodb.send(new QueryCommand({
TableName: 'Events',
KeyConditionExpression: 'PK = :pk',
ExpressionAttributeValues: { ':pk': `2025-01-09#${i}` }
}))
))
const merged = results.flatMap(r => r.Items)
console.log(merged.length)Kết quả mẫu: 30. Sharding 10 giá trị nâng trần ghi của một ngày lên khoảng 10 lần (tối đa 10 000 write unit/giây nếu tải chia đều), đổi lại mỗi lần đọc cả ngày phải gọi 10 Query.
Redis Anti-Patterns
1. Using KEYS in production
KEYS là O(N) theo số key và chạy trong luồng lệnh chính nên chặn mọi client khác tới khi xong. Doc Redis: dùng cho gỡ lỗi và thao tác đặc biệt, không dùng trong code ứng dụng thường.
bash
# Redis 8, chạy trên instance thử. Fixture: 1 triệu key user:*
redis-cli EVAL "for i=1,1000000 do redis.call('SET','user:'..i,'x') end return 1" 0
# ❌ SAI: KEYS là O(N) và chặn mọi lệnh khác tới khi xong
redis-cli KEYS 'user:*' | wc -l
# ✓ ĐÚNG: SCAN theo con trỏ, mỗi lần trả một phần (COUNT chỉ là gợi ý, key có thể lặp lại)
redis-cli SCAN 0 MATCH 'user:*' COUNT 100
# redis-cli --scan lặp SCAN tới khi con trỏ về 0
redis-cli --scan --pattern 'user:*' | wc -lKết quả đo (redis:8 trong Docker, 1 triệu key, đổi theo máy):
text
KEYS 'user:*' 387 ms (gồm truyền 1 triệu tên key qua redis-cli)
PING gửi lúc KEYS đang chạy phải đợi 122 msTài liệu Redis ghi khoảng 40 ms cho 1 triệu key trên laptop; thời gian tăng theo số key, nên đo trên bản sao dữ liệu thật. SCAN trả một phần mỗi lần, key có thể lặp lại, nên xử lý idempotent. Với client Python:
python
# Python (redis-py), cần Redis local; chạy sau khối fixture user:* ở trên
import redis
r = redis.Redis(decode_responses=True)
keys = list(r.scan_iter(match='user:*', count=100))
print(len(keys))Xem War Story 1 (KEYS) ở PART 1 cho kịch bản minh hoạ.
2. Not setting TTL
Key không có TTL sống mãi. Khi bộ nhớ chạm maxmemory, Redis xoá key theo maxmemory-policy; với noeviction thì lệnh ghi bị từ chối với lỗi OOM (đã đo: OOM command not allowed when used memory > 'maxmemory').
bash
# Redis 8
# ❌ SAI: không đặt TTL, key sống mãi dù người dùng đã đăng xuất
redis-cli SET session:abc123 '{"user":"alice"}'
redis-cli TTL session:abc123
# ✓ ĐÚNG: SET ... EX đặt giá trị và TTL trong một lệnh nguyên tử
redis-cli SET session:abc123 '{"user":"alice"}' EX 3600
redis-cli TTL session:abc123
# Ghi đè bằng SET thường sẽ xoá TTL; thêm KEEPTTL để giữ
redis-cli SET session:abc123 '{"user":"bob"}' KEEPTTL
redis-cli TTL session:abc123Kết quả mẫu: TTL lần đầu -1 (không hết hạn), sau SET ... EX 3600 là 3600, sau KEEPTTL vẫn 3600. SET rồi EXPIRE rời nhau không nguyên tử: lỗi giữa hai lệnh để lại key không TTL. Doc: SET thường xoá TTL cũ, nên ghi đè session phải dùng KEEPTTL hoặc đặt lại EX. TTL trả -2 khi key không tồn tại.
3. Large values
Giá trị hàng MB làm mỗi GET tốn băng thông và thời gian trong luồng lệnh chính, và nhân bản tới mọi replica. Xoá key lớn bằng UNLINK (giải phóng bộ nhớ ở luồng khác) thay vì DEL.
javascript
// Node.js (ioredis), cần Redis local. Phương án 3 (S3) chỉ là mô tả, không có code.
import Redis from 'ioredis'
import zlib from 'node:zlib'
const redis = new Redis()
const largeReport = JSON.stringify({
rows: Array.from({ length: 200000 }, (_, i) => ({ id: i, name: `item-${i}`, score: i % 97 }))
})
console.log('bytes', Buffer.byteLength(largeReport))
// ❌ SAI: một giá trị hàng MB cho mỗi GET
await redis.set('report:2025', largeReport)
// ✓ Phương án 1: chia chunk nhỏ, ghi cả bộ trong MULTI
const CHUNK = 100 * 1024
const tx = redis.multi()
for (let i = 0, n = 0; i < largeReport.length; i += CHUNK, n++) {
tx.set(`report:2025:chunk:${n}`, largeReport.slice(i, i + CHUNK))
}
await tx.exec()
// ✓ Phương án 2: nén trước khi lưu
const compressed = zlib.gzipSync(largeReport)
await redis.set('report:2025:gz', compressed)
console.log('gzip bytes', compressed.length)
await redis.quit()Kết quả đo (JSON giả 200 000 dòng): 8 957 170 byte, sau gzip 1 278 632 byte (tỉ lệ nén đổi theo dữ liệu); GET giá trị 9 MB mất 19 ms trên máy này, lặp lại với mỗi lượt đọc. Phương án 3: lưu đối tượng ở S3 hoặc kho bền khác, Redis chỉ giữ URL kèm TTL (redis-cli SET report:2025:url <URL> EX 3600).
Cassandra Anti-Patterns
1. Using secondary indexes
Index phụ gốc là một bảng ẩn cục bộ (doc: legacy secondary index, implemented as a hidden local table); doc không nêu chi phí theo số nút hay theo cardinality, đo bằng tracing trên cụm của bạn. SAI (Cassandra 5.0) theo doc có nhiều chức năng hơn 2i và hiệu năng ít nhất tương đương.
Fixture (khối đầu của mục này, chạy trước hai khối dưới):
cql
-- Cassandra 5.0
CREATE KEYSPACE IF NOT EXISTS demo WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1};
USE demo;
CREATE TABLE users (
user_id uuid PRIMARY KEY,
email text,
name text,
age int,
created_at timestamp
);
INSERT INTO users (user_id, email, name, age, created_at) VALUES (uuid(), 'user@example.com', 'Alice', 30, toTimestamp(now()));
INSERT INTO users (user_id, email, name, age, created_at) VALUES (uuid(), 'bob@example.com', 'Bob', 20, toTimestamp(now()));cql
-- Cassandra 5.0. Chạy sau khối tạo bảng users ở đầu mục này.
-- ❌ SAI: index phụ gốc trên cột có cardinality cao (email gần như duy nhất)
CREATE INDEX users_email_idx ON users (email);
SELECT * FROM users WHERE email = 'user@example.com';
-- ✓ ĐÚNG 1: bảng riêng theo truy vấn, email là partition key; ứng dụng ghi cả hai bảng
CREATE TABLE users_by_email (
email text PRIMARY KEY,
user_id uuid,
name text,
created_at timestamp
);
BEGIN BATCH
INSERT INTO users (user_id, email, name, age, created_at)
VALUES (11111111-1111-1111-1111-111111111111, 'carol@example.com', 'Carol', 28, '2026-11-01 00:00:00+0000');
INSERT INTO users_by_email (email, user_id, name, created_at)
VALUES ('carol@example.com', 11111111-1111-1111-1111-111111111111, 'Carol', '2026-11-01 00:00:00+0000');
APPLY BATCH;
SELECT * FROM users_by_email WHERE email = 'carol@example.com';
-- ✓ ĐÚNG 2: SAI (Storage-Attached Index, Cassandra 5.0) thay cho index phụ gốc
DROP INDEX users_email_idx;
CREATE INDEX users_email_sai ON users (email) USING 'sai';
SELECT * FROM users WHERE email = 'user@example.com';Index xây ở nền: nếu SELECT ngay sau CREATE INDEX báo lỗi (INDEX_NOT_AVAILABLE với SAI), đợi vài giây rồi chạy lại. Materialized view tắt mặc định (materialized_views_enabled: false); thử tạo trả Materialized views are disabled. Enable in cassandra.yaml to use., nên không dùng thay cho bảng theo truy vấn.
2. ALLOW FILTERING
ALLOW FILTERING cho phép lọc cột không có index và có thể quét toàn bộ dữ liệu, nên thời gian phụ thuộc kích thước bảng và có thể timeout. Thiếu nó, Cassandra từ chối:
text
InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot execute this query as it might involve data filtering and thus may have unpredictable performance. If you want to execute this query despite the performance unpredictability, use ALLOW FILTERING"cql
-- Cassandra 5.0. Chạy sau khối tạo bảng users ở đầu mục "Using secondary indexes".
-- ❌ SAI: lọc cột thường, không có index
SELECT * FROM users WHERE age > 25;
SELECT * FROM users WHERE age > 25 ALLOW FILTERING;
-- ✓ ĐÚNG: SAI hỗ trợ truy vấn khoảng trên cột số
CREATE INDEX users_age_sai ON users (age) USING 'sai';
SELECT * FROM users WHERE age > 25;Truy vấn khoảng (>) trên cột thường cần SAI hoặc thiết kế khoá phân cụm; bảng theo truy vấn có age làm partition key chỉ giải quyết truy vấn bằng (age = 25); truy vấn khoảng cần SAI hoặc age làm cột phân cụm trong một partition.
3. Reads before writes
Đọc rồi ghi lại giá trị cũ cộng một tốn hai lượt gọi, và hai client đồng thời có thể ghi đè nhau (mất cập nhật).
cql
-- Cassandra 5.0. Chạy sau khi USE demo; (keyspace tạo ở khối fixture).
-- ❌ SAI: đọc rồi ghi lại giá trị cũ cộng một
CREATE TABLE page_views_plain (id text PRIMARY KEY, views bigint);
INSERT INTO page_views_plain (id, views) VALUES ('page_views', 12347);
SELECT views FROM page_views_plain WHERE id = 'page_views';
UPDATE page_views_plain SET views = 12348 WHERE id = 'page_views';
-- ✓ ĐÚNG: cột counter, tăng bằng một lệnh, không cần đọc trước
CREATE TABLE page_views (id text PRIMARY KEY, views counter);
UPDATE page_views SET views = views + 1 WHERE id = 'page_views';
SELECT views FROM page_views WHERE id = 'page_views';Cột counter tăng bằng một lệnh, không đọc trước. Đánh đổi: thao tác counter không idempotent, retry sau timeout có thể đếm lặp, nên dùng cho số liệu chấp nhận sai lệch nhỏ.
Neo4j Anti-Patterns
1. Dense supernodes
Nút hub nối tới mọi nút cùng loại gom toàn bộ quan hệ vào một nút: duyệt qua nó phải đi hết các quan hệ MEMBER. Nếu chỉ cần liệt kê User, quét theo nhãn không cần hub.
Fixture (chạy trước các khối Cypher của PART này):
cypher
// Fixture: 2000 User, 50 Product, quan hệ PURCHASED và KNOWS
UNWIND range(1, 2000) AS i CREATE (:User {id: i, created: '2025-0' + toString(1 + i % 9) + '-15'});
UNWIND range(1, 50) AS i CREATE (:Product {id: i, name: 'p' + i, category: CASE WHEN i % 4 = 0 THEN 'books' ELSE 'toys' END});
MATCH (u:User), (p:Product) WHERE (u.id * 7 + p.id) % 25 = 0 CREATE (u)-[:PURCHASED]->(p);
MATCH (a:User), (b:User) WHERE a.id < b.id AND (a.id * 31 + b.id * 17) % 100 = 0 CREATE (a)-[:KNOWS]->(b);cypher
// Neo4j 5. Chạy sau khối fixture User ở đầu mục.
// ❌ SAI: một nút hub nối tới mọi User
CREATE (g:AllUsers) WITH g MATCH (u:User) CREATE (g)-[:MEMBER]->(u);
MATCH (g:AllUsers) RETURN COUNT { (g)-[:MEMBER]->() } AS rels;
// ✓ ĐÚNG: dùng nhãn User, không cần nút hub
EXPLAIN MATCH (u:User) RETURN u;
// Hoặc chia hub theo tháng, mỗi nhóm giữ số quan hệ nhỏ hơn nhiều
MERGE (g:UserGroup {month: '2025-01'})
WITH g
MATCH (u:User) WHERE u.created STARTS WITH '2025-01'
CREATE (g)-[:MEMBER]->(u);
MATCH (g:UserGroup {month: '2025-01'}) RETURN COUNT { (g)-[:MEMBER]->() } AS rels;Kết quả đo (Neo4j 5.26, 2 000 User): hub AllUsers có 2000 quan hệ, mỗi nhóm tháng có 222; plan của MATCH (u:User) RETURN u là NodeByLabelScan. Với dữ liệu thật số quan hệ lớn hơn nhiều: xem War Story 1 (Supernode) ở PART 3.
2. Cartesian products
Hai mẫu MATCH rời nhau tạo toán tử CartesianProduct: nhánh phải chạy lại cho mỗi hàng của nhánh trái, nên số db hits nhân lên.
cypher
// Neo4j 5. Chạy sau khối fixture User/Product ở đầu mục.
// ❌ SAI: hai mẫu rời nhau, nối bằng điều kiện lọc sau cùng
PROFILE MATCH (u:User), (p:Product)
WHERE u.id = 3 AND p.category = 'books' AND EXISTS { (u)-[:PURCHASED]->(p) }
RETURN p.name;
// ✓ ĐÚNG: mẫu nối u với p bằng quan hệ
PROFILE MATCH (u:User {id: 3})-[:PURCHASED]->(p:Product {category: 'books'})
RETURN p.name;Kết quả đo (Neo4j 5.26, 2 000 User, 50 Product, PROFILE): bản trên khoảng 48 nghìn db hits (CartesianProduct 12 hàng sản phẩm x quét 2000 User, NodeByLabelScan 24 000 hàng); bản dưới khoảng 2 nghìn. Thêm index trên User(id) và Product(category) giúp cả hai bản. Xem War Story 3 (Cartesian Product) ở PART 3.
3. Unbounded variable-length path
Số đường đi tăng gần theo bậc^độ sâu. Giới hạn độ sâu trước, thêm LIMIT sau; LIMIT chỉ dừng sớm khi truy vấn không phải sắp xếp hay gộp toàn bộ kết quả (đo trên 5.26, độ sâu 5, LIMIT 100: 2 535 db hits; thêm ORDER BY length(path) DESC: 5 789 783).
cypher
// Neo4j 5. Chạy sau khối fixture User/KNOWS ở đầu mục.
// ❌ SAI: số hop lớn, không LIMIT
MATCH path = (u1:User {id: 1})-[:KNOWS*1..5]-(u2:User)
RETURN path;
// ✓ ĐÚNG: ít hop, có LIMIT
MATCH path = (u1:User {id: 1})-[:KNOWS*1..2]-(u2:User)
RETURN path
LIMIT 100;Kết quả đo (Neo4j 5.26, 2 000 User, mỗi nút khoảng 20 quan hệ KNOWS, nút bắt đầu id 1), số đường đi theo độ sâu tối đa:
text
*1..2 400
*1..3 7 620
*1..4 144 800
*1..5 2 746 660Với đồ thị thật có bậc 52, cận trên 52^5 cỡ 380 triệu đường đi (phép tính lý thuyết, không phải số đo). Xem War Story 2 (3-Hop Traversal) ở PART 3.
Khi nào KHÔNG dùng từng DB (When NOT to Use)
Năm mục dưới (MongoDB, DynamoDB, Redis, Cassandra, Neo4j) liệt kê trường hợp mỗi DB không phù hợp và DB thay thế.
When NOT to Use MongoDB ❌
Purpose: Identify scenarios where MongoDB is the wrong tool, saving you from costly architectural mistakes. Each anti-pattern includes specific alternatives and decision criteria.
Mọi số độ trễ, giá, thông lượng và số document trong mục này là ví dụ minh hoạ, không phải benchmark có nguồn: đo bằng workload của bạn trước khi quyết định.
1. Sub-millisecond latency requirement (P99 < 5ms)
❌ Don't use: MongoDB for session storage requiring P99 < 1ms
✅ Use instead: Redis (in-memory, P99 < 1ms)
✅ Hybrid approach: Redis cache (hot data) + MongoDB (persistent store)
Why MongoDB doesn't fit:
- Disk-based storage → typical P99 latency 5-20ms
- WiredTiger cache helps but still slower than pure in-memory
- Network + query execution overhead
Example: User session store with 1M active users
MongoDB Atlas M40: P99 = 8ms, $600/month
Redis Cloud 25GB: P99 = 0.5ms, $180/month
→ Redis is 16x faster and 3x cheaper2. Write-heavy workload (>50K sustained writes/sec)
❌ Don't use: MongoDB for IoT sensor data (100K writes/sec)
✅ Use instead: Cassandra (ghi phân tán qua token ring; mức mở rộng đo bằng benchmark của bạn)
Why MongoDB doesn't fit:
- Mỗi replica set có một primary nhận ghi (sharding thêm primary theo từng shard, đổi lại độ phức tạp vận hành)
- Replication lag increases under high write load
- Sharding helps but adds complexity
Benchmark comparison (10-node cluster):
MongoDB sharded: ~50K writes/sec (limited by primary in each shard)
Cassandra: 500K+ writes/sec (all nodes accept writes)
→ Cassandra 10x better for write-heavy workloads3. True serverless with unpredictable traffic (0 → 10K QPS spikes)
❌ Don't use: MongoDB for weekend-only analytics dashboard
✅ Use instead: DynamoDB (instant scaling, pay-per-request)
Why MongoDB doesn't fit:
- Cụm cấp phát sẵn tính tiền theo giờ chạy, kể cả khi 0 QPS (Atlas có tầng Flex, tra bảng giá hiện hành)
- Auto-scaling cụm cần thời gian (đo trên cụm của bạn; doc không nêu số phút)
- DynamoDB on-demand tính theo request nên không có chi phí request khi 0 QPS (vẫn tính dung lượng lưu)
Cost example (traffic pattern: 0 QPS Mon-Fri, 10K QPS weekends):
MongoDB Atlas M30: $0.54/hr × 730 hrs = $394/month (runs 24/7)
DynamoDB On-Demand: $0 (weekdays) + $50 (weekends) = $50/month
→ DynamoDB 8x cheaper for spiky workloads4. Simple key-value lookups only (no complex queries)
❌ Don't use: MongoDB for rate limiting (key = userId, value = count)
✅ Use instead: Redis (faster, cheaper for key-value)
Why MongoDB is overkill:
- Paying for query engine, aggregation, transactions you don't need
- Slower than pure key-value stores
- More complex ops (backups, indexes, sharding)
Example: API rate limiting (10M requests/day)
MongoDB: db.rateLimit.findOne({ userId: '123' }) → 5-10ms
Redis: GET user:123:count → 0.5ms
→ Redis 10-20x faster for simple lookups5. Strong consistency + multi-region writes
❌ Don't use: MongoDB for global financial transactions
✅ Use instead:
- Google Spanner (global strong consistency)
- CockroachDB (distributed SQL with SERIALIZABLE isolation)
Why MongoDB doesn't fit:
- Cross-region replica sets/global clusters can give strong consistency with w:"majority" + readConcern majority/linearizable, at the cost of cross-region write latency; each shard still has a single primary region
- Atlas Global Clusters: mỗi shard có primary ở một vùng và client chỉ ghi được vào primary ("Clients can issue write operations only to the primary"), nên ghi từ vùng khác phải đi tới primary đó
Note: MongoDB good for multi-region reads (read preference), not multi-region writes6. Extremely wide documents (100+ fields per document)
❌ Don't use: MongoDB for analytics with 500 columns per event
✅ Use instead: Cassandra (designed for wide rows)
Why MongoDB struggles:
- Large documents (>100KB) = slow queries, high memory usage
- 16MB document size limit
- Indexes on wide documents expensive
Guideline:
- MongoDB documents: < 100 fields, < 100KB ideal
- Cassandra rows: 1000+ columns supported efficiently7. Complex transactions across many documents (>100 docs)
❌ Don't use: MongoDB for batch payment processing (update 10,000 accounts)
✅ Use instead: PostgreSQL (mature transaction support, no doc limit)
Why MongoDB transactions limited:
- 60-second default lifetime (configurable via transactionLifetimeLimitSeconds)
- Ngưỡng số document mỗi giao dịch (ví dụ 100 hay 1,000) chỉ là ví dụ minh hoạ, không phải giới hạn chính thức: trang Production Considerations của MongoDB chỉ nêu thời gian chạy mặc định dưới 1 phút, không nêu số document; đo bằng workload của bạn
- Increased lock contention
MongoDB transactions best for:
- 2-10 documents
- < 5 second duration
- Occasional use (not every write)
PostgreSQL better for:
- Complex multi-table joins with ACID
- Long-running batch jobs
- Heavy transaction workloadDecision framework:
START: Is MongoDB right for me?
Q1: Do I need P99 < 5ms?
YES → Use Redis
NO → Continue
Q2: Do I have >50K writes/sec?
YES → Use Cassandra
NO → Continue
Q3: Do I need serverless auto-scaling?
YES → Use DynamoDB
NO → Continue
Q4: Am I only doing key-value lookups?
YES → Use Redis
NO → Continue
Q5: Do I need multi-region strong consistency?
YES → Use Spanner/CockroachDB
NO → Continue
Q6: Do I have >100 fields per document?
YES → Use Cassandra
NO → Continue
Q7: Do I need complex transactions (ví dụ >10 docs, ngưỡng minh hoạ)?
YES → Use PostgreSQL
NO → ✅ MongoDB is likely a good fit!→ See also: Master Decision Tree, Database Selection Matrix
When NOT to Use DynamoDB ❌
1. Complex ad-hoc queries without predefined access patterns
- ❌ Analytics dashboard with 50 different query filters
- ✅ Use PostgreSQL or MongoDB instead
- Why: DynamoDB requires knowing all access patterns upfront (PK/SK design)
2. Frequent full table scans or reports
- ❌ Monthly reports requiring SCAN of entire table
- ✅ Use data warehouse (Redshift, BigQuery)
- Cost: SCAN của bảng 1 TiB ≈ $17–34 mỗi lần quét đủ, on-demand (≈134–268M RRU × $0.125/triệu, us-east-1, giá 2026-11-20); đắt khi lặp lại
3. Write-heavy with many GSIs (ví dụ ngưỡng minh hoạ: >3 GSI)
- ❌ Event logging with 5 GSIs for different queries
- ✅ Use Elasticsearch or Cassandra
- Why: mỗi GSI nhận thêm một lần ghi cho mỗi item được chiếu vào (bảng + 5 GSI = tới 6 lần ghi cho một lần PutItem)
4. Sub-$100/month budget with predictable traffic
- ❌ Small SaaS app with steady 1K QPS
- ✅ Use self-hosted MongoDB or Redis
- Cost (ví dụ tính, us-east-1, giá 2026-11-20, chỉ phần ghi): 1 000 ghi/giây × 1 KB = 1 000 WCU × $0,00065 × 730 giờ ≈ $475/tháng provisioned; đọc, GSI, storage tính thêm. So với tự quản MongoDB/Redis: đối chiếu giá cụm thật của bạn
5. Complex join operations
- ❌ Order + Customer + Product + Inventory multi-table joins
- ✅ Use PostgreSQL with proper indexing
- Why: DynamoDB single-table design complex, no native joins
→ See also: DynamoDB Single-Table Design
When NOT to Use Redis ❌
1. Primary data store with strict durability requirements
- ❌ User account data (can't afford any data loss)
- ✅ Use MongoDB or PostgreSQL
- Why: Redis is in-memory, AOF/RDB persistence adds latency
2. Datasets larger than available RAM (ví dụ ngưỡng minh hoạ: >256 GB)
- ❌ 1TB product catalog
- ✅ Use MongoDB or DynamoDB
- Cost: RAM đắt hơn SSD theo GB; giá thật đổi theo nhà cung cấp và region, đối chiếu trang giá (tài liệu này không có số có nguồn)
3. Complex queries with secondary indexes
- ❌ Search products by category, price range, rating
- ✅ Use MongoDB or Elasticsearch
- Why: Redis Query Engine (built into Redis 8) has secondary/full-text indexes, but data must fit in RAM and ad-hoc querying is limited compared with a document DB
4. Strong ACID transactions across multiple keys
- ❌ Multi-item inventory updates with rollback
- ✅ Use PostgreSQL or MongoDB
- Why: MULTI/EXEC không rollback: lệnh lỗi sau EXEC không chặn các lệnh còn lại trong hàng đợi (doc: "Redis does not support rollbacks of transactions")
→ See also: Redis Persistence Options
When NOT to Use Cassandra ❌
1. Small datasets (<100GB) with ad-hoc queries
- ❌ 10GB user database with flexible filtering
- ✅ Use MongoDB or PostgreSQL
- Why: Cassandra overhead not worth it for small data
2. Strong consistency requirements (banking)
- ❌ Financial transactions requiring immediate consistency
- ✅ Use PostgreSQL or MongoDB with w=majority
- Why: Cassandra designed for eventual consistency (tunable but complex)
3. Frequent updates/deletes (ví dụ ngưỡng minh hoạ: >30% thao tác)
- ❌ Shopping cart with frequent item updates
- ✅ Use MongoDB or DynamoDB
- Why: delete và TTL hết hạn tạo tombstone, update ghi thêm phiên bản mới; cả hai tăng tải compaction (doc chỉ nêu tombstone cho delete/TTL)
4. Team unfamiliar with data modeling (query-first design)
- ❌ Startup with no Cassandra experience
- ✅ Use MongoDB (more forgiving schema)
- Why: Cassandra requires upfront data modeling, hard to change later
→ See also: Cassandra Data Modeling
When NOT to Use Neo4j ❌
1. Simple lookups without relationship traversals
- ❌ Key-value user profile storage
- ✅ Use Redis or DynamoDB
- Why: Graph database overhead unnecessary for simple lookups
2. Write-heavy workloads (ví dụ ngưỡng minh hoạ: >10K ghi/giây)
- ❌ High-frequency trading event logs
- ✅ Use Cassandra or Kafka
- Why: mỗi database chỉ có một writer được bầu trong cluster và writer phải chờ các primary khác xác nhận, thêm primary làm tăng độ trễ ghi (doc không nêu ngưỡng thông lượng)
3. Large-scale analytics on full dataset
- ❌ Daily batch processing of 10TB graph
- ✅ Use graph analytics platform (Apache Spark + GraphX)
- Why: Neo4j designed for OLTP queries, not batch analytics
4. Time-series data (metrics, logs, events)
- ❌ IoT sensor data with timestamps
- ✅ Use Cassandra or TimescaleDB
- Why: Graph model overhead, Cassandra better for time-series
→ See also: Neo4j Use Cases
Phải nhớ (Anti-patterns):
- Đo từng anti-pattern:
bsonsize(MongoDB),ConsumedCapacity(DynamoDB), thời gianKEYSso vớiSCAN(Redis), lỗiALLOW FILTERING(Cassandra),PROFILE(Neo4j). Đo trước khi kết luận chậm. - Thay
KEYSbằngSCAN,ScanbằngQuery,ALLOW FILTERINGbằng bảng theo truy vấn hoặc SAI, đường dẫn không giới hạn bằng độ sâu cố định. - Số trong ví dụ là minh hoạ hoặc đo trên dữ liệu nhỏ (đổi theo máy); đo lại trên dữ liệu của mình.