Four NoSQL Families and the Trade-offs They Make
Compare key-value, document, wide-column and graph stores by what they can query, how consistent their reads are, how they scale and what they cost to run, then pick one for each part of a ride-hailing workload.
Contentsand lesson path
On this page
- Why it matters
- Four ways to organise data
- Four questions to compare stores
- Consistency you can tune
- Picking a store for a stated workload
- Check your understanding
- Apply it
- Review prompt
Lessons of NoSQL Data Modeling
- Four NoSQL Families and the Trade-offs They Make Concept · 20 min
- Access Patterns First: Modeling Documents Worked example · 30 min
- Partition Keys and Clustering in Wide-Column Stores Concept · 25 min
- Lab: One Workload, Two Data Models Lab · 30 min
- Lab: Flattening Nested Documents for Analytics Lab · 20 min
- Check: Choose and Defend a Data Store Knowledge check · 8 questions
What you will learn
- Compare document, key-value, wide-column and graph stores by query flexibility, consistency, scaling and operating cost, and pick one for a stated workload.
01. Why it matters
NoSQL is a loose name for databases that do not use the relational model of tables joined by SQL. It covers four quite different families: key-value, document, wide-column and graph stores. Each makes some questions cheap and others expensive or impossible, and the choice is hard to undo later.
This skill uses one running example, a ride-hailing app, whose parts ask very different questions. A price quote is fetched by ID many times while the rider decides, then expires. A trip receipt is one rich record. Location pings arrive by the million and are read back by time range. Analysts hunting promo abuse ask who is connected to whom.
A relational database such as PostgreSQL stays a strong default (see relational data modelling). This lesson helps you spot when another family serves a workload better, and what you give up. The examples need only Python 3.12.
02. Four ways to organise data
The families differ in what the database understands about your data, and so in which questions it can answer for you.
- A key-value store maps a key to a value it mostly treats as opaque. You get, set and delete by key, and little else. Redis and Amazon DynamoDB are common examples. Each request touches one key, so they are fast and easy to spread over many machines. Redis can also give a key a timeout with
EXPIRE, after which the key is deleted automatically: handy for sessions and caches. - A document store keeps self-describing records, usually JSON-like documents with nested objects and arrays. MongoDB is the best-known example. The database can read inside a document, so you can filter on any field, add secondary indexes and aggregate.
- A wide-column store such as Apache Cassandra groups rows into partitions. A partition is the set of rows that share a partition key; the store hashes that key to choose the machines that hold it, and keeps its rows sorted by clustering columns. Reads are fast when they name a partition and a range of its rows, and very limited otherwise (lesson 3).
- A graph store such as Neo4j stores nodes (riders, phones, cards) and relationships between them as first-class data. A query describes a pattern of connections, and the database follows stored relationships from node to node.
Promo abuse shows why the data model matters: some people open several accounts to reuse a sign-up discount. Find every rider linked to a flagged rider by a shared phone, card or promo code, directly or through one other rider (up to four links: rider, phone, rider, card, rider). In a key-value store the application has to do the walking. It also has to keep reverse keys, because the store cannot answer which riders used this phone? on its own:
# Which phones, payment cards and promo codes each rider has used.
USED = {
"rider:17": ["phone:a", "card:1"],
"rider:23": ["phone:a", "promo:9"],
"rider:31": ["card:1", "phone:b"],
"rider:44": ["promo:9", "card:2"],
"rider:58": ["phone:b"],
"rider:62": ["card:2", "phone:c"],
"rider:70": ["phone:c"],
}
# A key-value store cannot answer "who else used phone:a?", so the application
# must also keep a reverse key for every phone, card and promo code.
USED_BY: dict[str, list[str]] = {}
for rider, things in USED.items():
for thing in things:
USED_BY.setdefault(thing, []).append(rider)
calls = 0
def kv_get(key: str) -> list[str]:
"""One GET: one network round trip in a real key-value store."""
global calls
calls += 1
return USED.get(key) or USED_BY.get(key, [])
def within(start: str, max_edges: int) -> tuple[dict[str, int], int]:
seen, frontier, rounds = {start: 0}, [start], 0
for edge in range(1, max_edges + 1):
rounds += 1
next_frontier = []
for key in frontier: # every GET here needs the previous round's answers
for neighbour in kv_get(key):
if neighbour not in seen:
seen[neighbour] = edge
next_frontier.append(neighbour)
frontier = next_frontier
return seen, rounds
found, rounds = within("rider:17", max_edges=4)
linked = sorted(k for k, d in found.items() if k.startswith("rider:") and d > 0)
print("linked riders:", linked)
print("GET calls:", calls, "| rounds that wait on the previous one:", rounds)python hops.pylinked riders: ['rider:23', 'rider:31', 'rider:44', 'rider:58']
GET calls: 7 | rounds that wait on the previous one: 4Seven small reads answered the question in four rounds, and no round could start before the previous one returned. Over a network each round is a full trip to the server and back. A real graph has thousands of riders per step, and the application must keep USED_BY correct whenever USED changes. A graph store runs the same walk inside the database as one query. In Neo4j's Cypher language it looks like this:
MATCH (a:Rider {id: 'rider:17'})-[:USED*1..4]-(other:Rider)
WHERE other <> a
RETURN DISTINCT other.id ORDER BY other.id03. Four questions to compare stores
Compare candidate stores with the same four questions.
- Query flexibility. Which questions can it answer that you did not plan for? A key-value store answers one: what is stored under this key? A wide-column store answers questions about one partition, in clustering order. A document store answers ad hoc filters on any field, fast when an index matches. A graph store answers questions about paths and neighbours. Less flexibility often buys predictable speed at scale.
- Consistency. After a write is acknowledged, does every later read see it? That depends on how the store writes and reads its copies, or replicas; the next section shows how.
- Scaling. How does the store grow past one machine? Key-value and wide-column stores split data across nodes by key, so adding nodes adds capacity. MongoDB shards a collection on a shard key. A graph cut across machines pays for the network on many hops, so many graph deployments scale reads instead with replicas that each hold the whole graph.
- Operating cost. Every store you add needs backups, upgrades, monitoring, patches and someone on call who understands it. A managed service moves much of that work onto your bill. Two stores the team knows well often cost less overall than four that are each slightly better at one job.
04. Consistency you can tune
Distributed stores keep several replicas of each value so that one failed machine loses no data. The CAP theorem covers the case where the network splits replicas into groups that cannot talk, a network partition (unrelated to data partitions). The system must then either refuse some requests, losing availability, or answer with possibly stale data, losing consistency. Daniel Abadi's PACELC adds the everyday case: else, when there is no network partition, the system still trades latency against consistency, because waiting for more replicas takes longer.
Cassandra lets you choose that trade-off per request. With replication factor N, a write goes to all N replicas, and its consistency level sets how many must acknowledge before the client gets a reply: W. A read asks R replicas and returns the newest answer. Common levels are ONE, QUORUM (a majority: two of three replicas when N = 3) and ALL. The rule from the Cassandra documentation is R + W > N: when it holds, every set of replicas you might read shares at least one replica with every set that acknowledged the write. You can check this by brute force for N = 3:
from itertools import combinations
N = 3 # replication factor: every value is stored on 3 replicas
REPLICAS = range(N)
def always_overlap(w: int, r: int) -> bool:
"""Does every possible write set of size w share a replica with every read set?"""
return all(set(ws) & set(rs)
for ws in combinations(REPLICAS, w)
for rs in combinations(REPLICAS, r))
print("W R W+R>N every read meets the write")
for w in range(1, N + 1):
for r in range(1, N + 1):
print(f"{w} {r} {str(w + r > N):<6} {always_overlap(w, r)}")python quorum.pyW R W+R>N every read meets the write
1 1 False False
1 2 False False
1 3 True True
2 1 False False
2 2 True True
2 3 True True
3 1 True True
3 2 True True
3 3 True TrueThe columns agree in every row: overlap is guaranteed exactly when W + R > N. Now watch a stale read. A rider changes the saved home address, and the write is acknowledged once one replica has it, while the other two catch up:
def run(write_to: list[int], read_from: list[int]) -> str:
# three replicas all hold version 1 of a rider's saved home address
replicas = [{"value": "Old Street", "version": 1} for _ in range(3)]
for i in write_to: # the replicas that applied version 2 before the ack
replicas[i] = {"value": "New Street", "version": 2}
answers = [replicas[i] for i in read_from]
return max(answers, key=lambda a: a["version"])["value"] # newest wins
CASES = [
("W=1, R=1, read replica 2", [0], [2]),
("W=1, R=2, read replicas 1 and 2", [0], [1, 2]),
("W=2, R=2, read replicas 1 and 2", [0, 1], [1, 2]),
("W=2, R=2, read replicas 0 and 2", [0, 1], [0, 2]),
]
for label, write_to, read_from in CASES:
print(f"{label:<33} {run(write_to, read_from)}")python stale_read.pyW=1, R=1, read replica 2 Old Street
W=1, R=2, read replicas 1 and 2 Old Street
W=2, R=2, read replicas 1 and 2 New Street
W=2, R=2, read replicas 0 and 2 New StreetWith W = 1, a read of one or even two replicas can miss the only replica with the new value, so the rider sees the old address straight after saving the new one. With W = 2 and R = 2, any two replicas you read include one that took the write. That is why QUORUM for both writes and reads is the usual way to get read-your-writes in Cassandra without waiting for every replica.
Other combinations cost more. Writing at ONE and reading at ALL also overlaps, but every read waits for the slowest replica and fails when any replica is down. ANY lets a write be acknowledged by a stored hint before any replica has it, so it is weaker than ONE. (Abadi notes that quorums alone do not give strict linearisability in every failure case, but R + W > N is the core idea.) MongoDB chooses differently by default: a replica set reads from its primary and acknowledges writes once a majority of members have them.
05. Picking a store for a stated workload
Start from the access patterns, not the products. For each part of the app, note how data is looked up, how much there is and what a stale read would cost. Then match the shape:
- Price quotes: every access is one lookup by quote ID, and a quote must disappear two minutes after it was issued. A key-value store with expiry fits; anything richer adds cost without value.
- Trip records: a trip is shown as a whole, with its fare breakdown and addresses, and support staff filter by rider, driver or status. A document store with indexes fits. Lesson 2 designs it.
- Driver location pings: a high, steady write rate, read back as this driver's pings over this period. A wide-column store fits, partitioned by driver and time bucket (lesson 3).
- Promo-abuse rings: variable-depth questions about shared phones, cards and promo codes. A graph store fits, often fed by a copy of the data.
- Payments and the ledger: money moves between accounts and must balance, so transactions and constraints matter most. A relational database fits.
Then apply the operating-cost question to the whole list: five stores for five patterns is rarely sensible for a small team, and PostgreSQL may serve quotes and trips well enough until load proves otherwise. Add a family when a pattern clearly needs it, and record the trade-off you accepted.
06. Check your understanding
07. Apply it
Start the skill project: list the five main access patterns of your ride-hailing app. For each, write the lookup key, the read and write rates, how much data one request touches and what a stale read would cost. Pick a family for each and name the question that decided it. Then decide which patterns can share a store and justify the final number of stores. Lessons 2 to 5 build on this list.
08. Review prompt
Without looking back:
- Name the four families, and for each one a question it answers cheaply and one it cannot.
- What does PACELC add to CAP?
- State the overlap rule and give two level combinations that satisfy it when N = 3, with the cost of each.
- Why does a key-value store need reverse keys to answer a graph question?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.