One big ledger
A busy shop keeps its records in one big ledger. Every page has the same ruled columns: name, address, item, price. It's tidy and strict. Each fact is written once, and when you need two things together ("which customer made this order?"), you look up the number on one page and turn to another.
Then the shop grows. Some orders need a gift note, but there's no column for it, so every page has to be ruled again before anyone can write one down. And there's only one ledger: however fast the clerk writes, it can only be in one place.
So the shop tries something else. Instead of one ledger, it buys storage furniture built for the jobs it does most: filing cabinets that can stand in several rooms, holding folders that don't all need the same papers. That family of furniture has a name: NoSQL.
What NoSQL means
"NoSQL" is an umbrella for databases that don't use the relational model, usually read as "not only SQL". A relational database stores rows in tables with a fixed schema, normalises data so each fact lives in one place, and answers questions with joins, all inside ACID transactions.
NoSQL databases grew in the late 2000s for three reasons:
- Scale-out. They were designed to shard and replicate across many cheap machines from the start, instead of scaling one big server up.
- Flexible schemas. Records in the same collection can have different fields, so adding one doesn't need a migration of every row. The schema still exists; it moves into the application code that reads the data.
- Specific access patterns. Each model is fast at one shape of query (a lookup by key, a whole aggregate, a sorted range, a traversal) by giving up generality, usually joins and multi-record transactions.
"Schemaless" is a misnomer: data always has a shape. The question is whether the database enforces it on write or the code interprets it on read.
Four kinds of furniture
The shop's back room now has four pieces of furniture, each built for one kind of question:
- A wall of coat pegs, each with a number. Hang anything on peg 42, and get it back by saying "42". It's the fastest thing in the room, but you can't ask "which coats are red?" without checking every peg.
- Filing cabinets of folders. Each folder holds everything about one customer, and folders don't have to hold the same papers.
- A wide card catalogue. Each drawer is labelled with a customer's name, and the cards inside are kept in date order. A card can fill in just the few columns it needs out of many.
- A corkboard of photos joined by string. To see who knows whom, you follow the strings from photo to photo.
The four families
| Model | Data shape | Fast at | Examples |
|---|---|---|---|
| Key-value | Opaque value per key | Get and put by exact key | Redis and Valkey, DynamoDB |
| Document | Nested JSON-like documents in collections | Reading and writing a whole aggregate; queries and secondary indexes on fields | MongoDB, Couchbase |
| Wide-column | Rows grouped into partitions, sorted inside them; sparse columns | High write throughput; range reads inside one partition | Apache Cassandra, ScyllaDB, HBase |
| Graph | Nodes and relationships, both with properties | Multi-hop traversals | Neo4j, Amazon Neptune |
The lines blur: DynamoDB is key-value and document, Redis adds hashes, sorted sets and streams on top of plain keys, and MongoDB has secondary indexes and aggregation pipelines. Classify by the access pattern a store is built for, not by the label on the box.
A native graph database such as Neo4j stores relationships as first-class records attached to their nodes, so a query like "friends of
friends who bought this" follows links directly instead of joining tables once per hop. In Neo4j's query language,
Cypher, that is MATCH (a:Person)-[:KNOWS]->(b)-[:KNOWS]->(c) RETURN c.
Whole folders or a slip
In the filing cabinet, the clerk has a choice. Ana's address and her orders can go straight into Ana's folder, which is called embedding, so one trip to the cabinet brings back everything about her.
Or the page about one of Ana's orders can just say "see product folder 7", a slip pointing to another folder. That keeps one copy of each product, but the clerk now makes two trips.
The rule of thumb: keep together what you always read together. But a folder that gains a page with every order keeps growing, and in the end it gets too thick to carry. Things that pile up without end get their own folders.
Documents: embed or reference
In a document database the main modelling choice is embedding versus referencing:
- Embed data that is read with its parent, belongs to it and is bounded in size: a customer's addresses, an order's line items. One read returns the whole aggregate, and a write to a single document is atomic in MongoDB.
- Reference (store the other document's
_id) when the related data is shared by many parents, changes on its own, or grows without bound. Reading it costs a second query or a$lookupstage.
Unbounded arrays are the classic mistake: a customer document that embeds every order grows forever, slows every read, and eventually hits MongoDB's 16 MB document limit. MongoDB has supported multi-document ACID transactions since 4.0 (4.2 on sharded clusters), but they cost more than single-document writes, so a model that needs them everywhere is usually a relational model in disguise.
With Spring Data MongoDB, the mapping says which is which, and a repository interface gets its queries derived from method names:
1@Document("orders")2public class Order {3@Id private String id;4private String customerId; // reference by id5private List<LineItem> items; // embedded, bounded6@DocumentReference private Product gift; // stored as the product's id7private Instant placedAt;8}910public interface OrderRepository extends MongoRepository<Order, String> {11List<Order> findByCustomerIdOrderByPlacedAtDesc(String customerId);12}
Spring generates the implementation: save inserts or replaces the document, and the finder becomes a query on
customerId sorted by placedAt. Index the fields you query on, or the query scans the whole collection. @Indexed
and @CompoundIndex only create indexes if auto index creation is on (spring.data.mongodb.auto-index-creation=true,
off by default since Spring Data MongoDB 3.0); in production, create them explicitly.
Furniture for the questions you ask
With the ledger, you write each fact once and work out the answer when someone asks. With the card catalogue, you do it the other way round: first list the questions, then arrange the drawers so each question opens just one drawer.
"Ana's orders since February" is easy: open Ana's drawer, the cards are already in date order. But "who bought the teapot?" would mean opening every drawer. So the shop sets up a second catalogue with a drawer per product, and writes each order on two cards, one in each, which is called denormalising. Reading is quick; writing is double work, and if a price changes, every copy has to be fixed.
Model by access pattern, then denormalise
Relational design starts from the data and normalises it; queries come later. NoSQL design, especially for wide-column and key-value stores, starts from the access patterns and shapes the data so each query reads one partition.
In Cassandra, a table's primary key has two parts:
- the partition key decides which nodes store the row (hashed onto the token ring), and every query should give it;
- the clustering columns sort rows inside the partition, so range reads like "since February" are one sequential slice.
1CREATE TABLE orders_by_customer (2customer_id text, placed_at timestamp, order_id text, total decimal,3PRIMARY KEY ((customer_id), placed_at, order_id)4) WITH CLUSTERING ORDER BY (placed_at DESC, order_id ASC);
There are no joins, so a second question gets a second table (orders_by_product) holding the same orders keyed
differently. That is denormalisation: reads become one-partition lookups, and the cost moves to writes. Every order is
written twice, updates must reach every copy, and the copies can disagree if one write fails. Cassandra's logged batches
(which make sure all of a batch's writes are eventually applied) or retries help keep them in step; nothing makes it free.
Watch partition size too: a partition key with too little spread (a country, a single day) makes huge, hot partitions, the same hotspot problem as a bad shard key.
How sure do you need to be?
The card catalogue has copies in three rooms, in case one room is locked. When the clerk files a card, a helper at the desk carries it to all three rooms. The clerk chooses how long to wait: until one room says "done" (fast), until two say it (safer), or all three (slowest, and stuck if a room is locked).
Waiting for one is quick, but then someone reading from a room the card hasn't reached yet sees the old card. If you wait for two rooms when filing and ask two rooms when reading, at least one of them always has the new card.
Consistency is a dial
Replicated NoSQL stores make the CAP and latency trade-off per request instead of once.
Cassandra has tunable consistency: every read and write sets a consistency level, such as ONE, QUORUM,
LOCAL_QUORUM or ALL, saying how many replicas must respond. The coordinator node forwards the request to the
replicas and answers the client once enough have replied.
ONEis fastest and most available, but a read can return a stale value from a replica that hasn't received the write.- With replication factor
RF, choosing read and write levels so thatR + W > RF(for exampleQUORUMfor both withRF = 3) makes every read overlap at least one replica with the latest write. The newest timestamp wins. ALLfails if any replica is down;QUORUMwithRF = 3tolerates one.
Others expose the same dial differently: MongoDB with write concern and read concern, DynamoDB with eventually consistent reads by default and strongly consistent reads on request. Either way, many NoSQL defaults favour availability and latency, so check what your reads can see.
The right furniture for each job
The ledger hasn't gone anywhere. For money, where two pages must change together or not at all, and for questions nobody thought of in advance, its strict columns and cross-references are still the best tool.
So the shop uses each piece for what it does best: the ledger for payments, the coat pegs for each shopper's basket, the filing cabinet for the product folders and the corkboard for "people who bought this also liked". Using several kinds side by side is called polyglot persistence. The catch: when a product changes, every piece that holds a copy has to hear about it.
When relational still wins, and polyglot persistence
Choose a relational database when you need:
- multi-row ACID transactions and constraints (payments, inventory, bookings), with foreign keys enforced by the database;
- ad hoc queries and joins over data whose questions aren't known up front (reporting, back offices);
- a moderate scale that one primary with read replicas handles comfortably, which covers most applications.
Modern relational databases also store JSON columns, and several NoSQL stores have added transactions, so the gap is narrower than it was. Pick from the access patterns and the guarantees you need, not from the category.
Polyglot persistence means using several stores in one system, each for the workload it fits: PostgreSQL for orders and payments, Redis for sessions and carts, MongoDB for a product catalogue, Neo4j for recommendations. The cost is operational (more systems to run, back up and secure) and in consistency: the copies are usually kept in sync asynchronously, via events or change data capture from the system of record, so they lag behind it for a while.