Lesson 26 of 29Beyond relational, and interviews
NoSQL Families and When to Use Them
Document, key-value, wide-column and graph stores modelled on the same shop data: what each is fast at, what it makes painful, and when Postgres is still the answer.
You have now seen what a relational database can do in production. The last question is when you should reach for something else. A teammate proposes moving the orders service to MongoDB "because it scales and we will not need migrations". Another wants DynamoDB because the AWS bill looks simpler, and a third has read that Cassandra handles any write volume. All three may be right for some workload, and all three can be badly wrong for yours. The way to decide is not a feature list. It is to write down the queries your product runs, then model the same data in each family and see which queries get cheap and which become impossible. This lesson does that with the shop data you have used all course, so you can argue the choice in a design review and in an interview.
Start from access patterns
An access pattern is a query your product runs, with its key, its frequency and its latency budget. "Load customer 42's last 20 orders, 300 times a second, under 50 ms." "Count paid orders per city, once a night." "Find products whose name matches 'headphnes', on every keystroke."
Relational databases are built for unknown future queries. You normalise the data, add indexes as new patterns appear, and the planner works out how to answer anything you can write in SQL. Most NoSQL stores flip that deal: you design the storage around the queries you know today, and in return those queries get predictable latency at a scale where a single relational primary would struggle. Queries you did not plan for range from slow to impossible.
That is why the sensible default at most companies is Postgres until it hurts. The useful version of that phrase spells out what "hurts" means, because each pain points at a different family:
- Write volume beyond one primary, after you have tuned queries, batched writes and bought a bigger machine. Wide-column and key-value stores spread writes across many nodes by design.
- Huge read volume on one key with sub-millisecond latency, like sessions or rate limit counters. That is an in-memory key-value store.
- A query type SQL is poor at: full-text relevance, many-hop relationship traversal, similarity over vectors, scans of billions of rows for analytics. Each has a specialised engine.
- Global writes in several regions with local latency, where some managed NoSQL services offer multi-region tables out of the box.
"We do not want migrations" is not on the list. A document store still has a schema; it lives in your application code instead of the database, and changing it means migrating documents or handling every old shape forever.
| Family | Data model | Query flexibility | Consistency | Scaling | Typical use |
|---|---|---|---|---|---|
| Relational | Tables, joins | Anything SQL can say | Strong, ACID | Vertical, replicas, sharding is work | Orders, payments, most business data |
| Document | Nested JSON-like documents | Good within a collection, weak across | Strong per document, transactions cost more | Sharding built in | Catalogues, content, per-user profiles |
| Key-value | Key to value, or PK plus sort key | By key only, plus secondary indexes | Usually tunable or eventual for indexes | Horizontal by key | Sessions, carts, high-scale lookups |
| Wide-column | Partition key to sorted rows | Only the queries each table was built for | Tunable per query | Horizontal, write-optimised | Event logs, messages, time series at scale |
| Graph | Nodes and edges | Traversals of any depth | Usually strong on one machine | Harder to shard | Fraud rings, recommendations, permissions |
System Design's Databases lesson introduced these families. Here you go one level down: how each one stores the shop, and where it breaks.
Document stores: one read per page
MongoDB and Firestore store documents: nested JSON-like objects in a collection, each with an _id. The design rule is "data that is read together is stored together". Instead of three tables joined at read time, a customer document can embed their orders and each order's items.
Press Run (⌘ Enter) to see what happens.That one document is everything the "My account" page needs, fetched by _id in a single read, with no joins. Notice what got copied: the product name now lives inside every order item. That is deliberate denormalisation (an order should show what the product was called when it was bought), but it also means renaming a product does not update old orders, and if you wanted it to, you would have to rewrite every document that mentions it.
The decisions you make in a document model:
- Embed when the child belongs to one parent, is read with it, and stays bounded: order items inside an order, addresses inside a customer.
- Reference (store the other document's
_id) when the child is shared, large, or grows without limit. Products are shared by thousands of orders, so orders reference product ids. A customer's lifetime of orders can grow without bound, so in production you would usually make orders their own collection with acustomer_idfield and an index on it, not an embedded array. - Watch the size limit. A MongoDB document is capped at 16 MB and Firestore's at about 1 MiB. Unbounded arrays (every comment, every event) are the classic way to hit it, and long before the limit they make every update rewrite a big document.
Now try a question the model was not designed for: "which customers bought the USB-C Hub?"
Press Run (⌘ Enter) to see what happens.Without an index on the nested field, the document store reads every customer. MongoDB does let you index nested array fields (multikey indexes) and has $lookup for join-like queries, so this is fixable, but each new cross-cutting question needs its own index or a different collection shape. In SQL it was one join and an index you probably already had.
Two more facts seniors know. Updates to a single document are atomic, which is why embedding also helps with consistency. Multi-document transactions exist in MongoDB (on replica sets and sharded clusters) but they are slower and have time limits, so a design that needs them everywhere is a sign the data is relational. And "schemaless" really means schema-on-read: use MongoDB's $jsonSchema validation or a strict model in your app, or six months later you will find three spellings of createdAt.
Key-value: design around the key
A key-value store answers one question fast: given this key, what is the value? Redis and Valkey (the open-source fork of Redis started in 2024) keep data in memory with rich value types: strings, hashes, lists, sorted sets, streams. They are the standard home for sessions, caches, rate limit counters and leaderboards. Redis and Caching in the Python Backend course covers using them from an API.
DynamoDB is key-value at a different level: durable, managed, and partitioned across many machines. Databases on AWS explains partition keys, sort keys and single-table design. What matters here is the physics underneath, because it is where DynamoDB designs fail:
- The partition key is hashed to choose a physical partition. Each partition has a throughput limit, so all traffic for one key value lands on one machine's budget.
- A global secondary index (GSI) is a second, automatically maintained copy of the data keyed differently. It is how you query by something other than the main key. Every write to the table becomes an extra write to each GSI, and GSI reads are eventually consistent.
- Scan reads the whole table and is billed for it. If a feature needs a scan, the key design missed an access pattern.
The most common failure is a hot partition: a key that looks reasonable but concentrates traffic. Today's date, a status like pending, or a celebrity's user id all send a burst of writes to one partition while the others sit idle. This block simulates a busy launch day: 2,000 events are written, and you compare three partition key choices.
Press Run (⌘ Enter) to see what happens.Keying by day puts every write on one partition. Keying by user spreads it across a handful of partitions, but only 8 users exist, so the spread is uneven and one heavy user still lands in one place. A high-cardinality key (here the event id; in practice a user id among millions, or a key with a random suffix such as DAY#2025-06-07#7) spreads it evenly. The price of write sharding with a suffix is on the read side: to read "all of today" you now query every suffix and merge.
What does this print?
-- 2,000 writes, all with created_at on the same day -- 4 partitions, partition = hash(partition_key) % 4 -- partition_key = date(created_at) -- How many of the 4 partitions receive any writes?
Wide-column: one table per query
Cassandra, ScyllaDB and Google Bigtable store rows grouped by a partition key, sorted inside the partition by clustering columns, on a log-structured (LSM) storage engine that makes writes cheap (How Databases Store Data explains why). There are no joins and very limited ad-hoc filtering. You design query first: list the queries, then create one table per query, shaped so each query reads a single partition in order.
-- Cassandra (CQL): "a customer's orders, newest first"
CREATE TABLE orders_by_customer (
customer_id int,
created_at timestamp,
order_id int,
status text,
total_cents int,
PRIMARY KEY ((customer_id), created_at, order_id)
) WITH CLUSTERING ORDER BY (created_at DESC, order_id DESC);
-- "pending orders for the warehouse, by day" needs its own table
CREATE TABLE orders_by_status_day (
status text,
day date,
created_at timestamp,
order_id int,
PRIMARY KEY ((status, day), created_at, order_id)
);
SELECT * FROM orders_by_customer WHERE customer_id = 1 LIMIT 20; -- one partition, fast
SELECT * FROM orders_by_customer WHERE status = 'pending'; -- rejected without ALLOW FILTERINGThe same order is written to both tables. That write fan-out is normal in Cassandra, and it is cheap because writes are appends. The cost moves to your application: every new query means a new table and a backfill job, and keeping the copies in agreement is your problem. Note the (status, day) partition key: status alone would be a hot partition, exactly as in the simulation above.
Consistency is tunable per query. With a replication factor of 3, writing and reading at QUORUM (2 of 3 replicas) means the read and write sets overlap, so you read your own writes; ONE is faster and can return stale data. Consistency and CAP covers the R + W > N reasoning. Two operational traps: deletes write tombstones that slow reads until compaction removes them, so a "queue" table with constant deletes degrades badly; and lightweight transactions (IF NOT EXISTS) run a consensus round and are many times slower than normal writes.
Graph: relationships as data
In a graph database (Neo4j with Cypher, Amazon Neptune with openCypher or Gremlin), relationships are stored as first-class edges that point straight at their neighbours. Following an edge is a pointer hop, not an index lookup, so queries of variable depth stay fast: "accounts within four hops of this known fraudster", "can this user reach this document through any group".
In SQL, each hop is another pair of joins. Here is a two-hop recommendation: "customers who bought something Ada bought also bought..."
Press Run (⌘ Enter) to see what happens.The same idea in Cypher reads like the sentence:
MATCH (ada:Customer {id: 1})-[:BOUGHT]->(p:Product)<-[:BOUGHT]-(other:Customer)-[:BOUGHT]->(rec:Product)
WHERE other <> ada AND NOT (ada)-[:BOUGHT]->(rec)
RETURN rec.name, count(DISTINCT other) AS bought_by
ORDER BY bought_by DESCFor two fixed hops, Postgres with good indexes is fine, and Recursive CTEs and hierarchies showed how SQL handles variable depth. A graph database earns its place when depth is variable, the graph is dense, and traversal is the main workload, not an occasional report. Standards are converging: ISO published GQL as a graph query language in 2024, SQL:2023 added property-graph queries (SQL/PGQ), and Postgres 19 is adding SQL/PGQ support, so check the release notes for what shipped before you plan around it.
The specialists
Some engines are less a data model than a query type done extremely well:
- Time-series (TimescaleDB, which is a Postgres extension; InfluxDB): automatic time partitioning, compression, retention policies, downsampling. Metrics and IoT readings.
- Search engines (OpenSearch, Elasticsearch): inverted indexes, relevance scoring, facets, typo tolerance. Full-text search in the database showed how far Postgres gets first. A search engine should be a copy, never the source of truth.
- Vector databases (Pinecone, Qdrant, Weaviate, Milvus) versus pgvector in Postgres. For most teams pgvector with an HNSW index is enough and keeps vectors next to the rows they describe; dedicated stores win at very large scale or with heavy filtering needs.
- Analytical column stores (ClickHouse, DuckDB, BigQuery, Snowflake): store each column separately and compress it, so "sum revenue by month over two billion rows" reads only two columns. They are poor at updating single rows, which is exactly what your operational database is good at.
The cost of several databases
Every store you add is another thing to back up, monitor, secure, upgrade and page someone about at 3 a.m. The subtler cost is consistency between stores. The naive approach, a dual write from the app, fails in a way you can predict.
The product rename commits in Postgres.
The rule that follows: pick one source of truth for each piece of data, treat every other store as a derived copy fed by an outbox or change data capture, and make sure each copy can be rebuilt from scratch. If you cannot say which store wins when two disagree, you have two sources of truth, which means none.
Match each workload to the family that fits it best.
- access pattern
- A specific query the product runs, with its key, frequency and latency budget. NoSQL designs are built around them.
- embedding
- Storing related data inside a parent document so one read returns it all. Best for bounded data read together.
- hot partition
- A partition that receives a disproportionate share of traffic because many requests share one partition key value.
- global secondary index
- In DynamoDB, a maintained copy of a table keyed differently so it can be queried another way. Eventually consistent, and it costs extra writes.
- query-first design
- Wide-column modelling where each table is shaped to answer one known query from a single partition.
- tombstone
- A marker an LSM-based store writes for a delete. Many tombstones slow reads until compaction removes them.
- polyglot persistence
- Using several kinds of database in one system, each for the workload it suits, at the cost of keeping them in sync.