FullStack AI Hub
Studio
System Design · 03. Data & Storage
10 min
10 steps
Beginner

SQL vs NoSQL

Pick relational schemas, document stores, wide-column tables, or graph engines by real access pattern.

System Design03. Data & StorageLesson 1 of 11
10 minBeginner10 steps

SQL vs NoSQL

Pick relational schemas, document stores, wide-column tables, or graph engines by real access pattern.

CONSISTENCY
Strict ACID
CHECKOUT P95
24 ms
DATA ANOMALIES
0
ORDER RPS
1,800/s
POST /checkoutACID TX8k buyersCheckout API34%BEGIN..COMMITPostgreSQL38%3NF Tables
read query
write / mutation
fast single-hop fetch
multi-table JOIN / scan
lock / hotspot timeout
In This LessonStep 1 of 10
What You Will Master
  • ✓Recognize when normalized SQL tables, foreign keys, and ACID joins beat every alternative
  • ✓Model flexible, aggregate-oriented records cleanly in document stores without multi-table joins
  • ✓Design partition-key-first wide-column tables for massive write-heavy time or feed streams
  • ✓Combine relational, document, key-value, and search stores cleanly in a polyglot production stack

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Relational SQL (PostgreSQL / MySQL)Financial ledgers, orders, inventory, and relational data needing ACID transactions and ad-hoc JOINsSchema migrations need care and horizontal write sharding adds operational complexity
Document Store (MongoDB / DynamoDB JSON)Product catalogs, CMS profiles, and self-contained aggregates with varying attributes per itemCross-document joins are slow and duplicated nested fields require fan-out updates
Wide-Column (Cassandra / ScyllaDB)High-throughput append-heavy logs, chat history, and IoT events queried strictly by partition keyNo arbitrary JOINs; you must design tables backward from known query patterns
Polyglot PersistenceProduction platforms: SQL for billing/orders, Document for catalog, Redis for sessions/hot readsAdds CDC/event synchronization and more database engines for teams to operate

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for SQL vs NoSQL.

STEP 01 · SETUPJump to step →

Start with SQL: normalized tables & rock-solid ACID

For an e-commerce checkout system, **PostgreSQL** enforces strict schemas, foreign keys (`orders.user_id → users.id`), and multi-row **ACID transactions**.

When a shopper checks out, decrementing inventory and inserting an order succeed or roll back together atomically—zero orphaned orders and zero oversold items.

idea:Default to relational SQL whenever your data has clear relationships, evolving query needs, or strict financial consistency.

Normalization (3NF)Foreign KeysACID Guarantees
STEP 02 · PROBLEMJump to step →

Where strict SQL hurts: sparse catalogs & 7-way JOINs

Now you launch a marketplace selling **laptops** (CPU, RAM, screen size), **sneakers** (size, sole material), and **books** (ISBN, author, page count). Every product type has completely different attributes.

Forcing heterogeneous specs into rigid SQL tables creates sparse NULL columns or Entity-Attribute-Value (EAV) tables requiring **7-way JOINs** just to render one product page—spiking p95 latency to 340 ms.

watch:Entity-Attribute-Value (EAV) anti-patterns in SQL turn simple product reads into expensive multi-table JOINs and painful schema migrations.

Schema RigidityEAV Anti-PatternMulti-Table JOINs
STEP 03 · SOLUTIONJump to step →

Document Stores: fetch the entire aggregate in 1 read

Move the product catalog to a **Document Store** (MongoDB or PostgreSQL `JSONB`). Each product—along with its laptop CPU specs or sneaker sizes and nested variants—lives in **one contiguous JSON/BSON document**.

Rendering a product page drops from 7 JOINs to **1 primary-key lookup** in 9 ms, and onboarding a new product category requires zero database migrations.

idea:Document stores excel when data is read and written together as a self-contained tree (aggregate) with flexible per-item fields.

Document DenormalizationAggregate-Oriented ModelSchema-on-Read
STEP 04 · TRADE-OFFJump to step →

The document trade-off: duplicated writes & update fan-out

Denormalization is not free. Suppose you embedded `seller_name` and `seller_badge` inside **50,000 product documents** to avoid a JOIN.

When that merchant renames their store, SQL updates **1 row** in `sellers`. Your denormalized document store must fan out **50,000 background document rewrites**—and readers see stale names in between.

