Chuyển đến nội dung chính

Bài 9: SQL vs NoSQL - Chọn Database phù hợp

RDBMS và ACID properties. NoSQL categories: Key-Value (Redis, DynamoDB), Document (MongoDB, CouchDB), Wide Column (Cassandra, HBase), Graph (Neo4j). BASE vs ACID. Khi nào chọn SQL, khi nào chọn NoSQL. Polyglot Persistence. NewSQL (CockroachDB, TiDB).

🏗️ Kiến trúc — Bài 9 Bài 9: SQL vs NoSQL - Chọn Database phù hợp

System Architecture: From Zero to Hero

Phần 3: Database Architecture & Data Management

xdev.asia

Giới thiệu

Database là trái tim của mọi hệ thống. Chọn sai database có thể dẫn đến re-architecture toàn bộ hệ thống — tốn kém và đau đớn. Bài này giúp bạn hiểu rõ từng loại database và khi nào nên chọn cái nào.


1. SQL (Relational Database)

1.1 ACID Properties

PropertyÝ nghĩaVí dụ
AtomicityTransaction all-or-nothingChuyển tiền: trừ A + cộng B hoặc không gì cả
ConsistencyData luôn ở trạng thái hợp lệBalance không bao giờ âm
IsolationTransactions không ảnh hưởng nhau2 người cùng mua vé → không conflict
DurabilityCommit xong = data an toànServer crash ≠ mất data

1.2 Khi nào chọn SQL?

✓ Data có cấu trúc rõ ràng (schema cố định)
✓ Relationships phức tạp (foreign keys, joins)
✓ Cần ACID transactions
✓ Data integrity quan trọng
✓ Query patterns đa dạng (ad-hoc queries)

Ví dụ: Banking, ERP, E-commerce orders, CRM

1.3 Phổ biến: PostgreSQL vs MySQL

FeaturePostgreSQLMySQL
ACIDFullFull (InnoDB)
JSON supportExcellent (JSONB)Good
Full-text searchBuilt-inBuilt-in
ReplicationStreaming, LogicalBinlog
ExtensionsTimescaleDB, PostGISLimited
Best forComplex queries, data integrityWeb apps, read-heavy

2. NoSQL Categories

2.1 Key-Value Store

SET user:123 → {"name": "John", "email": "[email protected]"}
GET user:123 → {"name": "John", "email": "[email protected]"}

Cực nhanh: O(1) read/write
Hạn chế: Không có query phức tạp, không có relationships
DatabaseBest for
RedisCaching, sessions, leaderboards, pub/sub
DynamoDBServerless, auto-scaling key-value
MemcachedSimple caching

2.2 Document Store

// MongoDB document
{
  "_id": "order_123",
  "customer": {
    "name": "John",
    "email": "[email protected]"
  },
  "items": [
    {"product": "Laptop", "price": 1000, "qty": 1},
    {"product": "Mouse",  "price": 25,   "qty": 2}
  ],
  "total": 1050,
  "status": "shipped"
}
DatabaseBest for
MongoDBFlexible schema, rapid development
CouchDBOffline-first, sync
ElasticsearchFull-text search, analytics

2.3 Wide Column Store

Row Key: user_123
  Column Family "profile":
    name: "John"
    email: "[email protected]"
  Column Family "activity":
    last_login: "2026-03-30"
    posts_count: 42

Mỗi row có thể có columns khác nhau
→ Linh hoạt cho IoT, time-series, analytics
DatabaseBest for
CassandraHigh write throughput, multi-datacenter
HBaseHadoop ecosystem, analytics
ScyllaDBCassandra-compatible, higher performance

2.4 Graph Database

(John) ─[FRIENDS_WITH]─► (Jane)
(John) ─[WORKS_AT]────► (Google)
(Jane) ─[LIVES_IN]────► (Hanoi)
(John) ─[LIKES]───────► (Post_123)

Query: "Tìm bạn của bạn John sống ở Hà Nội"
→ Cực nhanh với Graph DB, cực chậm với SQL (multiple JOINs)
DatabaseBest for
Neo4jSocial networks, recommendations, fraud detection
Amazon NeptuneAWS managed graph
ArangoDBMulti-model (document + graph)

3. ACID vs BASE

PropertyACID (SQL)BASE (NoSQL)
FocusConsistencyAvailability
TransactionsStrongSoft state
ScaleVertical primarilyHorizontal
ConsistencyImmediateEventual
SchemaFixedFlexible

4. SQL vs NoSQL Decision Framework

                      Cần ACID?
                      ╱       ╲
                   Yes         No
                    │           │
               Complex         Scale
              Relations?    requirements?
              ╱       ╲     ╱        ╲
           Yes        No   High       Low
            │          │    │          │
         SQL          SQL  NoSQL      SQL
      (PostgreSQL)  (MySQL)(Cassandra)(Simple)
                           (MongoDB)

4.1 Decision Matrix

Requirement→ Database
Banking, FinancialPostgreSQL (ACID)
User sessions, cachingRedis (Key-Value)
Content management, CMSMongoDB (Document)
Social graph, recommendationsNeo4j (Graph)
IoT, time-seriesCassandra / TimescaleDB
Full-text searchElasticsearch
E-commerce catalogMongoDB + Elasticsearch
Analytics, data warehouseClickHouse / BigQuery

5. Polyglot Persistence

E-commerce Platform:

┌─────────────────────────────────────────────┐
│              Application Layer               │
├──────────┬──────────┬───────────┬───────────┤
│ Users    │ Products │ Orders    │ Analytics │
│   │      │   │      │   │       │   │       │
│PostgreSQL│ MongoDB  │PostgreSQL │ClickHouse │
│(accounts)│(catalog) │(payments) │(reports)  │
├──────────┴──────────┴───────────┴───────────┤
│              Redis (Caching Layer)            │
├─────────────────────────────────────────────┤
│          Elasticsearch (Search)              │
└─────────────────────────────────────────────┘

Mỗi service chọn database phù hợp nhất cho use case của nó.


6. NewSQL

NewSQL kết hợp ưu điểm của cả hai: ACID + Horizontal Scaling.

DatabaseMô tả
CockroachDBDistributed SQL, PostgreSQL-compatible
TiDBMySQL-compatible, HTAP
Google SpannerGlobal distributed, strong consistency
YugabyteDBPostgreSQL-compatible, distributed
NewSQL = SQL Syntax + ACID Transactions + Horizontal Scaling

Trade-off: Latency cao hơn single-node SQL (distributed overhead)

Tổng kết

Database TypeStrengthsUse Cases
SQLACID, relationships, complex queriesBanking, E-commerce, ERP
Key-ValueSpeed, simplicityCaching, sessions
DocumentFlexible schema, rapid devCMS, catalogs
Wide ColumnWrite throughput, scaleIoT, time-series
GraphRelationship queriesSocial, recommendations
NewSQLBest of both worldsDistributed ACID

Bài tập

  1. Database Selection: Cho hệ thống healthcare management (bệnh viện), chọn database cho: (a) Hồ sơ bệnh nhân, (b) Lịch sử khám bệnh, (c) Hình ảnh y tế, (d) Tìm kiếm triệu chứng, (e) Quan hệ bệnh nhân-bác sĩ.

  2. Polyglot Design: Thiết kế data architecture cho Shopee-like platform. Xác định mỗi service cần database nào và tại sao.

  3. Migration: Hệ thống hiện dùng MongoDB cho tất cả. Orders cần strong consistency. Lập kế hoạch migrate orders sang PostgreSQL mà không downtime.