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

Lesson 9: SQL vs NoSQL - Choose the right Database

RDBMS and ACID properties. NoSQL categories: Key-Value (Redis, DynamoDB), Document (MongoDB, CouchDB), Wide Column (Cassandra, HBase), Graph (Neo4j). BASE vs ACID. When to choose SQL, when to choose NoSQL. Polyglot Persistence. NewSQL (CockroachDB, TiDB).

🏗️ Architecture — Lesson 9 Lesson 9: SQL vs NoSQL - Choose the right Database suitable

System Architecture: From Zero to Hero

Part 3: Database Architecture & Data Management

xdev.asia

Introduction

Database is the heart of every system. Choosing the wrong database can lead to a complete system re-architecture — expensive and painful. This article helps you understand each type of database and when to choose which one.


1. SQL (Relational Database)

1.1 ACID Properties

PropertyMeaningExample
AtomicityTransaction all-or-nothingMoney transfer: minus A + plus B or nothing
ConsistencyData is always in a valid stateBalance is never negative
IsolationTransactions do not affect each other2 people buy tickets together → no conflict
DurabilityCommit completed = data safeServer crash ≠ data loss

1.2 When to choose 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 Popular: PostgreSQL vs MySQL

FeaturesPostgreSQLMySQL
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 mainlyHorizontal
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

Requirements→ 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)              │
└─────────────────────────────────────────────┘

Each service chooses the most suitable database for its use case.


6. NewSQL

NewSQL combines the advantages of both: ACID + Horizontal Scaling.

DatabaseDescription
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)

Summary

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

Exercises

  1. Database Selection: For the healthcare management system (hospital), select the database for: (a) Patient records, (b) Medical examination history, (c) Medical images, (d) Symptom search, (e) Patient-doctor relationship.

  2. Polyglot Design: Design data architecture for Shopee-like platform. Determine which database each service needs and why.

  3. Migration: The system currently uses MongoDB for all. Orders need strong consistency. Plan to migrate orders to PostgreSQL without downtime.