Hero image for NoSQL Introduction: Types, CAP Theorem & Storage Engines

NoSQL Introduction: Types, CAP Theorem & Storage Engines

nosql mongodb database cap-theorem distributed-systems

Prerequisites: Understanding of relational databases. See DB 02 Software Layer for SQL fundamentals.

NoSQL databases were created to solve problems that traditional SQL databases struggle with: massive scale, flexible schemas, and distributed computing.


Part A: The Four Types of NoSQL

1. Document Database

Structure: JSON-like documents (nested, flexible)

{
  "_id": "user123",
  "name": "Alice",
  "orders": [
    { "item": "Laptop", "price": 1200 },
    { "item": "Mouse", "price": 25 }
  ]
}
ProductUse Case
MongoDBContent management, e-commerce catalogs
CouchbaseMobile apps with offline sync

Why use it: When your data has variable structure (products with different attributes).


2. Key-Value Store

Structure: Simple dictionary — key → value

session:abc123 → { userId: 1, expires: "2024-03-15" }
cache:product:99 → { name: "Laptop", price: 1200 }
ProductUse Case
RedisCaching, session storage, real-time leaderboards
DynamoDBServerless apps, high-throughput workloads

Why use it: Blazing fast reads/writes for simple lookups.


3. Column-Family Store

Structure: Data stored by columns, not rows

Column Store (NoSQL)

Column: All IDs

Column: All Names

Column: All Ages

Row Store (SQL)

Row 1: ID, Name, Age, City

Row 2: ID, Name, Age, City

ProductUse Case
CassandraTime-series data, IoT sensor logs, high-velocity writes
HBaseHadoop ecosystem, log data ingestion

Why use it: Excellent write throughput and handling of sparse data. (Note: For pure analytical aggregations, consider Column-Oriented DBs like ClickHouse.)


4. Graph Database

Structure: Nodes (entities) + Edges (relationships)

FRIENDS_WITH

WORKS_AT

LIKES

LIKES

Alice

Bob

Google

Coffee

ProductUse Case
Neo4jSocial networks, fraud detection
Amazon NeptuneKnowledge graphs, recommendation engines

Why use it: Finding relationships is O(1) via index-free adjacency — each node directly points to its neighbors without index lookups, unlike SQL JOINs that must scan indexes.


5. Comparison Summary

TypeData ModelBest ForExample Query
DocumentJSON objectsFlexible schemas”Get user with all their orders”
Key-ValueKey → ValueCaching”Get session by ID”
ColumnColumn familiesAnalytics”Sum of all sales this month”
GraphNodes + EdgesRelationships”Friends who also bought X”

Part B: CAP Theorem

6. The Impossible Triangle

In a distributed system, you can only guarantee two of three properties:

💡 Modern Understanding of CAP

In reality, P (Partition Tolerance) is non-negotiable — networks WILL fail. So when a partition occurs, you must choose between C (Consistency) and A (Availability). “Pick 2” is a simplification; the real choice is C vs A during network failures.

CAP Theorem

Consistency

All nodes see same data

Availability

Every request gets response

Partition Tolerance

System works despite network splits

CombinationSacrificeExample
CAPartition ToleranceTraditional SQL (single server)
CPAvailabilityMongoDB (with strict write concern)
APConsistencyCassandra, DynamoDB

7. Real-World Example

Scenario: Network splits your 3 MongoDB servers into two groups.

Server 3Server 2Server 1 (Primary)ClientServer 3Server 2Server 1 (Primary)ClientNetwork Partition!Available = NOConsistent = NO (other servers outdated)alt[CP Mode (Consistency Priority)][AP Mode (Availability Priority)]Cannot reachCannot reachWrite orderERROR - Cannot confirm writeOK - Written locally

Part C: BASE vs ACID

8. ACID (SQL Databases)

PropertyMeaningExample
AtomicityAll or nothingBank transfer: both debit and credit succeed, or neither
ConsistencyValid state → Valid stateTotal money in system stays same
IsolationTransactions don’t interfereTwo users can’t buy the last item
DurabilityOnce committed, permanentSurvives power failure

9. BASE (NoSQL Databases)

PropertyMeaning
Basically AvailableSystem always responds (maybe stale data)
Soft stateData may change over time (syncing)
Eventual consistencyGiven time, all nodes will agree

10. Comparison

BASE (NoSQL)

ACID (SQL)

Trade-off

Strong Consistency

Immediate

Slower writes

Eventual Consistency

Faster at scale

May read stale data

ACIDBASE
PriorityCorrectnessAvailability
ScaleHarder to scale outBuilt for scale out
Use CaseBanking, inventorySocial feeds, analytics

Part D: MongoDB Storage Engine (WiredTiger)

11. What is WiredTiger?

WiredTiger is MongoDB’s default storage engine since version 3.2. Think of it as the “V8 engine” that powers MongoDB.

MongoDB Architecture

Application

MongoDB Driver

Query Engine

WiredTiger Engine

Disk Storage

12. Document-Level Locking

The Problem: Early MongoDB used database-level locking — if one user writes, the entire database is locked.

WiredTiger’s Solution: Document-level locking — only the specific document being modified is locked.

Document-Level Lock (WiredTiger)

Doc A LOCKED

User 1 writes Doc A

User 2 writes Doc B

Doc B FREE

Database-Level Lock (Old)

WAIT

Entire Database LOCKED

User 1 writes Doc A

User 2 wants Doc B

💡 MVCC: Why Reads Don’t Block Writes

WiredTiger uses MVCC (Multi-Version Concurrency Control): readers see the old version while writers create a new version. This is why reads and writes don’t block each other — true non-blocking concurrency.

13. Compression

WiredTiger compresses data on disk:

CompressionCPU UsageSpace Savings
snappy (default)Low~50%
zlibMedium~70%
zstdLow-Medium~60%
// Check current engine
db.serverStatus().storageEngine
// { "name": "wiredTiger", ... }

14. Journaling & Checkpoints

FeaturePurpose
JournalWrite-ahead log (WAL) for crash recovery
CheckpointPeriodic flush to disk (every 60s or 2GB)

This is similar to SQL Server’s transaction log!


Summary

NoSQL Type Selection Guide

NeedChoose
Flexible product catalogDocument (MongoDB)
Super-fast cachingKey-Value (Redis)
Time-series / IoT dataColumn (Cassandra)
Social network relationshipsGraph (Neo4j)

CAP/BASE Quick Reference

ConceptMeaning
CAPPick 2: Consistency, Availability, Partition Tolerance
CPStrong consistency, sacrifice availability during partition
APAlways available, sacrifice consistency during partition
BASEEventual consistency model for distributed systems

WiredTiger Benefits

  • ✅ Document-level locking (high concurrency)
  • ✅ Compression (50-70% space savings)
  • ✅ Journaling (crash recovery)

💡 Practice Questions

Conceptual

  1. Name the 4 types of NoSQL databases and give one use case for each.

  2. Explain the CAP theorem. Why can’t a distributed system have all three properties?

  3. What is the difference between ACID and BASE consistency models?

  4. Describe two features of MongoDB’s WiredTiger storage engine.

Scenario

  1. Decision: Your company needs to build a social network. Which NoSQL database type would you recommend for storing friend relationships, and why?

  2. Trade-off: An e-commerce site needs both fast reads and strong consistency for inventory counts. According to CAP theorem, what challenges might you face with a distributed database?