TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท nosql ยท data modelling ยท mongodb ยท cassandra

NoSQL data models

The four main non-relational data models (key-value, document, wide-column and graph), how each is modelled around its access patterns rather than normalised, and the trade-offs in joins, consistency and write cost that decide when to use one instead of a relational database.

16 min6 animations

๐Ÿ“š Builds on๐Ÿ“• Sharding๐Ÿ“š Replication and read replicas

๐Ÿ–จ๏ธ Cheat sheet

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.

From one ledger to storage furniture4 steps
๐Ÿง‘โ€๐Ÿ’ผClerk๐Ÿ“’ Shop ledger
Press play and watch it happen!

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

ModelData shapeFast atExamples
Key-valueOpaque value per keyGet and put by exact keyRedis and Valkey, DynamoDB
DocumentNested JSON-like documents in collectionsReading and writing a whole aggregate; queries and secondary indexes on fieldsMongoDB, Couchbase
Wide-columnRows grouped into partitions, sorted inside them; sparse columnsHigh write throughput; range reads inside one partitionApache Cassandra, ScyllaDB, HBase
GraphNodes and relationships, both with propertiesMulti-hop traversalsNeo4j, 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.

Four families, four kinds of question4 steps
๐Ÿง‘โ€๐Ÿ’ผClerk๐ŸชCoat-peg wall๐Ÿ—„๏ธ Filing cabinet๐Ÿ—ƒ๏ธ Card catalogue๐Ÿ“Œ Photo corkboard
Press play and watch it happen!

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 $lookup stage.

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;4    private String customerId;               // reference by id5    private List<LineItem> items;            // embedded, bounded6    @DocumentReference private Product gift; // stored as the product's id7    private Instant placedAt;8}9 10public interface OrderRepository extends MongoRepository<Order, String> {11    List<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.

Embed in the folder, or leave a slip4 steps
Ana's folder012345Product folders0123๐Ÿง‘โ€๐Ÿ’ผClerk
Press play and watch it happen!

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 (2  customer_id text, placed_at timestamp, order_id text, total decimal,3  PRIMARY 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.

One drawer per question4 steps
Ana's drawer01234Ben's drawer01234๐Ÿง‘โ€๐Ÿ’ผClerk
Press play and watch it happen!

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.

  • ONE is 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 that R + W > RF (for example QUORUM for both with RF = 3) makes every read overlap at least one replica with the latest write. The newest timestamp wins.
  • ALL fails if any replica is down; QUORUM with RF = 3 tolerates 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.

Waiting for one room, or for two4 steps
Room 1 copy012Room 2 copy012Room 3 copy012๐Ÿง‘โ€๐Ÿ’ผClerk๐Ÿ™‹Desk helper
Press play and watch it happen!

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.

The right furniture for each job5 steps
๐Ÿง‘โ€๐Ÿ’ผClerk๐ŸชCoat-peg wall๐Ÿ“’ Shop ledger๐Ÿ—„๏ธ Product cabinet๐Ÿ“Œ Photo corkboard
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about NoSQL data models, told the same way as the story.
  1. Every new order gets added to Ana's folder. What goes wrong after a few years?
  2. The shop wants to answer "who bought the teapot?" quickly, but the catalogue only has a drawer per customer. What does it do?
  3. The clerk only waits for one room to say done when filing, and someone then asks one room for the price. What can happen?
  4. Payments must take money and update stock together, and the boss keeps asking new questions nobody planned for. Which piece of furniture fits best?
Answer every question to check.Passing marks NoSQL data models as done.
Got the hang of NoSQL data models? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ—๏ธ Storing data at scaleStep 7 of 7

โ† Previous on the path๐Ÿ“• ShardingLast step ๐ŸŽ‰Back to the path