IIT Madras Zanzibar · Teaching

Module 10: Modern & AI Data Systems · Lecture 42 · Week 15

NoSQL Databases

Document, key-value, wide-column, and graph stores: when and why to go beyond relational

Learning Objectives

Document database model
Figure 42.1: Document databases store self-describing JSON/BSON documents; embedded sub-documents eliminate the need for joins in many read patterns

1. Why NoSQL?

Relational databases excel when data is strongly structured, relationships are complex, and ACID guarantees are required. NoSQL systems emerged to address workloads where these assumptions break down:

NoSQL ≠ No SQL, No Transactions, No Relations

The term "NoSQL" is misleading. Many NoSQL systems now support SQL-like query languages (e.g., CQL in Cassandra, N1QL in Couchbase). Several support multi-document transactions (MongoDB since 4.0, DynamoDB with transactions). "NoSQL" is best read as "Not Only SQL": these are complementary tools, not replacements.

2. The Four NoSQL Data Models

Key-Value Stores

The simplest model: store and retrieve opaque values by a unique key. O(1) get/put/delete. Examples: Redis, DynamoDB, Riak. Best for: caching, session storage, feature flags, leaderboards.

Document Stores

Extend key-value by storing structured, self-describing documents (JSON/BSON). Rich query languages, secondary indexes, aggregation pipelines. Examples: MongoDB, Couchbase, Firestore. Best for: catalogs, user profiles, CMS, event logs.

Wide-Column Stores

Rows have a primary key; each row may have a different set of columns. Optimized for write-heavy analytical workloads. Examples: Apache Cassandra, HBase, Google Bigtable. Best for: time-series, IoT, recommendations.

Graph Databases

Nodes and edges with properties; traversal queries are native (no expensive joins). Examples: Neo4j, Amazon Neptune, ArangoDB. Best for: social networks, fraud detection, knowledge graphs, recommendation engines.

3. Key-Value Stores in Detail

Key-value store diagram
Figure 42.2: A key-value store maps arbitrary keys to opaque byte values; the store has no knowledge of the value's internal structure

3.1 Redis

Redis is an in-memory key-value store that supports rich value types: strings, lists, sets, sorted sets, hashes, bitmaps, and streams. Because it operates in RAM, reads and writes complete in microseconds. Data is optionally persisted via RDB snapshots or AOF (append-only file) logging.

Redis data types: SET user:1001:name "Alice" → String LPUSH user:1001:cart "item_42" → List ZADD leaderboard 9820 "alice" → Sorted Set (score=9820) HSET user:1001 name "Alice" age 25 → Hash EXPIRE user:1001:session 3600 → TTL = 1 hour

3.2 DynamoDB

AWS DynamoDB is a fully managed key-value and document store. Each table has a primary key (partition key, optionally with a sort key). Horizontal sharding is automatic. Provides single-digit millisecond latency at any scale. Pricing is per read/write unit; provisioned or on-demand modes.

4. Document Databases in Detail

4.1 MongoDB

MongoDB stores documents as BSON (Binary JSON). A document can embed sub-documents and arrays, allowing complex structures to be retrieved in a single operation (no joins required for common access patterns).

MongoDB document: student: { "_id": ObjectId("64f3a1b2c9e4d"), "name": "Alice Kiprotich", "student_id": "IIT2024001", "courses": [ { "code": "Z2004", "grade": "A" }, { "code": "Z2005", "grade": "B+" } ], "contact": { "email": "alice@iitmz.ac.in", "phone": "+255-..." } } Query: db.students.find({ "courses.code": "Z2004", "courses.grade": "A" })

4.2 Embedding vs. Referencing

Embed (sub-document)Reference (foreign key)
Use whenData is accessed together; 1:few relationship; child rarely changes independentlyMany-to-many; data is large; child updated frequently; shared across documents
Read cost1 query, 1 document fetch2 queries (lookup reference, then fetch)
Write costUpdate the whole documentUpdate child independently
DuplicationData may be duplicated if sharedNo duplication; authoritative source

5. Wide-Column Stores: Apache Cassandra

Cassandra uses a partition key to hash data across nodes and a clustering key to sort rows within a partition. This design keeps writes rapid (log-structured merge-tree storage), but schema design must be driven by query patterns.

CQL: Cassandra Query Language: CREATE TABLE temperature_readings ( sensor_id UUID, reading_time TIMESTAMP, celsius FLOAT, PRIMARY KEY (sensor_id, reading_time) -- sensor_id is partition key ) WITH CLUSTERING ORDER BY (reading_time DESC); INSERT INTO temperature_readings (sensor_id, reading_time, celsius) VALUES (uuid(), toTimestamp(now()), 36.7); -- Efficient: query by partition key SELECT * FROM temperature_readings WHERE sensor_id = ? ORDER BY reading_time DESC LIMIT 100;

6. CAP Theorem

CAP Theorem (Brewer 2000, proved 2002)

In a distributed system, you can guarantee at most two of three properties simultaneously:
Consistency: every read receives the most recent write (or an error)
Availability: every request receives a (non-error) response, even if it may be stale
Partition tolerance: the system continues operating despite network partitions

Because network partitions cannot be avoided in practice, the real trade-off is between C and A.

System TypeTrade-offExamplesBest For
CP (Consistent + Partition-tolerant)May reject requests during partitions to stay consistentHBase, MongoDB (with majority write concern), ZookeeperFinancial data, inventory, config management
AP (Available + Partition-tolerant)Always responds, but response may be staleCassandra, CouchDB, DynamoDB (eventual consistency)Social feeds, shopping carts, DNS, CDN

7. BASE vs. ACID

ACID (RDBMS)BASE (NoSQL)
AcronymAtomic, Consistent, Isolated, DurableBasically Available, Soft state, Eventually consistent
ConsistencyStrong (immediately consistent after commit)Eventual (replicas converge over time)
AvailabilityMay reject operations during failuresAlways responds (even if stale)
Suitable forBanking, e-commerce, healthcare recordsSocial media, analytics, IoT, caching

8. Choosing the Right Database

If you need…Consider
Complex joins, strong ACID, mature toolingPostgreSQL, SQL Server, MySQL
Flexible schema, hierarchical documents, fast aggregationsMongoDB, Couchbase
Millisecond key lookups, caching, pub/subRedis, Memcached
Massive write throughput, time-series, multi-regionCassandra, HBase
Graph traversal, relationship queriesNeo4j, Amazon Neptune
Semantic search, vector similarityPinecone, Weaviate, pgvector (see L43)

9. Summary