Expert: design, speed and engines · Procedures, triggers, SQL engines and NoSQL · topic 55 of 62 · 30 min
NoSQL: documents, key-value, wide-column and graph
Explanation
Why NoSQL appeared
In the 2000s, web companies hit limits of a single relational server: billions of rows, traffic from every country, and data whose shape changed every week. Making one server bigger (scaling up) gets expensive and eventually stops. They needed to spread data across many servers (scaling out), and they wanted to add a field without a migration. New databases were built for that. They were called NoSQL, which today is usually read as "not only SQL".
Two words first. A schema is the agreed structure of the data (tables, columns, types). Flexible schema means each record may have different fields, and the database does not enforce one structure; your application does.
The four families
| Family | How data looks | Examples | Good for |
|---|---|---|---|
| Document | JSON-like documents with nested fields and arrays | MongoDB, Couchbase, Firestore | Product catalogues, user profiles, content where fields vary |
| Key-value | A key and an opaque value, looked up by key | Redis, Amazon DynamoDB, etcd | Caches, sessions, counters, shopping carts |
| Wide-column | Rows grouped by a partition key, many columns per row, spread over many servers | Apache Cassandra, ScyllaDB, HBase | Huge write-heavy data: sensor readings, messages, event logs |
| Graph | Nodes and relationships (edges) with properties | Neo4j, Amazon Neptune | Friends-of-friends, fraud rings, recommendations, route finding |
DynamoDB is usually called key-value, but it also stores document-style items. Many products blur the lines, so think of the families as shapes, not strict boxes.
The CAP theorem in plain words
When data lives on several servers, the network between them can break: this is a partition. The CAP theorem (Eric Brewer's idea, proven in 2002) says: during a partition, a database must choose. Either it stays Consistent (every read sees the latest write, so some requests must wait or fail) or it stays Available (every request gets an answer, which may be stale).
- Misreading 1: "pick any two of three". Partitions happen whether you like it or not, so the real choice is C or A while a partition lasts. When the network is healthy, you can have both.
- Misreading 2: the C in CAP is the C in ACID. It is not. CAP's C means every reader sees the newest value; ACID's C means rules and constraints hold.
- Misreading 3: "NoSQL is AP, SQL is CP". Many systems let you choose per query, for example Cassandra's consistency levels or MongoDB's read and write concerns.
BASE vs ACID
Module 8 taught ACID: Atomic, Consistent, Isolated, Durable. Many early NoSQL systems chose BASE instead: Basically Available, Soft state, Eventually consistent. Eventually consistent means copies may disagree for a short time, but if writes stop, they all end up with the same value. A "like" count that is a second late is fine; a bank balance is not.
The line has blurred. MongoDB supports multi-document ACID transactions since version 4.0 (and across shards since 4.2). DynamoDB has transactions too. And distributed SQL databases such as CockroachDB, YugabyteDB and Google Spanner scale out while keeping SQL and ACID.
Common mistakes
- Choosing NoSQL "because it scales" for an app with ten thousand users. Fix: a single PostgreSQL or MySQL server handles a lot; choose by data shape and access pattern.
- Thinking "schemaless" means "no design". Fix: in document stores you design around the queries you will run; the schema simply lives in your code.
- Assuming NoSQL has no transactions, or that every NoSQL query is eventually consistent. Fix: read the current docs of the product.
- Using a graph database for simple lookups, or a key-value store for reports. Fix: match the family to the questions you ask.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
NoSQL: documents, key-value, wide-column and graph · 1/7
NoSQL databases store data in shapes other than tables. Let us see why they appeared and what kinds exist.
Prefer a video by a teacher? Find free videos on “nosql database types document key value wide column graph cap theorem explained” on YouTube ↗
In real life: One food-delivery app, several data shapes
A food-delivery app like Swiggy or Zomato has very different kinds of data. Orders and payments need transactions, so a relational database is a natural fit. Restaurant menus vary a lot from place to place, so some teams store them as documents. The rider's live location and the "is this restaurant open" flag change every few seconds and are read constantly, which suits a fast key-value store. A "people who ordered this also ordered" feature is a graph question. This is typical of how such systems are described publicly, not the design of any particular company.
Practice (0/3 done)
A ride-hailing app wants to show "drivers within 2 km" and store each driver's latest location, updated every 3 seconds, with very fast reads. Which family fits the latest-location store best?
See the key-value idea inside SQL. Create a table kv(key TEXT PRIMARY KEY, value INTEGER NOT NULL). Then count page views like Redis INCR, using an upsert: INSERT INTO kv VALUES ('views:home', 1) ON CONFLICT(key) DO UPDATE SET value = value + 1; Run it for 'views:home' three times and for 'views:cart' once. Finally return key and value from kv.
Match each need to a database family and give a one-line reason: (1) user login sessions that expire after 30 minutes, (2) a product catalogue where phones, sarees and rice have very different attributes, (3) 50,000 smart electricity meters sending a reading every minute, (4) finding mutual friends and "people you may know", (5) bank account balances and transfers.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- MongoDB and Redis in practiceProcedures, triggers, SQL engines and NoSQL · same module
- TriggersProcedures, triggers, SQL engines and NoSQL · same module
- NoSQL and MongoDBBackend Development · NoSQL, ORMs and data features
- What is a database?Backend Development · Databases and SQL basics
- Transactions and ACIDBackend Development · SQL in depth
- Choosing a database: DynamoDB, caches and warehousesCloud Computing (AWS, Azure, Google Cloud) · Networking and databases: VPC and RDS
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which database is a graph database?
Answer: Neo4j
Neo4j stores nodes and relationships and is queried with Cypher.
What does the CAP theorem actually say?
Answer: During a network partition, a distributed database must choose between consistency and availability
The choice is forced only while a partition lasts. Partition tolerance is not optional for a distributed system.
Since which version does MongoDB support multi-document ACID transactions (on replica sets)?
Answer: 4.0
MongoDB 4.0 added multi-document transactions on replica sets, and 4.2 extended them to sharded clusters.
What does "eventually consistent" mean?
Answer: Copies may differ for a short time, but agree once writes stop
Replicas catch up over time; a read may briefly return an older value.
Which need is the best fit for a wide-column store such as Cassandra?
Answer: Billions of sensor readings written every second across many servers
Wide-column stores shine at huge, write-heavy, partitioned data.
In MongoDB, what is a collection?Related
Answer: A group of documents, like a table
A collection holds many documents, the way a SQL table holds many rows.
From NoSQL and MongoDB
Why do apps store users in a database and not in an array in the code?Related
Answer: An array is lost when the server restarts
An array lives in memory and disappears on restart. A database keeps data safely on disk.
From What is a database?
Which ACID property means "after the app shows Payment successful, a power cut cannot undo it"?Related
Answer: Durable
Durable: once committed, the change is safely stored and survives crashes.
Which ACID property promises that a committed booking survives a power cut?Related
Answer: Durability
Durability: once COMMIT returns, the change is safely on disk.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Procedures, triggers, SQL engines and NoSQL” before its exam: MongoDB and Redis in practice, Choosing a database, and keeping it safe.
- Module 11 exam: procedures, triggers, engines and NoSQL · 13 questions · 25 min, without help. 6 topics of this module still to finish first.
- Then the next module, Interview questions and practice projects. 62 topics left in the course before the final exam.