Lab: One Workload, Two Data Models
Build the same three ride-hailing queries twice: as MongoDB documents with compound indexes proved by explain(), and as wide-column query tables with partition and clustering keys, then measure partition sizes to find a hot, unbounded partition and fix it with a bucket.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Generate the workload
- Step 2: Model 1, documents with one index per query
- Step 3: Model 2, one query table per query
- Step 4: Measure partitions, find the hot one, fix it
- Step 5: Compare the two models
- Check your understanding
- Apply it: stretch tasks
- 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
- Design a document schema from access patterns, choosing between embedding and referencing and adding indexes for the main queries.
- Design a wide-column or key-value table around partition and clustering keys that avoids hot and unbounded partitions.
01. Goal and setup
In this lab you serve one workload with two data models and compare what each costs. The workload is three queries from the ride-hailing app:
- Q1 rider history: the 10 most recent completed trips of rider R0123.
- Q2 driver day: every trip of driver D042 on 17 October 2026, in time order.
- Q3 city hour: every trip requested in London between 18:00 and 19:00 on 17 October, for a demand map.
Model 1 is a MongoDB collection with one document per trip and a compound index per query; you prove each index with explain(). Model 2 is three wide-column query tables keyed the way Cassandra would key them. There is no Cassandra in this lab. Instead, SQLite tables declared WITHOUT ROWID with a composite primary key stand in for them. Such a table is stored as one B-tree sorted by its primary key, so the rows of one partition sit together in clustering order, which is the property a Cassandra node gives you. SQLite does not hash partitions across nodes, so the last step measures partition sizes directly and shows where a real cluster would hurt.
You need: Docker with the mongo:7 image, Python 3.12 (its built-in sqlite3 module is enough for model 2) and PyMongo. Tested with MongoDB 7.0, Python 3.12, PyMongo 4.20 and SQLite 3.53. The scripts read MONGO_URL, defaulting to mongodb://localhost:27017.
two-models-lab/
├── gen_trips.py step 1: writes trips.jsonl (24,000 seeded trips)
├── mongo_model.py step 2: model 1, documents and indexes
├── wide_model.py step 3: model 2, query tables in wide.db
└── partition_sizes.py step 4: naive keys against bucketed keysdocker run -d --name nosql-mongo -p 27017:27017 mongo:7
mkdir two-models-lab && cd two-models-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pymongo==4.20.002. Step 1: Generate the workload
The generator writes 30 days of trips with a fixed seed, so your numbers match the ones below. Demand is deliberately uneven, as in real cities: London gets 70% of trips, and evenings are busier than nights. Both models load the same file.
"""Write 30 days of ride-hailing trips to trips.jsonl (seeded, repeatable)."""
import json
import random
from collections import Counter
from datetime import datetime, timedelta
rng = random.Random(2026)
CITIES = ["London", "Leeds", "Bristol", "York"]
CITY_WEIGHTS = [70, 15, 10, 5]
HOUR_WEIGHTS = [1, 1, 1, 1, 1, 2, 4, 8, 9, 5, 4, 4,
5, 4, 4, 5, 7, 9, 10, 8, 6, 4, 3, 2] # busy mornings and evenings
START = datetime(2026, 10, 1)
with open("trips.jsonl", "w") as out:
for n in range(1, 24_001):
day = rng.randrange(30)
hour = rng.choices(range(24), HOUR_WEIGHTS)[0]
at = START + timedelta(days=day, hours=hour, seconds=rng.randrange(3600))
trip = {
"trip_id": f"T{n:06d}",
"rider_id": f"R{rng.randint(1, 600):04d}",
"driver_id": f"D{rng.randint(1, 120):03d}",
"city": rng.choices(CITIES, CITY_WEIGHTS)[0],
"status": "completed" if rng.random() < 0.88 else "cancelled",
"requested_at": at.strftime("%Y-%m-%dT%H:%M:%S"),
"fare_total": round(rng.uniform(5, 45), 2),
}
out.write(json.dumps(trip) + "\n")
trips = [json.loads(line) for line in open("trips.jsonl")]
print("trips:", len(trips))
print("by city:", sorted(Counter(t["city"] for t in trips).items()))
print("first:", " ".join(str(v) for v in trips[0].values()))python gen_trips.pytrips: 24000
by city: [('Bristol', 2376), ('Leeds', 3577), ('London', 16854), ('York', 1193)]
first: T000001 R0106 D114 London completed 2026-10-04T10:34:56 27.2603. Step 2: Model 1, documents with one index per query
Each trip becomes one document with nested driver, pickup and fare objects, as in lesson 2. Each query gets a compound index built with the ESR guideline: equality fields first, then the sort or range field. Q2 and Q3 have equality on one field and a time range that is also the sort, so requested_at comes second. The script runs every query twice through explain: once with the planner's choice, and once forced to a collection scan with hint({"$natural": 1}). It also saves the trip IDs each query returns, so step 3 can check that model 2 gives the same answers.
"""Model 1: one trips collection in MongoDB, one compound index per query."""
import json
import os
from datetime import datetime
from pymongo import ASCENDING as ASC, DESCENDING as DESC, MongoClient
db = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"))["lab"]
db.drop_collection("trips")
def to_document(t: dict) -> dict:
return {
"_id": t["trip_id"],
"rider_id": t["rider_id"],
"driver": {"id": t["driver_id"]},
"pickup": {"city": t["city"]},
"status": t["status"],
"requested_at": datetime.fromisoformat(t["requested_at"]),
"fare": {"total": t["fare_total"], "currency": "GBP"},
}
db.trips.insert_many(to_document(json.loads(line)) for line in open("trips.jsonl"))
db.trips.create_index([("rider_id", ASC), ("status", ASC), ("requested_at", DESC)],
name="rider_history")
db.trips.create_index([("driver.id", ASC), ("requested_at", ASC)], name="driver_day")
db.trips.create_index([("pickup.city", ASC), ("requested_at", ASC)], name="city_hour")
DAY = (datetime(2026, 10, 17), datetime(2026, 10, 18))
HOUR = (datetime(2026, 10, 17, 18), datetime(2026, 10, 17, 19))
QUERIES = { # name: (filter, sort, limit)
"Q1 rider history": ({"rider_id": "R0123", "status": "completed"},
{"requested_at": -1}, 10),
"Q2 driver day": ({"driver.id": "D042",
"requested_at": {"$gte": DAY[0], "$lt": DAY[1]}},
{"requested_at": 1}, 0),
"Q3 city hour": ({"pickup.city": "London",
"requested_at": {"$gte": HOUR[0], "$lt": HOUR[1]}},
{"requested_at": 1}, 0),
}
def stages(plan: dict) -> str:
plan = plan.get("queryPlan", plan)
names = []
while plan:
names.append(plan["stage"] + (f"({plan['indexName']})" if "indexName" in plan
else ""))
plan = plan.get("inputStage")
return " > ".join(names)
print("documents:", db.trips.count_documents({}))
for name, (flt, sort, limit) in QUERIES.items():
print(name)
for label, hint in (("index", None), ("no index", {"$natural": 1})):
cmd = {"find": "trips", "filter": flt, "sort": sort, "limit": limit}
if hint:
cmd["hint"] = hint # force a full collection scan for comparison
ex = db.command("explain", cmd, verbosity="executionStats")
st = ex["executionStats"]
print(f" {label:<9} {stages(ex['queryPlanner']['winningPlan']):<38} "
f"keys={st['totalKeysExamined']:<3} docs={st['totalDocsExamined']:<6}"
f" returned={st['nReturned']}")
ids = [d["_id"] for d in db.trips.find(flt, {"_id": 1}).sort(sort).limit(limit)]
json.dump(ids, open(f"mongo_{name[:2]}.json", "w"))python mongo_model.pydocuments: 24000
Q1 rider history
index LIMIT > FETCH > IXSCAN(rider_history) keys=10 docs=10 returned=10
no index SORT > COLLSCAN keys=0 docs=24000 returned=10
Q2 driver day
index FETCH > IXSCAN(driver_day) keys=4 docs=4 returned=4
no index SORT > COLLSCAN keys=0 docs=24000 returned=4
Q3 city hour
index FETCH > IXSCAN(city_hour) keys=50 docs=50 returned=50
no index SORT > COLLSCAN keys=0 docs=24000 returned=50Every indexed plan is an IXSCAN on the intended index, with keys examined equal to documents returned: the index finds exactly the matching trips, already in the requested order, and no SORT stage appears. The forced collection scans read all 24,000 documents and sort in memory to return the same results. Note what model 1 cost: one document per trip, plus one entry per trip in each of the three indexes and the _id index. Adding a fourth query later costs one more create_index call on the live collection.
04. Step 3: Model 2, one query table per query
Now design for a wide-column store. Each query gets its own table, and its primary key is partition key, then clustering columns:
trips_by_rider: partition(rider_id, status), clusteringrequested_at DESC, trip_id. Status is in the partition key because Q1 always filters on it.trips_by_driver_day: partition(driver_id, day), clusteringrequested_at, trip_id.trips_by_city_hour: partition(city, hour), clusteringrequested_at, trip_id.
trip_id closes each key so that two trips at the same second stay separate rows. The day and hour columns are derived from requested_at at write time, exactly as an application would compute bucket columns before writing to Cassandra. Every trip is written to all three tables. EXPLAIN QUERY PLAN shows how SQLite runs each query:
"""Model 2: one table per query, each keyed like a Cassandra table, in SQLite."""
import json
import sqlite3
from pathlib import Path
Path("wide.db").unlink(missing_ok=True)
db = sqlite3.connect("wide.db")
# PRIMARY KEY = partition columns, then clustering columns. WITHOUT ROWID makes
# SQLite store each table as one B-tree sorted by that key: rows of a partition
# sit next to each other in clustering order, as on a Cassandra node.
TABLES = {
"trips_by_rider": ("rider_id, status", "requested_at DESC, trip_id"),
"trips_by_driver_day": ("driver_id, day", "requested_at, trip_id"),
"trips_by_city_hour": ("city, hour", "requested_at, trip_id"),
}
COLUMNS = ("trip_id TEXT, rider_id TEXT, driver_id TEXT, city TEXT, status TEXT, "
"day TEXT, hour TEXT, requested_at TEXT, fare_total REAL")
for name, (partition, clustering) in TABLES.items():
db.execute(f"CREATE TABLE {name} ({COLUMNS}, "
f"PRIMARY KEY ({partition}, {clustering})) WITHOUT ROWID")
rows = []
for line in open("trips.jsonl"):
t = json.loads(line)
rows.append((t["trip_id"], t["rider_id"], t["driver_id"], t["city"],
t["status"], t["requested_at"][:10], t["requested_at"][:13],
t["requested_at"], t["fare_total"]))
for name in TABLES: # denormalised: every trip is written once per table
db.executemany(f"INSERT INTO {name} VALUES ({', '.join('?' * 9)})", rows)
db.commit()
QUERIES = {
"Q1": "SELECT trip_id FROM trips_by_rider WHERE rider_id = 'R0123' "
"AND status = 'completed' ORDER BY requested_at DESC LIMIT 10",
"Q2": "SELECT trip_id FROM trips_by_driver_day WHERE driver_id = 'D042' "
"AND day = '2026-10-17' ORDER BY requested_at",
"Q3": "SELECT trip_id FROM trips_by_city_hour WHERE city = 'London' "
"AND hour = '2026-10-17T18' ORDER BY requested_at",
"no key": "SELECT trip_id FROM trips_by_driver_day WHERE rider_id = 'R0123'",
}
for name in TABLES:
print(f"{name:<20} {db.execute(f'SELECT count(*) FROM {name}').fetchone()[0]} rows")
for name, sql in QUERIES.items():
plan = " | ".join(r[3] for r in db.execute("EXPLAIN QUERY PLAN " + sql))
print(f"{name:<6} {plan}")
if name.startswith("Q"):
ids = [r[0] for r in db.execute(sql)]
same = ids == json.load(open(f"mongo_{name}.json"))
print(f"{'':<6} {len(ids)} trips, same as MongoDB: {same}")python wide_model.pytrips_by_rider 24000 rows
trips_by_driver_day 24000 rows
trips_by_city_hour 24000 rows
Q1 SEARCH trips_by_rider USING PRIMARY KEY (rider_id=? AND status=?)
10 trips, same as MongoDB: True
Q2 SEARCH trips_by_driver_day USING PRIMARY KEY (driver_id=? AND day=?)
4 trips, same as MongoDB: True
Q3 SEARCH trips_by_city_hour USING PRIMARY KEY (city=? AND hour=?)
50 trips, same as MongoDB: True
no key SCAN trips_by_driver_dayEach query is a SEARCH ... USING PRIMARY KEY on its full partition key, and there is no USE TEMP B-TREE FOR ORDER BY line, which is how SQLite reports an extra sort: the clustering order already is the requested order. Both models return the same trips. The last query asks trips_by_driver_day for a rider, a column outside its key, and gets a SCAN of the whole table; Cassandra would refuse that query without ALLOW FILTERING. For reference, the first table in CQL:
CREATE TABLE trips_by_rider (
rider_id text, status text, requested_at timestamp, trip_id text,
driver_id text, city text, fare_total decimal,
PRIMARY KEY ((rider_id, status), requested_at, trip_id)
) WITH CLUSTERING ORDER BY (requested_at DESC, trip_id ASC);05. Step 4: Measure partitions, find the hot one, fix it
A first design often uses the obvious key: the city for the demand map, the driver for earnings. The script builds those two naive tables next to the bucketed ones, then measures every partition: how many there are, the rows and approximate bytes in the largest one (sum of the stored values), its share of all rows, and, for keys without a time bucket, its size after three years if growth continues at the same rate.
"""Measure partition sizes: two naive keys against the keys of wide_model.py."""
import sqlite3
db = sqlite3.connect("wide.db")
COLUMNS = ("trip_id TEXT, rider_id TEXT, driver_id TEXT, city TEXT, status TEXT, "
"day TEXT, hour TEXT, requested_at TEXT, fare_total REAL")
for name, partition in (("trips_by_city", "city"), ("trips_by_driver", "driver_id")):
db.execute(f"DROP TABLE IF EXISTS {name}")
db.execute(f"CREATE TABLE {name} ({COLUMNS}, "
f"PRIMARY KEY ({partition}, requested_at, trip_id)) WITHOUT ROWID")
db.execute(f"INSERT INTO {name} SELECT * FROM trips_by_city_hour")
ROW_BYTES = ("length(trip_id) + length(rider_id) + length(driver_id) + length(city) "
"+ length(status) + length(day) + length(hour) + length(requested_at) + 8")
DESIGNS = [ # table, partition key, does one partition keep growing with time?
("trips_by_city", "city", True),
("trips_by_city_hour", "city, hour", False),
("trips_by_driver", "driver_id", True),
("trips_by_driver_day", "driver_id, day", False),
("trips_by_rider", "rider_id, status", True),
]
print(f"{'table':<20} {'partitions':>10} {'largest':>8} {'KB':>6} {'share':>6} "
f"{'in 3 years':>11}")
for table, key, grows in DESIGNS:
sizes = db.execute(f"SELECT count(*), sum({ROW_BYTES}) FROM {table} "
f"GROUP BY {key} ORDER BY 1 DESC").fetchall()
rows, size = sizes[0] # the largest partition
later = f"{rows * 1095 // 30:,}" if grows else "same"
print(f"{table:<20} {len(sizes):>10,} {rows:>8,} {size / 1024:>6.0f} "
f"{rows / 24_000:>6.1%} {later:>11}")python partition_sizes.pytable partitions largest KB share in 3 years
trips_by_city 4 16,854 1333 70.2% 615,171
trips_by_city_hour 2,498 63 5 0.3% same
trips_by_driver 120 239 19 1.0% 8,723
trips_by_driver_day 3,595 16 1 0.1% same
trips_by_rider 1,196 59 5 0.2% 2,153Read the table row by row:
trips_by_cityis both hot and unbounded. Four partitions for the whole table, and London alone holds 70.2% of all rows, so every London write and every demand-map read hits one replica set. It also grows every day: about 615,000 rows after three years at this rate, all read in one place.trips_by_city_hourfixes both. The hour bucket spreads London over hundreds of partitions, and no partition can outgrow one hour of one city: the largest holds 63 rows. Q3 asks for one city-hour, so it still reads one partition.trips_by_driveris unbounded but grows slowly: 239 rows now, about 8,700 in three years. Q2 could even be served from it with a range onrequested_at. The day bucket is still cheap insurance, because Q2 always asks for one day.trips_by_rideralso grows without a bucket, at about 2,150 rows in three years for the busiest rider. That is a deliberate choice: Q1 reads the newest 10 rows from the front of the partition, and a rider's trips grow slowly, so a bucket would add reads without solving a real problem.
The lesson is to decide buckets from measured growth and the read pattern, not by habit.
06. Step 5: Compare the two models
Both models answer the three queries by reading only the matching rows, in order. They differ in where the cost goes:
- Writes. Model 1 writes each trip once, and the database maintains four index entries for it. Model 2 writes it three times, as 72,000 rows in total, and your application keeps the copies consistent when a trip changes.
- New questions. In model 1 a new query is a new index on the live collection, and ad hoc questions still work, slowly, without one. In model 2 a new query is a new table that must be backfilled from the source data, and anything off-key is a scan.
- Scale. Model 2 is designed for a cluster from the start: every read names a partition, and step 4 shows how to keep partitions bounded and evenly loaded. Model 1 runs on one server here; sharding it later brings the same questions back, because a shard key on a low-cardinality field such as the city concentrates load just as the naive partition key did.
07. Check your understanding
08. Apply it: stretch tasks
- Shard the hot key. Add a
trips_by_city_hour_shardtable whose partition key is(city, hour, shard)withshardcomputed from the trip ID modulo 4. Rerun the partition measurement and write the four-query read that rebuilds Q3. - Your five patterns. Model the five access patterns of your ride-hailing project both ways, in MongoDB with explain() evidence and as query tables with a partition-size report, and write one paragraph on which model you would run in production and why.
- Break an index on purpose. Recreate
rider_historyas{requested_at: -1, rider_id: 1, status: 1}and explain Q1 again. Record keys and documents examined, and explain the change.
09. Review prompt
Without looking back:
- Which explain() numbers show that a MongoDB index fits a query, and which stage shows that it does not support the sort?
- Why does a
WITHOUT ROWIDtable with a composite primary key behave like a wide-column partition, and what does it not imitate? - Why was
(city)both hot and unbounded, and how did(city, hour)fix both? - Name one cost of each model that the other does not have.
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.