Lecture: Lecture 21 - Beyond Relational Databases
Related: Replication CAP Theorem ACID vs BASE and Conflict Resolution · MongoDB Polyglot Persistence Hadoop and Apache Spark · Reliability Manager Log Records Undo Redo and Checkpoints
Why “Not Only SQL”? (Slides 2–5)
Traditional relational databases (RDBMSs) excel at structured tables and complex multi-table joins, but they face friction at web and Big Data scale: altering a predefined schema on a massive live distributed table is blocking and expensive, and scaling up a single server (vertical scaling) hits hardware cost ceilings.
The NoSQL label began in 1998 (Carlo Strozzi’s lightweight relational database without an SQL interface) and became a broader movement in 2009 when Johan Oskarsson (Last.fm) popularized #NoSQL on Twitter for non-relational databases (Slide 2). Today, NoSQL stands for “Not Only SQL”.
Relational vs. Non-Relational comparison (Slides 3–5)
| Dimension | Relational databases (RDBMS) | Non-Relational databases (NoSQL) |
|---|---|---|
| Storage model | Table-based; each record is a structured flat row | Specialized stores (document, key-value, graph, columnar) |
| Schema | Predefined per table; live schema changes are usually blocking | Schema-less / schema-free; dynamic per document (suits semi-structured and unstructured data) |
| Scaling | Mostly vertical (more powerful hardware/CPUs on one machine) | Horizontal (add more commodity servers to the resource pool to reduce load) |
| Query interface | Standardized SQL; built for complex queries and joins | Custom query APIs; no native joins and no single standard interface |
| Data shape | Flat, structured records | Complex hierarchical data (e.g., nested JSON / XML) |
| Examples | MySQL, Oracle, SQLite, PostgreSQL, Microsoft SQL Server | MongoDB, BigTable, Redis, Cassandra, HBase, CouchDB |
Four families of NoSQL databases (Slides 6–13)
| Type | Structure & mechanism | Strengths / best fit | Examples |
|---|---|---|---|
| 1. Key-Value (Slide 7) | Simplest store: opaque key → value pairs with no internal schema | Blazingly fast, great performance, trivial horizontal scaling | Redis, Riak, Memcached |
| 2. Column-Oriented / Column-Family (Slide 8) | Stores data by column (e.g., Name = "Daniele": row1, row3; "Marco": row2, row4), retrieved in parallel like indexes; rows can be rebuilt transparently | Massive parallel reads/writes across wide distributed tables | Cassandra, HBase, Hypertable, Amazon DynamoDB |
| 3. Graph (Slide 9) | Based on graph theory: Vertices and Edges | Networks (social graphs, dependencies, routing) | Neo4j, Infinite Graph, OrientDB |
| 4. Document (Slide 10) | Keys mapped to self-describing (attribute = value) nested hierarchical trees (maps, lists, datetimes); documents can be heterogeneous | Evolving business objects without rigid tables | MongoDB, CouchDB, RavenDB |
(Familiarity — Slides 11–13): CouchDB (“Cluster Of Unreliable Commodity Hardware”) is a notable document-oriented database written in Erlang (ideal for concurrent, scalable distributed systems). It exposes a RESTful JSON/HTTP API, supports incremental bi-directional replication with conflict detection, and queries/indexes data using MapReduce.
MapReduce: moving computation to the data (Slides 14–28)
Published by Google in 2004 (Dean & Ghemawat, OSDI ‘04), MapReduce is a scalable distributed programming model for running parallel algorithms across clusters of commodity machines (Slides 14–15).
- Core principle: Move the computation (algorithm) to the data (where the records reside on remote nodes/disks), instead of moving terabytes of raw data across the network to one central compute node.
- Functional programming inspiration: A pure function’s output depends only on its arguments—calling twice with the same always produces the exact same , independent of local or global program state.
How Map and Reduce work (Slides 16–17, 22)
Map(doc)(Required):- Invoked once per record (
doc). Can skip a document or callemit(key, value)one or more times. - Strict independence rule (Slide 17):
Mapmay NOT depend on any information outside that single document. Because each document is mapped in complete isolation, CouchDB and Hadoop can runMapin parallel across nodes and update views incrementally (re-mapping only changed documents).
- Invoked once per record (
- Sort & Shuffle (Automatic intermediate step, Slide 22):
- All emitted
(key, value)pairs are sorted and grouped bykey. Platforms such as Hadoop also let developers customize the shuffle phase to control network communication costs between mappers and reducers.
- All emitted
Reduce(key, values)(Optional):- Receives one
keyand the list of all values emitted for that key, reducing them to one key-value output (the simplest SQL analogue is aGROUP BYaggregation, though reducers can output lists or tuples too). - Re-reduce (Slide 22): In CouchDB, reduce functions can also be called recursively on their own partial outputs across distributed nodes or grouped key prefixes.
- Receives one
Worked source examples (Slides 18–28)
Using the source database of 8 university exam documents (Id, Exam, Student, AYear, Date, Mark, CFU):
- Example 1 — Average mark per exam (Slides 19, 23):
Map:emit(doc.exam, doc.mark);→ groupsDatabaseintovalues = [29, 26, 25].Reduce:S = sum(values); N = len(values); return S / N;→Bioinformatics: 30,Computer architectures: 25.5,Database: 26.67,Software engineering: 19.5.
- Example 2 — Average mark per
[exam, AYear](Slides 20, 24):Map:emit([doc.exam, doc.AYear], doc.mark);- Same
Reduceproduces[Database, 2014-15]: 25.5(from[26, 25]) and[Database, 2015-16]: 29(from[29]).
- Rereduce trap on
AVG(Slide 25):- Calling CouchDB
Rereducewithgroup level = 1(examonly) feeds the partial averages[25.5, 29]back into the sameReducefunction, returning(25.5 + 29) / 2 = 27.25forDatabase—which is inaccurate compared to the true weighted mean26.67, because2014-15had 2 exams and2015-16had 1 exam! - Fix: Have
Reduceemit[sum, count](e.g.,[51, 2]and[29, 1]), soRereducesums both components to[80, 3]before dividing (80 / 3 = 26.67).
- Calling CouchDB
- Example 3a — CFU-weighted average per student (Slides 21, 26–27):
Map:emit(doc.student, [doc.mark, doc.CFU]);Reduce:S = sum([X*Y for X,Y in values]); N = sum([Y for X,Y in values]); return S / N;→S123456: 25.6,S654321: 23.9,s987654: 25.
- Example 3b — Distributed exam count across nodes (Slide 28):
S123456has 3 docs on Node 1 (Reduce → 3) and 1 doc on Node 2 (Reduce → 1). Because counting/summing is distributive,Rereducegives the exact total3 + 1 = 4.
CouchDB views as materialized indexes (Slide 29)
- The only way to query CouchDB is by defining a view produced by MapReduce.
- Every database has a built-in default view (
key = doc.id,value = whole document, no Reduce). - Views are materialized and stored sorted by key, allowing a single database to maintain multiple primary indexes; when writing a
Mapfunction, the primary design goal is to store related data under nearby keys.
NoSQL banking design recipe & idempotency (Slides 68–75)
The failure problem with mutable account documents (Slides 69–73)
A bank must always balance—it cannot lose or create money. Suppose you send $100 to cousin Paul in CouchDB by updating two separate account documents (bank_account_001 from 1000 → 900, and bank_account_002 from 1000 → 1100). Because CouchDB lacks multi-document ACID transactions, if the second update message is lost during transmission (Slide 72), your balance drops to 900 while Paul’s stays 1000—$100 vanishes and CouchDB cannot guarantee the bank balance (Slide 73).
The single-document + MapReduce solution (Slides 74–75)
Redesign the data model so every transfer is stored as one single immutable transaction document (Slide 74):
{
"id": "transaction001",
"from": "bank_account_001",
"to": "bank_account_002",
"qty": 100,
"when": 1290678353.45
}Because writing one document is atomic, $100 can never be half-transferred. Current account balances are then computed via a MapReduce view (Slide 75):
// Map
function(transaction) {
emit(transaction.from, transaction.amount * -1);
emit(transaction.to, transaction.amount);
}
// Reduce
function(key, values) {
return sum(values);
}For bank_account_001 ([1000, -100]) and bank_account_002 ([1000, 100]), the view returns {key: "bank_account_001", value: 900} and {key: "bank_account_002", value: 1100}.
Added clarification: why this design preserves idempotency
(Added study connection to Reliability Manager Log Records Undo Redo and Checkpoints, outside the source PDF): Unlike Lecture 18’s warning against logging relative deltas (+100) on a mutable value, the Banking Design Recipe remains idempotent on both reads and writes:
- Reads (MapReduce): There is no mutable
balanceoverwritten in place—MapReduce is a pure function over immutable transfer documents, so re-running it 1 or 100 times produces the exact same balances (900and1100). - Writes (
PUTwithid): Writing viaPUT /bank/transaction001uses the transaction’s uniqueidas an idempotency key; retrying the samePUTafter a timeout returns409 Conflictrather than creating a second transfer (provided the client reuses"transaction001"instead of generating a new ID).
Common confusions
- Thinking
Rereducealways matches a fullReduce: Holistic/algebraic aggregates likeAVGcannot simply average partial averages (27.25 ≠ 26.67on Slide 25); you must pass[sum, count]intermediates to preserve exactness. - Allowing
Map(doc)to query another document: Forbidden because it breaks parallel execution and incremental view maintenance. - Trying to fake joins in Document DBs: Splitting into separate account documents and issuing two updates sacrifices atomicity; store atomic events/embedded sub-documents and aggregate with views instead.
Retrieval questions with answers
1. Why is a Map function strictly forbidden from reading other documents or global state? What two capabilities depend on this rule?
Because Map(doc) depends solely on one isolated document, CouchDB and MapReduce platforms can execute mapping in parallel across cluster nodes and update views incrementally whenever individual documents change.
2. On Slide 25, re-reducing AVG across [Database, 2014-15] = 25.5 and [Database, 2015-16] = 29 gave 27.25 instead of 26.67. How do you fix the Reduce output so Rereduce returns the exact mean?
Return a pair [sum, count] ([51, 2] and [29, 1]) rather than a pre-divided average, so Rereduce can sum both parts ([80, 3]) and divide once at the final display step (80 / 3 = 26.67).
3. Why does storing each transfer as one {id, from, to, qty} document plus MapReduce solve CouchDB’s lost-message banking bug without losing idempotency?
Writing a single document is atomic (eliminating half-applied transfers), PUT with a fixed id rejects duplicate retries (409 Conflict), and MapReduce computes balances purely from immutable transfer documents, making repeated runs idempotent.