Appearance
PART 8: MIGRATION & INTEGRATION
SQL sang NoSQL, MongoDB sang DocumentDB và polyglot persistence. Công cụ chạy được đã kiểm trên Docker (mongo:8, redis:8, amazon/dynamodb-local, cassandra:5, postgres:18); dịch vụ managed (DocumentDB, DMS) chưa chạy, đã đối chiếu tài liệu AWS.
SQL to NoSQL Migration
Khi nào nên chuyển:
text
Migrate when:
✅ Schema changes frequently (agile development)
✅ Need horizontal scaling (SQL vertical limits)
✅ Hierarchical data (documents > tables)
✅ Write throughput vượt giới hạn một máy (đo bằng workload thật, không dùng ngưỡng cố định)
✅ Flexible schema (multi-tenant, dynamic fields)
DON'T migrate when:
❌ Complex JOINs across many tables
❌ Ad-hoc queries (unknown access patterns)
❌ ACID transactions across entities
❌ Team lacks NoSQL expertiseChuyển mô hình dữ liệu:
sql
-- PostgreSQL 18
-- SQL (normalized):
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(255),
name VARCHAR(255)
);
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT REFERENCES users(id),
total DECIMAL(10,2),
created_at TIMESTAMP
);
CREATE TABLE order_items (
id INT PRIMARY KEY,
order_id INT REFERENCES orders(id),
product_id INT,
quantity INT,
price DECIMAL(10,2)
);javascript
// mongosh, MongoDB 8: tài liệu phi chuẩn hoá (denormalized)
db.users.insertOne({
userId: "USR-123",
email: "user@example.com",
name: "John Doe",
orders: [
{
orderId: "ORD-456",
total: 149.99,
createdAt: ISODate("2025-01-09"),
items: [
{ productId: "PROD-789", quantity: 2, price: 49.99 },
{ productId: "PROD-101", quantity: 1, price: 50.01 }
]
}
]
})
// Đánh đổi: trùng dữ liệu đổi lấy ít lượt đọc
// SQL: 3 bảng, cần JOIN; MongoDB: 1 truy vấn theo userId (đo độ trễ bằng workload thật)
// Cảnh báo: mảng orders nhúng tăng không giới hạn, tài liệu tối đa 16 MiB;
// chỉ nhúng phần có giới hạn, đơn hàng lịch sử tách thành collection orders riêng (như Case Study 1)Chiến lược ghi kép (dual-write, chuyển không ngừng dịch vụ):
javascript
// Node.js, minh hoạ, không chạy độc lập (sqlDB, mongodb, logger là client giả định; thao tác Mongo đã chạy thử bằng mongosh trên mongo:8)
// Phase 1: Dual-write (ghi cả SQL + NoSQL; phải phủ cả UPDATE và DELETE, không chỉ INSERT)
async function createOrder(orderData) {
// Write to SQL (existing system)
const sqlOrder = await sqlDB.query(
'INSERT INTO orders (user_id, total) VALUES (?, ?)',
[orderData.userId, orderData.total]
)
// Write to MongoDB (new system)
try {
await mongodb.collection('orders').insertOne({
orderId: `ORD-${sqlOrder.insertId}`,
userId: orderData.userId,
total: orderData.total,
createdAt: new Date()
})
} catch (err) {
// Chỉ ghi log, không làm hỏng yêu cầu (MongoDB chỉ là bản bóng); dòng lỗi này là chỗ hai bên lệch nhau,
// đẩy vào hàng đợi retry hoặc chạy đối soát định kỳ
logger.error('MongoDB write failed:', err)
}
return sqlOrder
}
// Phase 2: Backfill dữ liệu cũ, chạy SAU khi dual-write đã bật; phân trang theo id, idempotent
async function backfillOrders() {
let lastId = 0
for (;;) {
const orders = await sqlDB.query(
'SELECT * FROM orders WHERE id > ? ORDER BY id LIMIT 1000', [lastId]
)
if (orders.length === 0) break
for (const order of orders) {
await mongodb.collection('orders').updateOne(
{ orderId: `ORD-${order.id}` },
{ $setOnInsert: {
orderId: `ORD-${order.id}`,
userId: order.user_id,
total: order.total,
createdAt: order.created_at
} },
{ upsert: true } // thiếu upsert thì $setOnInsert không làm gì; $setOnInsert không đè bản mới do dual-write ghi
)
}
lastId = orders[orders.length - 1].id
}
}
// Phase 3: Read from MongoDB (with SQL fallback)
async function getOrder(orderId) {
// Try MongoDB first
let order = await mongodb.collection('orders').findOne({ orderId })
if (!order) {
// Fallback to SQL
order = await sqlDB.query('SELECT * FROM orders WHERE id = ?', [orderId])
}
return order
}
// Phase 4: Cut over (read only from MongoDB)
// Phase 5: Stop writing to SQL
// Phase 6: Decommission SQLMongoDB to DocumentDB Migration
Tương thích tính năng (khác biệt quan trọng). Bảng đầy đủ nằm ở Feature Compatibility Matrix; trích các dòng hay làm gãy migration (nguồn: AWS "Supported MongoDB APIs", đọc 2026-11-25):
| Tính năng | MongoDB 8.0 | DocumentDB (instance-based) |
|---|---|---|
| Aggregation | Đầy đủ | Tập con: $lookup có (subquery tương quan từ 8.0.2); $graphLookup và $merge chỉ từ 8.0 (5.0: No); $unionWith: trang Supported APIs ghi No, nhưng release notes 8.0.3 (2026-11-11) ghi đã thêm stage này; kiểm bản engine thật |
| Transaction nhiều tài liệu | ACID | Từ 4.0; Elastic Clusters: No |
| Change streams | Có | Có (3.6 đến 8.0); Elastic: No |
| Retryable writes | Có | Từ 8.0.2; bản cũ hơn đặt retryWrites=false |
| Tìm kiếm | Atlas Search (chỉ trên Atlas) | Không có Atlas Search; $search cho text index từ 5.0, vector index từ 5.0, stage $vectorSearch từ 8.0 |
| Triggers | Atlas Triggers (dịch vụ của Atlas) | Trang tương thích không nêu trigger; phản ứng theo sự kiện bằng change streams |
| Sharding | Tự quản (mongos) | Elastic Clusters (sharded); instance-based: 1 primary + tối đa 15 replica |
| Mã hoá khi lưu | Có | Có (KMS) |
Migration tools:
Công cụ 1: mongodump/mongorestore (tập nhỏ, chấp nhận downtime). URI đích KHÔNG kèm tên DB khi có thư mục dump: mongorestore --uri=mongodb://host:27017/mydb /backup khôi phục 0 tài liệu ("don't know what to do with subdirectory", đã đo trên mongo:8); dùng --nsInclude.
bash
# minh hoạ, không chạy độc lập: cần MongoDB nguồn, cluster DocumentDB và global-bundle.pem (mongodump/mongorestore đã chạy thật giữa hai mongod 8; dùng Database Tools tới 100.11.0 cho DocumentDB)
mongodump --uri="mongodb://source:27017/mydb" --out=/backup
mongorestore --uri="mongodb://user:pass@docdb-cluster.cluster-xxx.us-east-1.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=global-bundle.pem&retryWrites=false" --nsInclude='mydb.*' /backupCông cụ 2: AWS DMS (tập lớn, downtime tối thiểu; dịch vụ managed, chưa chạy, đã đối chiếu CLI reference).
bash
# minh hoạ, không chạy độc lập: cần tài khoản AWS, VPC, hai endpoint; $SOURCE_ARN, $TARGET_ARN, $INSTANCE_ARN, $TASK_ARN là ARN do lệnh create-* trả về (create-replication-task trả $TASK_ARN)
# 1. Create replication instance
aws dms create-replication-instance --replication-instance-identifier mongo-to-docdb --replication-instance-class dms.r5.large
# 2. Create source endpoint (MongoDB)
aws dms create-endpoint --endpoint-identifier mongodb-source --endpoint-type source --engine-name mongodb --server-name mongodb.example.com --port 27017 --username dms_user --password "$MONGO_PASSWORD" --database-name mydb
# 3. Create target endpoint (DocumentDB)
aws dms create-endpoint --endpoint-identifier documentdb-target --endpoint-type target --engine-name docdb --server-name docdb-cluster.cluster-xxx.us-east-1.docdb.amazonaws.com --port 27017 --username dms_user --password "$DOCDB_PASSWORD" --database-name mydb --ssl-mode require
# 4. Create replication task (bắt buộc: --replication-instance-arn và --table-mappings)
aws dms create-replication-task --replication-task-identifier migrate-mydb --source-endpoint-arn "$SOURCE_ARN" --target-endpoint-arn "$TARGET_ARN" --replication-instance-arn "$INSTANCE_ARN" --migration-type full-load-and-cdc --table-mappings file://table-mappings.json
# 5. Start replication
aws dms start-replication-task --replication-task-arn "$TASK_ARN" --start-replication-task-type start-replicationPerformance differences:
javascript
// mongosh, MongoDB 8: tạo dữ liệu mẫu rồi so $lookup với phi chuẩn hoá (DocumentDB: chưa chạy, dịch vụ managed)
db.users.insertOne({ userId: "USR-123", name: "John Doe", email: "john@example.com" })
db.orders.insertMany([
{ orderId: "ORD-1", userId: "USR-123", total: 149.99 },
{ orderId: "ORD-2", userId: "USR-123", total: 20 }
])
// MongoDB: $lookup supported
db.orders.aggregate([
{ $match: { userId: "USR-123" } },
{ $lookup: {
from: "users",
localField: "userId",
foreignField: "userId",
as: "user"
}}
])
// DocumentDB: $lookup supported (so khớp bằng nhau; subquery tương quan từ 8.0.2); chỉ phi chuẩn hoá khi đo thấy chậm
// Phi chuẩn hoá: chép dữ liệu user vào orders (phải cập nhật lại khi user đổi tên hoặc email)
db.orders.updateMany(
{ userId: "USR-123" },
{ $set: {
userName: "John Doe", // Denormalized from users collection
userEmail: "john@example.com"
}}
)
// Query (no $lookup needed):
db.orders.find({ userId: "USR-123" })
// Returns orders with user data embeddedPolyglot Persistence Patterns
Pattern 1: CQRS (Command Query Responsibility Segregation)
text
Write Path (Commands):
User → API → MongoDB (write-optimized)
↓
Event Stream (Kafka)
↓
Elasticsearch (read-optimized)
Read Path (Queries):
User → API → Elasticsearch (search)
→ Redis (cache)
→ MongoDB (fallback)
Example:
- Write product to MongoDB (source of truth)
- Publish event to Kafka: { type: 'ProductCreated', productId, name, price }
- Consumer updates Elasticsearch (full-text search)
- Consumer updates Redis (cache)javascript
// Node.js, minh hoạ, không chạy độc lập (mongodb, kafka, elasticsearch là client giả định)
// Rủi ro: ghi Mongo xong, sập trước khi publish thì sự kiện mất; dùng outbox (ghi sự kiện cùng giao dịch)
// hoặc đọc change stream của MongoDB thay vì publish tay
// Write: Save to MongoDB, publish event
async function createProduct(productData) {
const product = await mongodb.collection('products').insertOne(productData)
await kafka.publish('product-events', {
type: 'ProductCreated',
productId: product.insertedId,
data: productData
})
return product
}
// Event consumer: Update Elasticsearch
kafka.subscribe('product-events', async (event) => {
if (event.type === 'ProductCreated') {
await elasticsearch.index({
index: 'products',
id: event.productId,
body: event.data
})
}
})
// Read: Query Elasticsearch (fast search)
async function searchProducts(query) {
return await elasticsearch.search({
index: 'products',
body: {
query: { match: { name: query } }
}
})
}Pattern 2: Multi-database per use case
text
System Architecture:
┌──────────────┐
│ API Gateway│
└──────┬───────┘
│
┌───┴───┬────────┬────────┬────────┐
↓ ↓ ↓ ↓ ↓
MongoDB DynamoDB Redis Cassandra Neo4j
(core) (sessions)(cache) (metrics) (social)
MongoDB: User profiles, products, orders (flexible schema)
DynamoDB: User sessions (low-latency key-value, auto-scale)
Redis: Cache layer (response cache, rate limiting)
Cassandra: Time-series metrics (high write throughput)
Neo4j: Social graph (friends, recommendations)javascript
// Node.js (AWS SDK v3), minh hoạ, không chạy độc lập: redis (ioredis), mongodb, cassandra, neo4j là client giả định; dynamodb là DynamoDBDocumentClient
import { GetCommand } from '@aws-sdk/lib-dynamodb'
// Example: E-commerce system
class EcommerceService {
async getProduct(productId) {
// 1. Check Redis cache
let product = await redis.get(`product:${productId}`)
if (product) return JSON.parse(product)
// 2. Query MongoDB (source of truth)
product = await mongodb.collection('products').findOne({ productId })
// 3. Cache in Redis (TTL 1 hour)
await redis.setex(`product:${productId}`, 3600, JSON.stringify(product))
return product
}
async getUserSession(sessionId) {
// DynamoDB: Fast session lookup
return await dynamodb.send(new GetCommand({
TableName: 'Sessions',
Key: { sessionId }
}))
}
async logMetric(metricData) {
// Cassandra: High-throughput time-series writes
await cassandra.execute(
'INSERT INTO metrics (device_id, timestamp, value) VALUES (?, ?, ?)',
[metricData.deviceId, Date.now(), metricData.value]
)
}
async getRecommendations(userId) {
// Neo4j: Graph traversal for recommendations
const result = await neo4j.run(`
MATCH (u:User {id: $userId})-[:PURCHASED]->(p:Product)<-[:PURCHASED]-(other:User)
MATCH (other)-[:PURCHASED]->(rec:Product)
WHERE NOT (u)-[:PURCHASED]->(rec)
RETURN rec.id, rec.name, count(*) as score
ORDER BY score DESC
LIMIT 10
`, { userId })
return result.records.map(r => ({ id: r.get('rec.id'), name: r.get('rec.name'), score: r.get('score') }))
}
}Phải nhớ (PART 8):
mongorestore --uri=.../mydb /backupkhôi phục 0 tài liệu; dùng--nsInclude='mydb.*'(đo trên mongo:8).- DocumentDB:
$graphLookupvà$mergechỉ từ 8.0, retryable writes từ 8.0.2; transaction và change streams không có trên Elastic Clusters. - Dual-write: bật ghi kép (cả UPDATE/DELETE) trước, backfill idempotent (
$setOnInsertkèmupsert: true) sau, rồi mới chuyển đọc.