watch:Embed data that changes rarely and is read together (shipping address on an order). Reference data that changes frequently across thousands of records (seller profile).

Embed vs ReferenceWrite AmplificationStale Denormalized Copies
STEP 05 · SOLUTIONJump to step →

Wide-Column Stores: massive write scale by partition key

Next, your app adds **clickstream & message history** generating **80,000 writes/sec**. A single primary SQL server hits disk and replication ceilings immediately.

A **Wide-Column Store** (Cassandra / ScyllaDB / DynamoDB) shards rows horizontally by **Partition Key** (`user_id` or `channel_id`) and sorts rows on disk by **Clustering Key** (`timestamp DESC`), turning 80k writes/sec into fast leaderless appends across 3 peer nodes.

idea:Wide-column modeling flips SQL on its head: instead of modeling entities first, list your exact queries first and build one table per query pattern.

Partition KeyClustering KeyQuery-First Modeling
STEP 06 · PROBLEMJump to step →

The NoSQL query trap: querying without the partition key

A product manager asks: *"Can we also filter all messages globally by `keyword` or `sender_email`?"* Neither column is your partition key.

Without the partition key, the coordinator must **scatter-gather scan every single partition on every node** (`ALLOW FILTERING`), turning a 7 ms read into a cluster-melting 2,400 ms storm.

watch:Never run `ALLOW FILTERING` or full-table scans on a production wide-column cluster—if you need ad-hoc filters, feed a secondary index or Search Engine via CDC.

Scatter-Gather ScanPartition Key DisciplineQuery Rigidity
STEP 07 · TECHNIQUEJump to step →

Key-Value & Graph: sub-ms lookups vs deep traversals

Two specialized NoSQL models solve opposite extremes: **Key-Value Stores** (Redis, DynamoDB KV) serve `GET key` in **<1 ms** for sessions, carts, and feature flags with O(1) simplicity.

**Graph Databases** (Neo4j) store pointer-linked edges directly on disk so *"friends-of-friends-of-friends who bought this item"* traverses 4 hops in **12 ms** instead of recursive SQL JOIN explosions.

idea:Use Key-Value for O(1) ephemeral or hot lookups; reach for Graph only when multi-hop relationship traversal (3+ hops) is your core query.

Key-Value O(1)Index-Free AdjacencyMulti-Hop Traversals
STEP 08 · TECHNIQUEJump to step →

Don’t split too early: PostgreSQL JSONB + modern SQL

Before spinning up three separate databases, remember that modern **PostgreSQL** blurs the line: you can store rigid order columns alongside a GIN-indexed **`JSONB` specs column** in the exact same ACID table.

At early and mid scale (up to ~10k rps and a few terabytes), keeping one relational engine with `JSONB` eliminates cross-database sync bugs and halves operational overhead.

idea:Rule of thumb: start with PostgreSQL (relational + JSONB) and add a specialized NoSQL engine only when a measured bottleneck proves you need it.

JSONB HybridOperational SimplicityGIN Indexing
STEP 09 · SOLUTIONJump to step →

At scale: Polyglot Persistence synced via CDC

At high scale, no single engine wins every workload. **Polyglot Persistence** assigns each bounded context its ideal store: **PostgreSQL** for financial orders, **Document DB** for flexible catalogs, **Wide-Column** for 80k/s activity streams, and **Redis** for sub-ms sessions.

Connect them cleanly with **CDC / Event Logs** so each store stays the clear source of truth for its own domain.

idea:Polyglot persistence works cleanly when each database owns ONE domain boundary—never split one table’s truth across two stores with manual dual-writes.

Polyglot PersistenceBounded ContextsSource of Truth
STEP 10 · RECAPJump to step →

Recap: choose databases by access pattern, not hype

Never ask *"Is SQL or NoSQL better?"*—ask **how your data is queried, mutated, and scaled**.

Start with **SQL** for relational integrity and unpredictable queries; reach for **Documents** for flexible self-contained aggregates, **Wide-Column** for massive keyed write streams, and **KV/Graph** for specialized sub-ms or multi-hop needs.

idea:Interview winning heuristic: "Start with PostgreSQL for ACID + relational clarity; introduce Redis, Document, or Wide-Column stores only where specific access patterns demand them."

Access-Pattern DesignSQL vs NoSQLPolyglot Persistence

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.