AlgoViz

NoSQL databases

easy 26 min

NoSQL 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

0:00 / 3:47

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

  1. 1998

    Carlo Strozzi names a small relational database NoSQL because it has no SQL interface. Today's meaning came later.

  2. 2006

    Google publishes Bigtable, a store designed to reach petabytes over thousands of machines. Wide-column databases follow its model.

  3. 2007

    Amazon publishes Dynamo, a highly available key-value store, and lets applications trade consistency for availability.

  4. 2009

    Johan Oskarsson uses NoSQL as the name of a meeting about open source distributed databases. The name sticks.

  5. 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.

Step 1 of 4

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.

One holder for each kind of tool
The same box for everything

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

Users send requests to an app. The app asks four stores: a key-value store for a session by id, a document store for one whole profile, a wide-column store for the events of one user, and a graph store for friends of friends.
A system rarely needs all four. Each arrow is the question that its store answers with one small read.
FamilyLooks likeProductsGood for
Key-valuesession:123 to user dataRedis, DynamoDB, MemcachedCaching, sessions, simple lookups
DocumentOne user with nested ordersMongoDB, CouchDB, FirestoreContent, catalogues, user profiles
Wide-columnRow key, then sorted columnsCassandra, HBase, ScyllaDBTime series, device data, message history
GraphUser FOLLOWS userNeo4j, Amazon Neptune, DgraphSocial links, recommendations, fraud rings
DynamoDB sits between two rows: AWS describes it as both a key-value and a document database. Full-text search engines are sometimes counted as a fifth family.
  • 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.

SQL
-- 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';
A UUID column needs a UUID value. Two events of one user in the same millisecond would overwrite each other here, so real tables add a unique last key part, such as a time-based UUID.

Which question fits this table?

Model the query first. A second question often means a second table with the same facts under another key.

Keep partitions bounded

50eventsday×365×5 years×1 KB≈91 MB50 \tfrac{\text{events}}{\text{day}} \times 365 \times 5\,\text{years} \times 1\,\text{KB} \approx 91\,\text{MB}
One user's events over five years, with assumed numbers. A device that writes every second makes 86,400 KB a day, so about 86 MB each day. Add the day or month to its partition key.

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

Di is reached through two friends and Eli through one, so Di is the stronger suggestion.
Text
// 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 DESC
Run the three CREATE clauses as one statement, then the MATCH as another, so that the names a and b are known.

Modelling

Start from the questions

  1. 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. 2

    One read, one place

    Arrange data so that a frequent question touches one partition or one document.

  3. 3

    Duplicate with a plan

    Name the true copy and how the others are refreshed: both writes, a change stream, or a rebuild.

  4. 4

    Check the spread

    Look for a key that everyone writes: today's date, one celebrity, one country.

  5. 5

    Plan the rare questions

    Reports and searches go to another system. See OLAP.

Chat messages, modelled by question

QuestionPartition keySort by
Newest messages of a chatChat and monthTime, newest first
Chats of a userUserLast message time
Unread countUser and chatNone: one counter
Search by wordsNot hereA search index beside it
The same message feeds three shapes. That is normal here and would be a smell in a normalised relational model.

Scale

Spreading and copying

A write with three copies

An app sends a write for user 42 to a coordinator in a cluster. The coordinator hashes the key and sends the write to nodes A, B and C, which hold three copies. Two acknowledgements, from A and B, are enough; C receives it later.
In this example two answers of three are enough. If C is down, the write still succeeds and C catches up.

When does a read meet the newest write?

R+W>NN=3,;W=2,;R=2:;4>3R + W > N \qquad N = 3,; W = 2,; R = 2:; 4 > 3
NN copies, WW must confirm a write, RR must answer a read. If the sum is larger than NN, the two sets share at least one replica. Sloppy quorums, clock trouble and concurrent writes can still surprise you, so this is not a full guarantee.

Choices with three copies

WROverlapWrites survive
11No2 replicas down
22Yes1 replica down
31YesNone down
13Yes2 down, but reads then fail
Assumes strict quorums on the three home replicas. Cassandra calls this tunable consistency: each request can choose its level.

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

Partition tolerance is not a switch. Networks break, so the real choice is C or A while one is broken.

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

LettersMeaningIn practice
BABasically availableMost requests get an answer, perhaps partial or old
SSoft stateCopies may change later, as repairs arrive, without new input
EEventually consistentIf writes stop, copies become equal
PropertyACID tendencyBASE tendency
ConsistencyStrong, by levelEventual
AvailabilityMay block or refusePrefers to answer
FocusCorrectnessAvailability
ScalingOne primary is the simple caseMany machines is the simple case
These are tendencies, not a border. MongoDB has multi-document transactions, DynamoDB groups up to 100 actions, and Neo4j is fully transactional. Distributed SQL databases scale out.

Eventually consistent, step by step

The window is often short, but nothing in the word eventual promises how short.

Products

Popular NoSQL databases

ProductTypeCharacter
MongoDBDocumentJSON-like documents up to 16 MiB, rich queries, transactions
RedisKey-valueIn memory, data structures, optional persistence
CassandraWide-columnMany equal nodes, tunable consistency, LSM storage
DynamoDBKey-value and documentManaged by AWS, items up to 400 KB
Neo4jGraphNodes and relationships, Cypher, ACID transactions
ElasticsearchSearchWord search and analytics; new data is searchable within about a second by default
Limits are from each product's documentation in November 2026. Check them before you design against them.

Decide

Do you need one?

A number that decides

20,000,000 devices×1,440100,000=288,000/s×3=864,000/s\frac{20{,}000{,}000 \text{ devices} \times 1{,}440}{100{,}000} = 288{,}000/\text{s} \qquad \times 3 = 864{,}000/\text{s}
Each device reports once a minute, which is 1,440 times a day. Writes like this, always addressed by device, ask for a store that spreads by key.

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.

Sources