NoSQL databases
easy 26 minNoSQL is a family name for databases that do not use the relational model.
Video lesson · Chapter 1 of 5
Orders can look like nested documents
Theory
Read or listen first. About 2 min.
What it is
NoSQL is usually read as "not only SQL". It names many databases that store something other than related tables: values behind keys, whole documents, wide rows inside partitions, or nodes joined by relationships.
They have little in common except what they are not. So "use NoSQL" is not a design decision. "Store each user's events in one partition, sorted by time, because that is the only question we ask" is one.
Why it exists
In the 2000s, large websites met loads that one database machine could not take. They built stores that spread data by key over many ordinary machines and keep working when some fail.
The second reason is shape. A nested profile, a stream of events or a web of friendships can be awkward in tables. A store with the right shape answers its main question with one small read.
A short history
1998
Carlo Strozzi names a small relational database NoSQL because it has no SQL interface. Today's meaning came later.
2006
Google publishes Bigtable, a store designed to reach petabytes over thousands of machines. Wide-column databases follow its model.
2007
Amazon publishes Dynamo, a highly available key-value store, and lets applications trade consistency for availability.
2009
Johan Oskarsson uses NoSQL as the name of a meeting about open source distributed databases. The name sticks.
2012
Eric Brewer revisits CAP and writes that "two of three" was always misleading. In the same year Amazon launches DynamoDB as a service.
Words to know
- Partition key
- The part of a key that decides which machine holds the data.
- Replica
- One of several copies of the same data on different machines.
- Quorum
- Enough replicas to be a majority.
- Eventual consistency
- If writes stop, all copies become equal after some time.
- Schema on read
- The program that reads the data decides what it means; the store does not check it on write.
- Access pattern
- A question the application asks, with its key, order and rate.
- Hot partition
- One partition that gets far more work than the others.
- Network partition
- A break that stops some machines from reaching others.
How it works
Step through the idea, or press Play.
List the questions. Key, order, size and rate of each read and write
Understand it
Start here
A garage with the right holders
Someone tidies a garage. Identical boxes look neat, but a rake does not fit and a saw hides. A holder made for each kind of tool is faster to use, until a question crosses all of the holders.
Good holders are chosen for how the tool is used, not for how it looks on the wall.
The idea
What you gain and what you pay
Advantages
- Flexible, changing record shapes
- Horizontal scaling: add machines
- Built for a specific access pattern
- High write throughput in many designs
- Comfortable with nested or uneven data
Trade-offs
- Few or no joins
- Often eventual consistency by default
- Tools and skills vary by product
- Query flexibility varies a lot
- The same data stored several times
The families
Four shapes
One question for each family
| Family | Looks like | Products | Good for |
|---|---|---|---|
| Key-value | session:123 to user data | Redis, DynamoDB, Memcached | Caching, sessions, simple lookups |
| Document | One user with nested orders | MongoDB, CouchDB, Firestore | Content, catalogues, user profiles |
| Wide-column | Row key, then sorted columns | Cassandra, HBase, ScyllaDB | Time series, device data, message history |
| Graph | User FOLLOWS user | Neo4j, Amazon Neptune, Dgraph | Social links, recommendations, fraud rings |
Key-value
The store does not look inside the value. Simplest and easiest to spread. See key-value database.
Document
The store understands the fields, so it can index and change parts. See document database.
Wide-column
A partition key finds the machine. A clustering key sorts rows inside. Slices are cheap.
Graph
Relationships are first-class records with properties. Multi-step walks stay readable.
Wide-column
A partition, sorted inside
A wide-column table is declared like a relational one but used differently. The primary key has two parts. The partition key says where; the clustering key says in which order.
-- Cassandra (CQL)CREATE TABLE events ( user_id UUID, event_time TIMESTAMP, event_type TEXT, data TEXT, PRIMARY KEY ((user_id), event_time)) WITH CLUSTERING ORDER BY (event_time DESC);SELECT * FROM eventsWHERE user_id = 123e4567-e89b-12d3-a456-426614174000 AND event_time > '2024-01-01';Which question fits this table?
Keep partitions bounded
Graph
Following relationships
In a graph store, a node knows its relationships. "Who do my friends know that I do not?" walks two steps from one node. In SQL the same walk is two joins of the friendship table with itself, which works well with indexes until walks get long or their length is unknown.
Two hops from Alice
// Cypher, the query language of Neo4jCREATE (a:Person {name: "Alice"})CREATE (b:Person {name: "Bob"})CREATE (a)-[:KNOWS]->(b)// friends of friends of AliceMATCH (:Person {name: "Alice"})-[:KNOWS]->()-[:KNOWS]->(x)RETURN x.name, count(*) AS waysORDER BY ways DESCModelling
Start from the questions
- 1
Write the access patterns
"Latest 50 messages of a chat, 2,000 times a second" has a key, an order, a size and a rate.
- 2
One read, one place
Arrange data so that a frequent question touches one partition or one document.
- 3
Duplicate with a plan
Name the true copy and how the others are refreshed: both writes, a change stream, or a rebuild.
- 4
Check the spread
Look for a key that everyone writes: today's date, one celebrity, one country.
- 5
Plan the rare questions
Reports and searches go to another system. See OLAP.
Chat messages, modelled by question
| Question | Partition key | Sort by |
|---|---|---|
| Newest messages of a chat | Chat and month | Time, newest first |
| Chats of a user | User | Last message time |
| Unread count | User and chat | None: one counter |
| Search by words | Not here | A search index beside it |
Scale
Spreading and copying
A write with three copies
When does a read meet the newest write?
Choices with three copies
| W | R | Overlap | Writes survive |
|---|---|---|---|
| 1 | 1 | No | 2 replicas down |
| 2 | 2 | Yes | 1 replica down |
| 3 | 1 | Yes | None down |
| 1 | 3 | Yes | 2 down, but reads then fail |
Spreading by hash and handling hot keys are covered in sharding. The write path of many of these stores is an LSM tree.
Consistency
CAP, said correctly
CAP is about a network partition. When some machines cannot reach others, a request that needs the missing side has two choices: refuse or wait, so that nobody sees old or conflicting data (consistency), or answer with what it has (availability). Without a partition you can have both.
During a partition
Leaning to consistency
- May reject or delay writes during a partition
- Good for balances and stock
- MongoDB with majority writes and suitable reads
- HBase, which documents strictly consistent operations
- Cassandra's lightweight transactions, for single decisions
Leaning to availability
- Keeps answering, repairs conflicts later
- Good for likes, presence and activity logs
- Cassandra at low consistency levels
- CouchDB, which documents eventual consistency
- DynamoDB's default reads; strongly consistent reads are an option
Consistency
BASE and ACID
| Letters | Meaning | In practice |
|---|---|---|
| BA | Basically available | Most requests get an answer, perhaps partial or old |
| S | Soft state | Copies may change later, as repairs arrive, without new input |
| E | Eventually consistent | If writes stop, copies become equal |
| Property | ACID tendency | BASE tendency |
|---|---|---|
| Consistency | Strong, by level | Eventual |
| Availability | May block or refuse | Prefers to answer |
| Focus | Correctness | Availability |
| Scaling | One primary is the simple case | Many machines is the simple case |
Eventually consistent, step by step
Products
Popular NoSQL databases
| Product | Type | Character |
|---|---|---|
| MongoDB | Document | JSON-like documents up to 16 MiB, rich queries, transactions |
| Redis | Key-value | In memory, data structures, optional persistence |
| Cassandra | Wide-column | Many equal nodes, tunable consistency, LSM storage |
| DynamoDB | Key-value and document | Managed by AWS, items up to 400 KB |
| Neo4j | Graph | Nodes and relationships, Cypher, ACID transactions |
| Elasticsearch | Search | Word search and analytics; new data is searchable within about a second by default |
Decide
Do you need one?
A number that decides
Good reasons
- Write rate or size beyond one tested machine
- One dominant access by key
- Records read whole and shaped unevenly
- Walks over relationships of unknown length
- Must answer during a partition
Weak reasons
- "Schemas slow us down"
- "It is web scale" with 50 writes a second
- Data full of relations and unknown questions
- Avoiding SQL
- A hope that consistency will not matter
The side-by-side decision, with examples and migration, is in SQL or NoSQL.
Summary
The whole topic in one minute.
NoSQL is four main shapes. Key-value finds a value by its name, document returns a whole nested record, wide-column returns a sorted slice of one partition, and graph walks relationships.
The cost is planning. You list the questions first, store data once per question, choose a key that spreads the load and choose how many copies must answer. Several NoSQL databases have transactions and strong reads, so check the product instead of the label.
- Four shapes: key-value, document, wide-column, graph.
- Model the questions first; copies are normal, unplanned copies are not.
- The partition key decides the spread, and a hot key defeats any cluster.
- R + W > N makes read and write sets overlap.
- CAP forces a choice only while the network is split.
- Judge a product by setting and operation, not by its family name.