Choosing stores for a marketplace
Load a fixed marketplace dataset into PostgreSQL, MongoDB and OpenSearch, run each dataset's key query, record what it needed (index, plan, result), and turn the evidence into a storage table with chosen and rejected stores.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: generate the dataset
- Step 2: start the three stores
- Step 3: load the record store
- Step 4: listings by seller, and what they need
- Step 5: an order that cannot oversell
- Step 6: chat history in a document store
- Step 7: search with typos and facets
- Step 8: an ad hoc report and click analytics
- Step 9: write the storage table
- Step 10: clean up
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Store Selection
- Access patterns before technology Concept · 15 min
- Store families and what each is good at Concept · 25 min
- Sanity-checking a store choice at target scale Worked example · 25 min
- Blobs in object storage, metadata in a database Concept · 15 min
- Choosing stores for a marketplace Lab · 25 min
- Data store selection check Knowledge check · 8 questions
What you will learn
- Characterize a dataset by access pattern, size, growth, consistency and query needs.
- Select a store family per dataset and justify it against at least one rejected alternative.
01. Goal and setup
You will test a store design instead of only drawing it. A small, fixed marketplace dataset goes into three stores: PostgreSQL for listings and orders, MongoDB for chat, and OpenSearch for listing search. For five of the six datasets you run the key query and record what it needed: an index, a plan, a result. Product images need object storage, which lesson 4 covered. Those records become the evidence column of the storage table you start in the last step.
The lab uses small data, so it shows what each query needs, not how fast it runs at scale. The targets below, all assumptions for year two, are what the storage table must be justified against:
dataset target in year 2 (assumptions) main reads
listings 5 M active, 300 edits/s at peak by id, by seller, search
orders 150,000 a day, kept 10 years by buyer, ad hoc reports
chat messages 40 M a day, about 2 KB, 2 years latest N per conversation
product images 6 M new a day, about 400 KB by key, through a CDN
search 30 M queries a day words, typos, facets
click events 400 M a day, kept 13 months counts by listing and dayYou need Docker with about 3 GB of free memory (OpenSearch alone uses about 1.5 GB with a 1 GB heap), about 4 GB of disk for the images, and Python 3.12. Pull the images before you start: postgres:18-alpine, mongo:7 and opensearchproject/opensearch:2.19.4. This lab was run with PostgreSQL 18.6, MongoDB 7.0.45 and OpenSearch 2.19.4. MongoDB 7.0 is supported until August 2027, and the 2.19 line of OpenSearch still received fixes in October 2026 (2.19.7). If 2.19.4 is no longer available, pull the latest 2.19.x patch, which is expected to give the same results. Newer major versions (MongoDB 8.0 or later, OpenSearch 3.x) were not tested with this lab: read their release notes first, and expect explain output to look different.
Every store keeps its data in memory (--tmpfs), so removing the containers removes everything. You reach the stores with docker exec, so no ports are opened on your machine. Create a folder named storage-lab and save the files from each step in it:
storage-lab/
gen_data.py step 1: writes data/ (fixed seed)
schema.sql step 3: PostgreSQL tables and load
seller.sql step 4: seller dashboard, before and after an index
buy.sql step 5: one order as a single conditional statement
chat.js step 6: chat history in MongoDB
listings-index.json step 7: OpenSearch index settings and field types
search.json step 7: a search with typos, filters and a facet
show_search.py step 7: prints the search response as a table
reports.sql step 8: an ad hoc report and click analytics02. Step 1: generate the dataset
The generator writes sellers, listings, orders, chat messages and clicks with a fixed seed, so everyone gets the same rows. Each listing stores only the object key of its photo; the photo itself would live in object storage, as in lesson 4.
"""Generate a small, fixed marketplace dataset (Python 3.12, standard library only)."""
import csv
import json
import random
from datetime import datetime, timedelta, timezone
from pathlib import Path
rng = random.Random(2026) # fixed seed: everyone gets the same data
NOW = datetime(2026, 11, 1, tzinfo=timezone.utc)
OUT = Path("data")
OUT.mkdir(exist_ok=True)
ADJECTIVES = ["Vintage", "Modern", "Handmade", "Classic", "Compact", "Rustic", "Retro"]
ITEMS = {
"clothing": ["leather jacket", "wool coat", "denim jacket", "silk scarf", "boots"],
"furniture": ["oak table", "office chair", "bookshelf", "floor lamp", "desk"],
"kitchen": ["coffee grinder", "teapot", "cast iron pan", "knife set", "mug set"],
"sports": ["road bike", "bike helmet", "tennis racket", "yoga mat", "kayak"],
"electronics": ["speaker", "headphones", "film camera", "turntable", "keyboard"],
}
CONDITIONS = ["new", "like new", "good", "fair"]
COUNTRIES = ["DE", "FR", "NL", "PL", "ES", "IT"]
def stamp(days_back: float) -> str:
return (NOW - timedelta(days=days_back)).strftime("%Y-%m-%dT%H:%M:%SZ")
def write_csv(name: str, header: list[str], rows: list[list]) -> None:
with open(OUT / name, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(header)
writer.writerows(rows)
sellers = [[i, f"seller-{i:04d}", rng.choice(COUNTRIES)] for i in range(1, 1001)]
write_csv("sellers.csv", ["id", "name", "country"], sellers)
listings, bulk = [], []
for i in range(1, 20_001):
category = rng.choice(list(ITEMS))
title = f"{rng.choice(ADJECTIVES)} {rng.choice(ITEMS[category])}"
condition = rng.choice(CONDITIONS)
row = {
"id": i,
"seller_id": rng.randint(1, 1000),
"title": title,
"description": f"{title} in {condition} condition.",
"category": category,
"condition": condition,
"price_cents": rng.randint(5, 400) * 100,
"stock": rng.randint(1, 3),
"status": "active" if rng.random() < 0.8 else "sold",
"created_at": stamp(rng.uniform(0, 180)),
"image_key": f"listings/{i}/main.jpg", # the photo lives in object storage
}
listings.append(list(row.values()))
bulk.append(json.dumps({"index": {"_index": "listings", "_id": i}}))
bulk.append(json.dumps({k: v for k, v in row.items() if k != "image_key"}))
write_csv("listings.csv", list(row), listings)
(OUT / "listings.bulk.ndjson").write_text("\n".join(bulk) + "\n")
orders = []
for i in range(1, 30_001):
listing = rng.choice(listings)
qty = 1 if rng.random() < 0.9 else 2
orders.append([i, listing[0], rng.randint(1, 50_000), qty, listing[6] * qty,
stamp(rng.uniform(0, 90))])
write_csv("orders.csv",
["id", "listing_id", "buyer_id", "qty", "total_cents", "created_at"], orders)
with open(OUT / "messages.ndjson", "w") as f:
for c in range(1, 5001):
start = rng.uniform(1, 60)
count = 60 if c == 42 else rng.randint(2, 18) # c-00042 is a long chat
for n in range(count):
msg = {"conversationId": f"c-{c:05d}", "senderId": rng.randint(1, 50_000),
"sentAt": {"$date": stamp(start - n * 0.01)}}
kind = rng.choices(["text", "offer", "image"], [8, 1, 1])[0]
if kind == "text":
msg |= {"kind": "text", "body": f"Message {n + 1} in chat {c}"}
elif kind == "offer":
msg |= {"kind": "offer", "offerCents": rng.randint(5, 300) * 100}
else:
msg |= {"kind": "image", "imageKey": f"chat/c-{c:05d}/{n + 1}.jpg"}
f.write(json.dumps(msg) + "\n")
clicks = [[stamp(rng.uniform(0, 30)), rng.randint(1, 20_000), rng.randint(1, 50_000),
rng.choice(["search", "home", "seller_page"])] for _ in range(200_000)]
write_csv("clicks.csv", ["ts", "listing_id", "user_id", "source"], clicks)
for path in sorted(OUT.iterdir()):
print(f"{path.name:<22}{sum(1 for _ in open(path)):>8} lines")python3.12 gen_data.pyclicks.csv 200001 lines
listings.bulk.ndjson 40000 lines
listings.csv 20001 lines
messages.ndjson 49424 lines
orders.csv 30001 lines
sellers.csv 1001 lines03. Step 2: start the three stores
Start the containers from inside storage-lab; each one mounts the folder read-only at /lab. The security plugin of OpenSearch is switched off because this is a local lab with no open ports. Never do that on a shared or reachable server.
docker run -d --name storage-pg -e POSTGRES_PASSWORD=lab \
--tmpfs /var/lib/postgresql -v "$PWD":/lab:ro postgres:18-alpine
docker run -d --name storage-mongo --tmpfs /data/db --tmpfs /data/configdb \
-v "$PWD":/lab:ro mongo:7
docker run -d --name storage-os -e discovery.type=single-node \
-e DISABLE_SECURITY_PLUGIN=true -e DISABLE_INSTALL_DEMO_CONFIG=true \
-e OPENSEARCH_JAVA_OPTS="-Xms1g -Xmx1g" \
--tmpfs /usr/share/opensearch/data:uid=1000,gid=1000 \
--tmpfs /usr/share/opensearch/logs:uid=1000,gid=1000 --tmpfs /tmp \
-v "$PWD":/lab:ro opensearchproject/opensearch:2.19.4until docker exec storage-os curl -s localhost:9200 >/dev/null; do sleep 2; done
until docker exec storage-pg pg_isready -h 127.0.0.1 -U postgres -q; do sleep 1; done
until docker exec storage-mongo mongosh --quiet \
--eval 'db.runCommand({ ping: 1 }).ok' >/dev/null 2>&1; do sleep 1; done
docker exec storage-pg psql -U postgres -tAc 'SHOW server_version'
docker exec storage-mongo mongosh --quiet --eval 'db.version()'
docker exec storage-os curl -s localhost:9200 | grep '"number"'18.6
7.0.45
"number" : "2.19.4",04. Step 3: load the record store
PostgreSQL holds the records that need constraints and transactions: sellers, listings and orders. The raw clicks go there too for now, so that step 8 can show what an analytics query costs in a row store.
-- Record store: sellers, listings and orders, plus raw clicks for step 8.
CREATE TABLE sellers (id int PRIMARY KEY, name text NOT NULL, country text NOT NULL);
CREATE TABLE listings (
id int PRIMARY KEY,
seller_id int NOT NULL REFERENCES sellers (id),
title text NOT NULL,
description text NOT NULL,
category text NOT NULL,
condition text NOT NULL,
price_cents int NOT NULL CHECK (price_cents > 0),
stock int NOT NULL CHECK (stock >= 0),
status text NOT NULL,
created_at timestamptz NOT NULL,
image_key text NOT NULL
);
CREATE TABLE orders (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
listing_id int NOT NULL REFERENCES listings (id),
buyer_id int NOT NULL,
qty int NOT NULL CHECK (qty > 0),
total_cents int NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE clicks (ts timestamptz, listing_id int, user_id int, source text);
\copy sellers FROM '/lab/data/sellers.csv' WITH (FORMAT csv, HEADER true)
\copy listings FROM '/lab/data/listings.csv' WITH (FORMAT csv, HEADER true)
\copy orders FROM '/lab/data/orders.csv' WITH (FORMAT csv, HEADER true)
\copy clicks FROM '/lab/data/clicks.csv' WITH (FORMAT csv, HEADER true)
SELECT setval(pg_get_serial_sequence('orders', 'id'), 30000);
ANALYZE;docker exec storage-pg psql -U postgres -q -f /lab/schema.sql setval
--------
30000
(1 row)05. Step 4: listings by seller, and what they need
The seller dashboard reads "my active listings, newest first". EXPLAIN ANALYZE shows the plan PostgreSQL chose and how many rows each step handled; the options switch off timings so that the output is the same on every machine.
-- Seller dashboard: one seller's active listings, newest first.
\echo '--- before the index'
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT id, title, price_cents, created_at FROM listings
WHERE seller_id = 17 AND status = 'active' ORDER BY created_at DESC LIMIT 5;
CREATE INDEX listings_seller_idx ON listings (seller_id, created_at DESC);
\echo '--- after the index'
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT id, title, price_cents, created_at FROM listings
WHERE seller_id = 17 AND status = 'active' ORDER BY created_at DESC LIMIT 5;
SELECT id, title, price_cents, created_at FROM listings
WHERE seller_id = 17 AND status = 'active' ORDER BY created_at DESC LIMIT 5;docker exec storage-pg psql -U postgres -f /lab/seller.sql--- before the index
QUERY PLAN
------------------------------------------------------------------------
Limit (actual rows=5.00 loops=1)
-> Sort (actual rows=5.00 loops=1)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 25kB
-> Seq Scan on listings (actual rows=20.00 loops=1)
Filter: ((seller_id = 17) AND (status = 'active'::text))
Rows Removed by Filter: 19980
(7 rows)
CREATE INDEX
--- after the index
QUERY PLAN
-----------------------------------------------------------------------------------
Limit (actual rows=5.00 loops=1)
-> Index Scan using listings_seller_idx on listings (actual rows=5.00 loops=1)
Index Cond: (seller_id = 17)
Filter: (status = 'active'::text)
Index Searches: 1
(5 rows)
id | title | price_cents | created_at
-------+------------------------+-------------+------------------------
8039 | Handmade cast iron pan | 23800 | 2026-10-26 20:52:48+00
2287 | Rustic office chair | 25500 | 2026-10-26 02:24:10+00
2887 | Handmade road bike | 37700 | 2026-10-02 17:21:03+00
18273 | Vintage boots | 14200 | 2026-09-26 15:23:36+00
19247 | Modern coffee grinder | 5900 | 2026-09-18 22:15:12+00
(5 rows)Before the index, PostgreSQL read all 20,000 listings and threw away 19,980 to sort 20. After the index on (seller_id, created_at DESC), it walked the index from the seller's newest listing and stopped after five rows. Write in your notes: the by-seller read needs an index on (seller_id, created_at); with it, work follows the rows returned, not the table size.
06. Step 5: an order that cannot oversell
Listing 8036 has one unit left. The order is a single statement: it decrements the stock only if a unit is left, and inserts the order only if the decrement happened. Run it twice, for two buyers.
-- Buy one unit of listing 8036 for buyer :buyer, in one atomic statement.
WITH taken AS (
UPDATE listings SET stock = stock - 1
WHERE id = 8036 AND status = 'active' AND stock >= 1
RETURNING id, price_cents
)
INSERT INTO orders (listing_id, buyer_id, qty, total_cents, created_at)
SELECT id, :buyer, 1, price_cents, now() FROM taken
RETURNING id AS order_id, listing_id, total_cents;docker exec storage-pg psql -U postgres -v buyer=777 -f /lab/buy.sql
docker exec storage-pg psql -U postgres -v buyer=778 -f /lab/buy.sql
docker exec storage-pg psql -U postgres \
-c 'SELECT id, stock FROM listings WHERE id = 8036' order_id | listing_id | total_cents
----------+------------+-------------
30001 | 8036 | 22900
(1 row)
INSERT 0 1
order_id | listing_id | total_cents
----------+------------+-------------
(0 rows)
INSERT 0 0
id | stock
------+-------
8036 | 0
(1 row)The first buyer gets order 30001; the second statement inserts nothing because the condition stock >= 1 no longer holds. If the two statements ran at the same moment, the second would wait for the first one's row lock and then, under PostgreSQL's default isolation level, re-check its WHERE clause against the updated row, so it would still insert nothing. Write in your notes: orders need a conditional update and an insert in one atomic step, which a relational store gives directly.
07. Step 6: chat history in a document store
Chat messages have three shapes (text, offer with a price, image with an object key), and almost every read is "the latest messages of one conversation". The script explains that query before and after an index, then prints a few messages.
// Chat history: the latest 20 messages of one conversation, before and after an index.
const query = { conversationId: 'c-00042' };
function explainLatest(label) {
const plan = db.messages.find(query).sort({ sentAt: -1 }).limit(20)
.explain('executionStats');
let stage = plan.queryPlanner.winningPlan.queryPlan ?? plan.queryPlanner.winningPlan;
const stages = [];
while (stage) {
stages.push(stage.stage);
stage = stage.inputStage;
}
const stats = plan.executionStats;
print(`${label}: ${stages.join(' <- ')}, docs examined ${stats.totalDocsExamined},`
+ ` returned ${stats.nReturned}`);
}
explainLatest('before index');
db.messages.createIndex({ conversationId: 1, sentAt: -1 });
explainLatest('after index ');
print('message shapes in the collection:');
db.messages
.aggregate([{ $group: { _id: '$kind', count: { $sum: 1 } } }, { $sort: { _id: 1 } }])
.forEach((row) => print(` ${row._id}: ${row.count}`));
print('newest three messages of c-00042:');
db.messages.find(query).sort({ sentAt: -1 }).limit(3).forEach((m) => {
const content = m.body ?? m.offerCents ?? m.imageKey;
print(` ${m.sentAt.toISOString()} ${m.kind.padEnd(6)} ${content}`);
});docker exec storage-mongo mongoimport --quiet --db market --collection messages \
--file /lab/data/messages.ndjson
docker exec storage-mongo mongosh --quiet market /lab/chat.jsbefore index: SORT <- COLLSCAN, docs examined 49424, returned 20
after index : LIMIT <- FETCH <- IXSCAN, docs examined 20, returned 20
message shapes in the collection:
image: 4866
offer: 4942
text: 39616
newest three messages of c-00042:
2026-09-23T13:16:04.000Z text Message 60 in chat 42
2026-09-23T13:01:40.000Z image chat/c-00042/59.jpg
2026-09-23T12:47:16.000Z text Message 58 in chat 42Without an index, MongoDB scanned the whole collection (COLLSCAN) and sorted it to return 20 messages. With an index on (conversationId, sentAt) it read exactly 20. The three shapes live in one collection without a schema change. PostgreSQL would answer this query just as well with the same index; what moves chat to a separate, sharded store is the target volume in the table above, not this query. Sharded PostgreSQL (for example the Citus extension) and wide-column stores such as Cassandra are serious candidates too, so the storage table must say why one won and when to look again.
08. Step 7: search with typos and facets
Buyers type "vintge lether jaket". The index settings declare which fields are full text and which are exact values; the search allows typos with fuzziness: AUTO (one edit for words of 3 to 5 characters, two for longer ones, as the OpenSearch documentation defines it), filters on status and price, and counts results per category.
{
"settings": { "number_of_shards": 1, "number_of_replicas": 0 },
"mappings": {
"properties": {
"id": { "type": "integer" },
"seller_id": { "type": "integer" },
"title": { "type": "text" },
"description": { "type": "text" },
"category": { "type": "keyword" },
"condition": { "type": "keyword" },
"price_cents": { "type": "integer" },
"stock": { "type": "integer" },
"status": { "type": "keyword" },
"created_at": { "type": "date" }
}
}
}{
"size": 5,
"_source": ["title", "price_cents"],
"query": {
"bool": {
"must": {
"multi_match": {
"query": "vintge lether jaket",
"fields": ["title^2", "description"],
"fuzziness": "AUTO"
}
},
"filter": [
{ "term": { "status": "active" } },
{ "range": { "price_cents": { "lte": 15000 } } }
]
}
},
"sort": ["_score", { "price_cents": "asc" }],
"aggs": { "by_category": { "terms": { "field": "category" } } }
}"""Print an OpenSearch search response as a short table (Python 3.12)."""
import json
import sys
result = json.load(sys.stdin)
print(f"matching listings: {result['hits']['total']['value']}")
for hit in result["hits"]["hits"]:
doc = hit["_source"]
euros = doc["price_cents"] / 100
print(f" score {hit['_score']:5.2f} {doc['title']:<26}{euros:>8.2f} EUR")
print("facet by category:")
for bucket in result["aggregations"]["by_category"]["buckets"]:
print(f" {bucket['key']:<14}{bucket['doc_count']:>5}")docker exec storage-os curl -s -XPUT localhost:9200/listings \
-H 'Content-Type: application/json' --data-binary @/lab/listings-index.json; echo
docker exec storage-os curl -s -XPOST \
'localhost:9200/_bulk?refresh=true&filter_path=errors' \
-H 'Content-Type: application/x-ndjson' \
--data-binary @/lab/data/listings.bulk.ndjson; echo{"acknowledged":true,"shards_acknowledged":true,"index":"listings"}
{"errors":false}docker exec storage-os curl -s -XPOST localhost:9200/listings/_search \
-H 'Content-Type: application/json' --data-binary @/lab/search.json \
| python3.12 show_search.py
docker exec storage-pg psql -U postgres \
-c "SELECT count(*) FROM listings WHERE title ILIKE '%vintge lether%'"matching listings: 1258
score 12.21 Vintage leather jacket 11.00 EUR
score 12.21 Vintage leather jacket 15.00 EUR
score 12.21 Vintage leather jacket 21.00 EUR
score 12.21 Vintage leather jacket 22.00 EUR
score 12.21 Vintage leather jacket 27.00 EUR
facet by category:
clothing 567
furniture 183
kitchen 176
sports 176
electronics 156
count
-------
0
(1 row)OpenSearch found 1,258 matching listings, ranked those that match all three words first, and counted them by category in the same request. The SQL ILIKE found nothing, because it looks for the misspelled text as typed. That comparison is not the whole story: PostgreSQL also has full-text search and trigram similarity (the pg_trgm extension). The search engine earns its place through relevance tuning, facets over millions of listings and keeping search load off the record store, which stays the source of truth and feeds the search copy.
09. Step 8: an ad hoc report and click analytics
Finance asks for revenue per category in October; product asks for the most-clicked listings of the last week.
-- Ad hoc report on orders: revenue per category in October 2026.
SELECT l.category, count(*) AS orders, sum(o.total_cents) / 100 AS revenue_eur
FROM orders o JOIN listings l ON l.id = o.listing_id
WHERE o.created_at >= '2026-10-01' AND o.created_at < '2026-11-01'
GROUP BY l.category ORDER BY revenue_eur DESC;
-- Click analytics: most-clicked listings in the last 7 days of data.
SET max_parallel_workers_per_gather = 0; -- same plan on every machine
EXPLAIN (COSTS OFF)
SELECT listing_id, count(*) AS clicks FROM clicks
WHERE ts >= '2026-10-25' GROUP BY listing_id ORDER BY clicks DESC LIMIT 5;
SELECT count(*) AS rows_in_table,
count(*) FILTER (WHERE ts >= '2026-10-25') AS rows_in_last_7_days
FROM clicks;docker exec storage-pg psql -U postgres -f /lab/reports.sql category | orders | revenue_eur
-------------+--------+-------------
electronics | 2041 | 469463
sports | 2059 | 468398
kitchen | 2089 | 460964
furniture | 2085 | 452908
clothing | 2043 | 441981
(5 rows)
SET
QUERY PLAN
----------------------------------------------------------------------------------------
Limit
-> Sort
Sort Key: (count(*)) DESC
-> HashAggregate
Group Key: listing_id
-> Seq Scan on clicks
Filter: (ts >= '2026-10-25 00:00:00+00'::timestamp with time zone)
(7 rows)
rows_in_table | rows_in_last_7_days
---------------+---------------------
200000 | 46559
(1 row)The revenue report joins orders to listings and groups them, a question nobody planned for, answered with plain SQL. The click query is different: the plan is a sequential scan of the whole clicks table, reading 200,000 rows to use 46,559, and every row carries all its columns. That is fine here, but at 400 million clicks a day the same plan reads billions of rows. Write in your notes: clicks need an analytical copy (columnar store or warehouse) fed from an event stream, not the record store.
10. Step 9: write the storage table
Turn your notes into the storage table. Two rows are filled in as examples. Write the other four (orders, product images, search, click analytics) in the same format, and put the step and the observed number in the evidence line wherever the lab tested something.
dataset listings
reads R1 by id; R2 by seller, newest first; R3 text search (step 7)
volume 5 M active rows, about 300 edits/s at peak, about 2 KB per row
consistency price and stock must be exact at checkout; search may lag 1-2 s
chosen PostgreSQL as the record; OpenSearch as a derived search copy
rejected MongoDB as the record: orders need transactions and joins with
listings, and PostgreSQL serves R1 and R2 with plain indexes
revisit if listing writes fail the lesson 3 scale check on one primary, or
search needs shrink to what PostgreSQL full-text and pg_trgm cover
lab evidence step 4: index (seller_id, created_at) cut 20,000 rows read to 5;
step 5: conditional UPDATE sold the last unit once
dataset chat messages
reads latest N of one conversation (almost all reads); append only
volume 40 M a day, about 2 KB, 2 years online (about 58 TB)
consistency the sender sees their own message at once; others may lag 1 s
chosen document store (MongoDB), sharded by conversationId; message
shapes vary by type (assumption: the team already runs MongoDB)
rejected plain PostgreSQL: 58 TB needs sharding we would build ourselves;
a wide-column store (Cassandra-style) fits the read as well, but
would be one more kind of store for this team to run
revisit if the team adopts sharded PostgreSQL (for example Citus), volume
or retention shrinks until one node passes the lesson 3 check,
or write cost on MongoDB grows enough to make wide-column cheaper
lab evidence step 6: index (conversationId, sentAt) examined 20 documents,
not 49,424; three message shapes share one collection11. Step 10: clean up
Remove the containers. Their data was in memory, so nothing is left on disk except the generated files in storage-lab/data.
docker rm -f -v storage-pg storage-mongo storage-osstorage-pg
storage-mongo
storage-os12. Troubleshooting
13. Check your understanding
14. Apply it
Finish the practice task of this skill with the lab as your evidence:
- Complete the storage table for all six datasets, with a rejected alternative and its reason for each.
- For the two highest-traffic datasets, run the scale check from lesson 3 with your target volumes: size per node, write rate, restore time and hot-key risk.
- Stretch: enable
pg_trgmin the PostgreSQL container (CREATE EXTENSION pg_trgm;), add a trigram index ontitle, and compare asimilarity()query with step 7. Record which needs, such as relevance tuning or facets, still argue for the search engine.
15. Review prompt
Without looking back, answer in your own words:
- What did the seller dashboard need, and how did the plan change once it had it?
- Why can the order statement not oversell, even when two buyers press Pay at the same moment?
- Which lab result supports keeping chat in a document store, and which result does not decide the question?
- What does the click query's plan tell you about the store for click analytics at target volume?
References
- PostgreSQL: using EXPLAIN
- PostgreSQL: transaction isolation (Read Committed)
- PostgreSQL: pg_trgm
- MongoDB: explain results
- OpenSearch: fuzziness
- OpenSearch: installing with Docker
- Docker Official Image: postgres (PGDATA in version 18)
- Citus: distributed PostgreSQL as an extension
- Understand data store models (Azure Architecture Center)
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.