Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

System Design (High-Level Design)  Module 6 – Data modelling and storage engines

Choosing a data model: relational to vector

Compare relational, document, wide-column, key-value, graph, time-series, search and vector models, and pick each from the access patterns it serves.

  • Beginner
  • 20 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Describe the relational, document, wide-column, key-value, graph, time-series, search and vector models
  • Match each model to the access patterns it serves well, starting from a written inventory
  • Explain why most systems use more than one store, and what every extra store costs

Before you start

What you’ll learn · Before you start

What you will learn

  • Describe the relational, document, wide-column, key-value, graph, time-series, search and vector models
  • Match each model to the access patterns it serves well, starting from a written inventory
  • Explain why most systems use more than one store, and what every extra store costs

Before you start

On this page

At its peak, a food-delivery app in one large city reads menus 4,000 times a second, takes 120 orders a second and records 25,000 rider locations a second, and no single shape of data serves all three well. A data model is the shape a store gives your data: rows in tables, nested documents, values under keys, nodes joined by edges, points on a timeline, or numbers that describe meaning. Every shape makes some questions cheap and others expensive, so you choose it from the questions your system will ask most often, never from habit or fashion.

Below, you write those questions down first, as access pattern: How a system reads and writes one kind of data: by which key, how often, in what shape and how fresh it must be. Access patterns, not product names, decide where data is stored. More in “Turning a vague prompt into requirements”, and then match them to the eight models a system designer meets most: relational, document, wide-column, key-value, graph, time-series, search and vector. One small dataset is then kept in three of the shapes, with the output recorded, so you can see the trade rather than take it on trust.

Start from the access patterns

An access pattern is one way the system touches its data: who reads or writes what, by which key or filter, how often, how fresh the answer must be, and which changes must happen together or not at all. Write them down before naming any database. The requirements lesson turns a prompt into features and quality goals; the access patterns are those features restated as reads and writes.

Here is an inventory for a food-delivery app serving one large city. The rates are assumptions for the example, the kind you would estimate in the round, not measurements:

  1. Show a restaurant’s menu: by restaurant id, 4,000 reads a second at the peak; a minute old is fine.
  2. Place an order and take payment: by customer and order id, 120 writes a second; exact, and the order, its lines and the payment must change together.
  3. Track an order on screen: by order id, 3,000 reads a second; a few seconds old is fine.
  4. Record rider locations: by rider id and time, 25,000 points a second; read back within seconds.
  5. Search dishes by name: by the words typed, 600 queries a second; minutes behind is fine.
  6. Suggest similar dishes: by the dish’s meaning, 300 queries a second; hours behind is fine.
  7. Revenue per restaurant per month: by restaurant and month, a few queries a day; a day behind is fine.

Each pattern already leans towards a shape. Placing an order changes several records that must stay consistent, which is what relational transactions are for. The tracking screen reads one order with everything it shows, which suits a document. Rider locations arrive as a firehose of timestamped points, read back as recent ranges. Search ranks text, suggestions compare meaning, and monthly revenue scans history. Seven patterns, several shapes: that is normal, and the last section of this lesson deals with its cost.

The step-through below turns patterns 2 and 4 into the fields of an access pattern, one question at a time. Watch the last two fields: they are where the two patterns part ways.

Interactive · stage by stage From a feature to an access pattern Step through the questions that turn a feature into an access pattern, first for placing an order, then for recording rider locations.
From a feature to an access pattern, step 8 of 8. Showing The feature (record rider locations), What is read or written (timestamped points), By which key or filter (rider id and time), How often (25,000 points a second), How fresh (within seconds), What changes together (nothing, each point alone), The shape it leans to (time-series, read by range). In focus: The shape it leans to.The featurerecord rider locationsWhat is read or writtentimestamped pointsBy which key or filterrider id and timeHow often25,000 points a secondHow freshwithin secondsWhat changes togethernothing, each point aloneThe shape it leans totime-series, read by range

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. Place an order. Start from the feature, written as something a user does. Placing an order and paying for it is pattern 2 of the inventory.
  2. Records and key. It writes an order, its lines and a payment, found by the customer and the order id.
  3. Rate and freshness. About 120 writes a second at the peak, and the answer must be exact, never a little old.
  4. What changes together. The order, its lines and the payment must change together or not at all, so a crash halfway through must leave none of them written.
  5. The shape. Several records that change together under rules the store enforces lean towards relational tables with a transaction around them.
  6. Record rider locations. Now pattern 4. Each rider's app sends timestamped points, found by rider id and time, 25,000 a second, and read back within seconds.
  7. Nothing changes together. Each point stands alone, so no two writes must change together, and the points are read back as recent ranges of time.
  8. A different shape. A firehose of timestamped points read as ranges leans towards a time-series store. Two features of one app, two shapes, which is why the inventory comes before the database.

Two features of one app ended on two shapes, and no database product was named on the way.

Checkpoint

Check: Writing the access patterns first

  1. Question 1 of 2 A teammate writes one pattern as "Show order history: 500 reads a second". What must be added before it can point at a data model?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: By which key or filter it is read, and how fresh the answer must be

    An access pattern names what is read or written, by which key or filter, how often, how fresh, and what must change together. The rate is one field of several; for this read, the key and the freshness are the ones that point at a shape.

  2. Question 2 of 2 In the step-through, placing an order leans to relational tables and recording rider locations leans to a time-series store. Which answers made the difference?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The order's records must change together; each location point stands alone and is read back by range

    The rates and the freshness differ too, but the last two fields decide: what must change together, and how the data is read back.

Eight models, and what each makes cheap

The diagram pairs each model with the pattern it serves best; the sections after it take the eight one at a time.

Eight access patterns, each with an arrow to the data model that serves it best, from relational to vector.Join entities, enforce rules,change several rows atomicallyRelationalRead one aggregate whole by its idDocumentHuge write volume, read bypartition key in sorted orderWide-columnGet or set one value by its keyKey-valueFollow relationships several hopsGraphAppend measurements,read time rangesTime-seriesRank text by relevance to wordsSearch (inverted index)Find the items nearest in meaningVector (nearest neighbours)

From the access pattern to the data model

Text description of the diagram

The diagram lists eight pairs from top to bottom: each access pattern, with an arrow down to the data model that serves it best.

  1. Join entities, enforce rules and change several rows atomically: relational.
  2. Read one aggregate whole by its id: document.
  3. A huge write volume, read by partition key in sorted order: wide-column.
  4. Get or set one value by its key: key-value.
  5. Follow relationships several hops deep: graph.
  6. Append measurements and read time ranges: time-series.
  7. Rank text by relevance to a few words: search, with an inverted index.
  8. Find the items nearest in meaning: vector, with a nearest-neighbour index.

Relational: tables, joins and constraints

The relational model keeps each fact once, in a row of a table, and joins tables when a question spans them. Its strength is everything around the data: transaction: A group of reads and writes that a database applies as one unit: all of its changes take effect or none do, and other transactions see it only as far as the isolation level allows. More in “Transactions, isolation levels and anomalies” that change several rows atomically, and constraints such as unique keys, foreign keys and checks that the database enforces on every write (PostgreSQL constraints). Ad hoc questions are easy, because SQL can join and group in ways nobody planned. The price shows at scale: joins across very large tables and writes beyond one machine need care, which the partitioning module covers.

Document: the aggregate you read together

A document store keeps one nested record, such as an order with its lines, under one key. MongoDB’s manual states the principle well: data that is accessed together should be stored together, and embedding related data avoids joins (MongoDB data modeling). Fields may differ from one document to the next, which suits catalogues whose attributes vary by category. Two limits follow from the shape: a fact copied into many documents must be updated in all of them, and a document cannot grow without bound (MongoDB caps one at 16 mebibytes, limits).

Wide-column: partitions built for heavy writes

A wide-column store such as Apache Cassandra groups rows into partitions by a partition key: The field of a request or a record, such as a tenant id or a user id, that decides which partition, shard or cell owns it. More in “Cells, deployment stamps and blast radius”, spreads the partitions across machines, and keeps rows sorted inside each partition by The columns of a Cassandra primary key that come after the partition key. They set the order in which rows are kept inside each partition.. Cassandra’s documentation calls its data modelling query-driven: there are no joins, so each query gets a table shaped for it and data is duplicated across tables on purpose (Cassandra data modeling). In return, a well-chosen partition key spreads data and load evenly across the cluster and keeps lookups by key fast as it grows. A question nobody designed a table for is expensive, or impossible without scanning everything.

Checkpoint

Check: What each of the eight models makes cheap

  1. Question 1 of 2 Why is a customer document that holds every order the customer has ever placed a poor design?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The list grows without limit, and one document has a size cap (16 mebibytes in MongoDB)

    Data that is read together is stored together, but only while the aggregate stays bounded. Every order of a customer is a list without an end, so the document keeps growing towards the store's cap, and the orders belong in records of their own.

  2. Question 2 of 2 A Cassandra table holds trips partitioned by rider id and sorted by time inside each partition. Product now asks for every trip that started in one area yesterday. What does it take?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: A new table shaped for that question, or a scan of everything

    A wide-column store answers fast the questions its tables were shaped for. For a new question you add a table that duplicates the trips by area and day, or you pay for a scan of everything.

Key-value: one key, one value

A key-value store answers one question: the value stored under this key. It is the simplest shape, and the usual home for sessions, carts, feature flags and caches. Redis describes itself as a data structure server whose most basic type is the string, a sequence of bytes under a key, and adds hashes, lists, sets and sorted sets for richer values (Redis data types). Anything that is not a lookup by key, such as “all carts older than a day”, needs a structure you build yourself.

Graph: relationships as data

A graph database stores nodes and the relationships between them, each with properties, and answers questions by walking from node to node (Neo4j). “Accounts that share a device or a phone number with this one, up to three steps away” is a short traversal in a graph and a pile of self-joins in tables. The trade runs the other way for big aggregates, such as revenue across every order, which a graph computes by visiting nodes one at a time.

Time-series: append, then read ranges

A time-series store is built for measurements that arrive in time order and are read back as ranges and summaries: metrics, sensor readings, locations. Prometheus, for example, groups incoming samples into two-hour blocks, protects recent data with a write-ahead log (WAL): An append-only file of changes that a database flushes to disk before a change counts as committed, so that after a crash it can redo whatever the data files missed. More in “Storage engines: B-trees vs LSM-trees”, and compacts old blocks into larger ones in the background (Prometheus storage). Old data leaves by age: Prometheus keeps samples for 15 days unless configured otherwise. Updating an arbitrary old point, or joining it with business records, is not what these stores are for.

Checkpoint

Check: What each of the eight models makes cheap

  1. Question 1 of 2 Carts live in a key-value store under each customer's id. Support asks for all carts older than a day. What does the store give you?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Nothing ready-made, so you build and keep up a structure for that question yourself

    Lookups by key are what key-value stores are for. "All carts older than a day" is not a lookup by key, so it needs a structure of its own, such as a sorted set ordered by time, that every write keeps up to date.

  2. Question 2 of 2 A metrics store keeps 15 days of samples. A team wants to correct one reading from 10 days ago and join every reading with the customer table. What does the lesson say about that?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Neither is what a time-series store is for, because it appends, reads ranges and drops data by age

    A time-series store is built for points that arrive in time order and are read back as ranges and summaries, then dropped by age. Corrections to old points and joins with business records belong to stores built for them.

Search: an inverted index ranks text

A search engine keeps an inverted index: for every word, the list of documents that contain it, so a query for a few words finds and ranks matches without reading every document. PostgreSQL’s GIN index is one such structure (GIN stands for Generalized Inverted Index), and its documentation names the cost: one inserted row can mean many index entries, one per extracted word (GIN indexes). Dedicated search engines build relevance scoring, word forms and typo tolerance on the same idea.

Vector: nearest neighbours by meaning

A vector index stores embeddings, lists of numbers that a model computes so that similar meanings land close together, and finds the stored vectors nearest to a query vector. pgvector adds this to PostgreSQL with exact search and two approximate index types; its documentation says an HNSW index gives a better speed-recall trade-off than IVFFlat but builds more slowly and uses more memory (pgvector). Approximate means a fast answer may miss a true neighbour, so The share of the true nearest neighbours that an approximate search returns. A recall of 0.9 means it finds 9 of every 10. becomes a quality goal you measure.

The table puts the eight side by side:

Model Cheap Expensive
Relational Joins, constraints, atomic changes to several rows Joins of huge tables, writes beyond one machine
Document One aggregate read whole by its key A fact copied into many documents
Wide-column Heavy writes and lookups by partition key A question no table was shaped for
Key-value The value under one key Anything that is not a lookup by key
Graph Relationships followed several hops deep Big aggregates, computed node by node
Time-series Appends, read back as ranges of time Updating old points, joins with business data
Search Ranking text by the words typed Many index entries per row written
Vector Nearest neighbours by meaning Exactness: a fast search may miss a neighbour

Rule of thumb

Name the question each pattern asks most: by key, one aggregate by its id, a range of time, the words typed, what is nearest in meaning, or the links between records. Then pick the model whose Cheap cell names it.

The same data in three shapes

The script below keeps seven orders from three restaurants three ways: as relational rows in SQLite, as one document per order, and as a graph in which customers and restaurants are nodes and orders are edges. Each shape then answers the question it is best at:

One dataset as rows, documents and a graph Python · models_demo.py
# One small food-delivery dataset kept three ways: relational rows (SQLite), order documents and a graph of who
# ordered where. Each shape answers one question cheaply and makes another one expensive.
import json
import sqlite3
from collections import deque

RESTAURANTS = [(1, "Dosa Corner"), (2, "Biryani House"), (3, "Green Bowl")]
DISHES = [(11, 1, "Masala dosa", 120), (12, 1, "Filter coffee", 40), (21, 2, "Veg biryani", 220),
          (22, 2, "Raita", 50), (31, 3, "Quinoa salad", 260)]
ORDERS = [(1001, "asha", 1), (1002, "ravi", 2), (1003, "asha", 2), (1004, "meera", 3),
          (1005, "ravi", 1), (1006, "kabir", 3), (1007, "meera", 2)]
ITEMS = [(1001, 11, 2), (1001, 12, 2), (1002, 21, 1), (1002, 22, 1), (1003, 21, 2), (1004, 31, 1),
         (1005, 11, 1), (1006, 31, 2), (1007, 21, 1), (1007, 22, 2)]

# 1. Relational: one fact in one place, joined at read time.
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE restaurants (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE dishes (id INTEGER PRIMARY KEY, restaurant_id INTEGER NOT NULL REFERENCES restaurants(id),
                     name TEXT NOT NULL, price INTEGER NOT NULL);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL,
                     restaurant_id INTEGER NOT NULL REFERENCES restaurants(id));
CREATE TABLE order_items (order_id INTEGER NOT NULL REFERENCES orders(id),
                          dish_id INTEGER NOT NULL REFERENCES dishes(id), qty INTEGER NOT NULL,
                          PRIMARY KEY (order_id, dish_id));
""")
db.executemany("INSERT INTO restaurants VALUES (?, ?)", RESTAURANTS)
db.executemany("INSERT INTO dishes VALUES (?, ?, ?, ?)", DISHES)
db.executemany("INSERT INTO orders VALUES (?, ?, ?)", ORDERS)
db.executemany("INSERT INTO order_items VALUES (?, ?, ?)", ITEMS)

print("Relational rows: revenue per restaurant, one query joining four tables")
for name, revenue in db.execute("""
    SELECT r.name, SUM(i.qty * d.price) AS revenue
    FROM restaurants r JOIN orders o ON o.restaurant_id = r.id
    JOIN order_items i ON i.order_id = o.id JOIN dishes d ON d.id = i.dish_id
    GROUP BY r.id ORDER BY revenue DESC"""):
    print(f"  {name:<14}{revenue:>6}")

# 2. Documents: everything one screen shows, stored together and read by one key.
dish = {d[0]: d for d in DISHES}
name_of = dict(RESTAURANTS)
documents = {}
for order_id, customer, restaurant_id in ORDERS:
    lines = [{"dish": dish[d][2], "qty": q, "price": dish[d][3]} for o, d, q in ITEMS if o == order_id]
    documents[order_id] = {"order": order_id, "customer": customer,
                           "restaurant": {"id": restaurant_id, "name": name_of[restaurant_id]},
                           "items": lines, "total": sum(x["qty"] * x["price"] for x in lines)}

print("\nDocument: the order-tracking screen reads order 1007 with one lookup")
doc = documents[1007]
print("  {")
for key, value in doc.items():
    if isinstance(value, list):
        print(f'    "{key}": [')
        print(",\n".join("      " + json.dumps(v) for v in value))
        print("    ],")
    else:
        print(f'    "{key}": {json.dumps(value)}' + ("," if key != "total" else ""))
print("  }")
copies = sum(1 for doc in documents.values() if doc["restaurant"]["id"] == 2)
print(f"  Renaming restaurant 2 rewrites {copies} documents; the relational schema updates 1 row.")

# 3. Graph: customers and restaurants as nodes, orders as edges, walked hop by hop.
edges = {}
for _, customer, restaurant_id in ORDERS:
    edges.setdefault(("customer", customer), set()).add(("restaurant", restaurant_id))
    edges.setdefault(("restaurant", restaurant_id), set()).add(("customer", customer))


def within_two_hops(start):
    """Nodes two hops from start (customer -> restaurant -> customer), and the edges followed."""
    seen, frontier, followed = {start: 0}, deque([start]), 0
    while frontier:
        node = frontier.popleft()
        if seen[node] == 2:
            continue
        for nxt in sorted(edges[node], key=str):
            followed += 1
            if nxt not in seen:
                seen[nxt] = seen[node] + 1
                frontier.append(nxt)
    return sorted(n[1] for n, hops in seen.items() if hops == 2), followed


people, followed = within_two_hops(("customer", "asha"))
print("\nGraph: who ordered from the same restaurants as asha")
print(f"  {', '.join(people)} (found by following {followed} edges)")

Output

Relational rows: revenue per restaurant, one query joining four tables
  Biryani House   1030
  Green Bowl       780
  Dosa Corner      440

Document: the order-tracking screen reads order 1007 with one lookup
  {
    "order": 1007,
    "customer": "meera",
    "restaurant": {"id": 2, "name": "Biryani House"},
    "items": [
      {"dish": "Veg biryani", "qty": 1, "price": 220},
      {"dish": "Raita", "qty": 2, "price": 50}
    ],
    "total": 320
  }
  Renaming restaurant 2 rewrites 3 documents; the relational schema updates 1 row.

Graph: who ordered from the same restaurants as asha
  meera, ravi (found by following 7 edges)

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 models_demo.py

Read the output as three trade-offs. Revenue per restaurant is one SQL statement over four tables, because the rows can be joined and grouped any way the question asks. The tracking screen gets everything it shows from one document, but that document copied the restaurant’s name: renaming the restaurant rewrites three documents where the relational schema changes one row, and a missed copy leaves two names in circulation. The graph finds the customers who share a restaurant with asha by following seven edges; in tables the same question is a self-join of orders on restaurant, which grows heavier with every extra hop.

Start the walk somewhere else

In the line that calls within_two_hops, change the start from asha to kabir and run the script again. The customer kabir ordered only from Green Bowl, so the walk follows 3 edges instead of 7 and finds meera alone: its work follows the neighbourhood it visits, not the size of the data.

SQLite Online (SQL Playground) Paste the four CREATE TABLE statements and try your own joins on the same rows.

Checkpoint

Check: One dataset in three shapes

  1. Question 1 of 2 In the recorded run, renaming Biryani House rewrites 3 order documents. If kabir places 2 more orders from Biryani House, how many documents would the same rename rewrite?

    Type a number.

    A hint

    Every order document of the restaurant holds its own copy of the name.

    Show the answer: Question 1 of 2

    Answer: 5 documents

    The 3 documents of the run and the 2 new ones each copy the name, so the rename rewrites 5 documents, while the relational schema still changes 1 row. The cost of a copied fact grows with the number of documents that hold it.

  2. Question 2 of 2 In tables, the customers who share a restaurant with asha come from a self-join of orders on restaurant. Why does the question get heavier in tables with every extra hop?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Each hop adds another self-join of the orders, while the graph walk follows only the edges of the nodes it reaches

    Every hop in tables is one more join over the orders, whatever the size of the neighbourhood. The walk's work follows the edges it visits, 7 from asha and 3 from kabir.

One system, several stores

Real systems rarely fit one shape, so most use several stores. Martin Fowler’s note on polyglot persistence: Running several storage technologies in one system, each for the data and access patterns it suits, such as a relational database for orders beside a search engine for text. expects any sizeable organisation to run several storage technologies, each for the kind of data it suits (Fowler). The food-delivery app could reasonably keep orders in PostgreSQL, sessions in a key-value store, rider locations in a time-series store and dish search in a search engine.

Every extra store has a price, and the price is paid in correctness more than in money:

  • A second copy to keep in step. The search index and the suggestions are copies of data whose source of truth: The one store whose copy of a fact is authoritative. Every other store that holds the fact copies it from there and can be rebuilt from it. is elsewhere. Writing to two stores from application code can leave them disagreeing after a crash between the two writes; the module on distributed transactions covers the safe ways to feed a copy.
  • A delay readers can see. A copy fed asynchronously is behind its source, so a dish renamed a second ago may still show its old name in search.
  • Another system to run. Backups, upgrades, monitoring, access control and on-call knowledge, for every store.

Step through a dish rename to watch the first two costs happen, and to see what one source of truth gives you when they do:

Interactive · step by step A dish renamed, and the copy that follows it Step through a dish rename in the orders database, the search index that copies it, and what readers see on the way.
A dish renamed, and the copy that follows it, step 6 of 6. Showing The app, Orders database (newer name), Search index (newer name, rebuilt), A reader. In focus: Orders database, Search index.renamechange feedsearchThe apprenames a dishOrders databasenewer nameSearch indexnewer name, rebuiltA readersearches dishesrebuild

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. One source of truth. The dish's name lives in one place, the orders database. The search index is a copy of it, kept for queries by the words typed.
  2. The rename. The app renames the dish. The orders database has the new name at once.
  3. A delay readers can see. The copy is fed asynchronously, so for a moment the index still holds the old name, and a reader who searches sees it.
  4. The copy catches up. The change arrives through the feed, and the index takes the new name. Copies fed this way lag, then agree.
  5. Two writes from the app. Now take the next rename, in a design with no feed, where the app writes to both stores itself. It writes the database, then crashes before the second write. The database has the newer name, the index keeps the one before, and nothing brings the two back in step on its own.
  6. Rebuild from the source. Because the name has one source of truth, the index can be rebuilt from the database at any time, and a feed keeps it in step from then on. A copy you can rebuild is a copy you can repair.

Two rules keep this manageable. Give every fact exactly one source of truth, and make every other store a derived copy: Data kept in a second store, such as a search index, that is computed from a source of truth. It can lag behind its source, and it can always be rebuilt from it. you could rebuild from it. And before adding a store, check what the one you have can do: PostgreSQL’s jsonb type stores documents in a binary format that supports indexing (JSON types), its GIN indexes support text search, and the pgvector extension adds vector search. One store that covers four patterns adequately is often a better starting point than four stores that each cover one perfectly.

Common mistakes

Picking a database before writing the access patterns. Treating “NoSQL” as one kind of store, when key-value, document, wide-column and graph stores differ from each other as much as each differs from a relational database. Believing a schemaless store has no schema: the schema moves into application code and must still evolve. Embedding a list that grows without limit, such as every order of a customer inside the customer’s document.

Checkpoint

Check: Several stores and the cost of each copy

  1. Question 1 of 2 The app writes a dish's new name to PostgreSQL and then to the search index itself, and it crashes between the two writes. What is left?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: PostgreSQL has the new name and the index the old one, until something rebuilds or rewrites the index

    Writing two stores from application code leaves a gap between the writes, and a crash in the gap leaves them disagreeing. A rebuild from the source of truth repairs the index; a feed from the source keeps it in step.

  2. Question 2 of 2 Which patterns of the food-delivery inventory could be served from a copy that is fed asynchronously and lags its source a little?

    Choose every answer that is right.

    Show the answer: Question 2 of 2

    Answer:

    • Suggest similar dishes
    • Search dishes by name
    • Revenue per restaurant per month

    The freshness field of each pattern says how far a copy may lag. Search, suggestions and revenue allow minutes to a day; placing an order allows none, so it writes to the source of truth.

Practise on an order document

Build the tracking screen’s order document in Python, and run the sample tests: the lines and the restaurant copied in, the total worked out from the lines, a refusal to copy another restaurant’s facts, and a rename that counts every document it changed.

Exercise · Easy · Python

Build the order document a screen reads, and pay for its copies

The order-tracking screen reads one order at a time, with its lines, the restaurant's name and the total. Write two functions in order_doc.py that keep that screen to a single lookup and handle the cost of the copy it needs.

to_document(order, items, restaurant) returns the document for one order. order is a dict such as {"id": 1007, "customer": "meera", "restaurant_id": 2}, items is a list of dicts such as {"dish": "Raita", "qty": 2, "price": 50}, and restaurant is a dict such as {"id": 2, "name": "Biryani House"}. The result has the keys order, customer, restaurant (a dict with the restaurant's id and name), items (new dicts with the same three keys, in the same order) and total (the sum of quantity times price). If the restaurant is not the order's restaurant, raise ValueError: a document must never copy the wrong facts.

rename_restaurant(documents, restaurant_id, new_name) takes a list of such documents, changes the copied name in every document of that restaurant, and returns how many documents it changed. That count is the price of the copy: the relational schema would have changed one row.

Starter code · order_doc.py

def to_document(order, items, restaurant):
    """The document the order-tracking screen reads with one lookup."""
    # Replace this line with your code.
    return {}


def rename_restaurant(documents, restaurant_id, new_name):
    """Change the copied restaurant name everywhere; return how many documents changed."""
    # Replace this line with your code.
    return 0
The sample tests · test_order_doc.py
import copy

from order_doc import rename_restaurant, to_document

ORDER = {"id": 1007, "customer": "meera", "restaurant_id": 2}
ITEMS = [{"dish": "Veg biryani", "qty": 1, "price": 220}, {"dish": "Raita", "qty": 2, "price": 50}]
BIRYANI = {"id": 2, "name": "Biryani House"}


def test_document_shape():
    """embeds the lines and the restaurant, and adds the total"""
    assert to_document(ORDER, ITEMS, BIRYANI) == {
        "order": 1007,
        "customer": "meera",
        "restaurant": {"id": 2, "name": "Biryani House"},
        "items": [{"dish": "Veg biryani", "qty": 1, "price": 220}, {"dish": "Raita", "qty": 2, "price": 50}],
        "total": 320,
    }


def test_no_items():
    """an order without lines totals 0"""
    doc = to_document({"id": 5, "customer": "kabir", "restaurant_id": 3}, [], {"id": 3, "name": "Green Bowl"})
    assert doc["items"] == [] and doc["total"] == 0


def test_lines_are_copies():
    """the document keeps its own copy of each line"""
    items = copy.deepcopy(ITEMS)
    doc = to_document(ORDER, items, BIRYANI)
    items[0]["qty"] = 9
    assert doc["items"][0]["qty"] == 1


def test_wrong_restaurant():
    """refuses to copy another restaurant's facts"""
    try:
        to_document(ORDER, ITEMS, {"id": 3, "name": "Green Bowl"})
    except ValueError:
        return
    assert False, "expected ValueError"


def test_rename_counts_copies():
    """renames every copy of one restaurant and counts them"""
    docs = [to_document({"id": i, "customer": "c", "restaurant_id": r}, [], {"id": r, "name": f"R{r}"}) for i, r in [(1, 2), (2, 1), (3, 2)]]
    assert rename_restaurant(docs, 2, "Biryani Mahal") == 2
    assert [d["restaurant"]["name"] for d in docs] == ["Biryani Mahal", "R1", "Biryani Mahal"]
A hint

Build items with a list comprehension that makes a new dict for each line, and compute the total with sum() over the same lines. In rename_restaurant, loop over the documents, compare doc["restaurant"]["id"] with the id you were given, and count the ones you change.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then check yourself, one question at a time, weakest idea first:

Practice that adapts to you

Practise this lesson

14 questions about 4 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 14 A wallet moves money between two accounts. Both balances must change together or not at all, and no balance may go below zero. Which model fits the primary store?

    Choose one answer.

    Show the answer: Question 1 of 14

    Answer: Relational, with a transaction around both updates and a check constraint on the balance

    Changing two rows atomically and enforcing a rule on every write are exactly what relational transactions and constraints do. A key-value store can hold the balances, but it gives you neither the atomic two-row change nor the rule.

  2. Question 2 of 14 A product page always shows a product with its variants, images and specifications, read together by product id, and the specification fields differ by category. Which model fits?

    Choose one answer.

    Show the answer: Question 2 of 14

    Answer: Document, one document per product

    The page reads one aggregate whole by its id, and its fields vary from one category to another: data that is accessed together, stored together, with a flexible shape.

  3. Question 3 of 14 A ride app records every driver's position every 4 seconds. The reads are "the last 10 minutes of one driver" and "average speed per area per hour", and data older than 30 days is deleted. Which model fits?

    Choose one answer.

    Show the answer: Question 3 of 14

    Answer: Time-series

    Timestamped points arrive in order, are read back as ranges and summaries, and leave by age: the time-series pattern. One growing document per driver would hit a size limit and rewrite the same record constantly.

  4. Question 4 of 14 A fraud team asks which accounts share a device, a phone number or a card with a given account, up to three steps away. Which model answers this most directly?

    Choose one answer.

    Show the answer: Question 4 of 14

    Answer: Graph

    Following relationships several hops deep is a traversal in a graph. In tables it becomes a chain of self-joins that grows with every hop.

  5. Question 5 of 14 A help bot must find the 5 past answers closest in meaning to a new question, even when they share no words with it. Which model fits?

    Choose one answer.

    Show the answer: Question 5 of 14

    Answer: Vector, with a nearest-neighbour index over embeddings

    An inverted index finds documents that share words with the query. Answers that mean the same thing in other words are found by comparing embeddings, which is what a vector index does.

  6. Question 6 of 14 A help desk needs two lookups, tickets that contain the word refund, and tickets that mean the same as a new one even when they share no words. Which pair serves them?

    Choose one answer.

    Show the answer: Question 6 of 14

    Answer: An inverted index for the words, and a vector index over embeddings for the meaning

    Words and meaning are two access patterns. Search ranks by the words typed with an inverted index, and vector search compares embeddings. PostgreSQL can hold both, with GIN indexes for text search and the pgvector extension for vectors.

  7. Question 7 of 14 Which of these is an access pattern, written the way the lesson asks?

    Choose one answer.

    Show the answer: Question 7 of 14

    Answer: Track an order by order id, 3,000 reads a second, a few seconds old is fine

    An access pattern says who reads or writes what, by which key or filter, how often, how fresh, and what must change together. Products and schemas come after the patterns.

  8. Question 8 of 14 An interviewer says only "design the data layer of a food-delivery app". What is the strongest first move?

    Choose one answer.

    Show the answer: Question 8 of 14

    Answer: List the access patterns, each with its key, rate, freshness and what changes together, then choose stores from that list

    The seven patterns of one food-delivery app pointed at several shapes. Writing them down first makes every later choice checkable.

  9. Question 9 of 14 In the script's output, which shape answered which question with the least work?

    Choose one answer.

    Show the answer: Question 9 of 14

    Answer: Rows gave revenue per restaurant in one statement, a document gave order 1007 in one lookup, and the graph found asha's neighbours by following 7 edges

    Revenue per restaurant was one SQL statement over four tables, order 1007 came from one document, and the walk from asha followed 7 edges.

  10. Question 10 of 14 A rename of Biryani House reaches 2 of its 3 order documents. What does the tracking screen of the third order show?

    Choose one answer.

    Show the answer: Question 10 of 14

    Answer: The old name, so two names are in circulation

    That is the price of a copy. The rename must reach every document that holds the name, and a missed copy leaves two names in circulation, where the relational schema changes one row.

  11. Question 11 of 14 A new screen shows, for one customer, everyone who ordered from the same restaurants, then the restaurants those people ordered from, then the customers of those restaurants. Which shape keeps this cheap as the hops grow?

    Choose one answer.

    Show the answer: Question 11 of 14

    Answer: The graph, walking from node to node

    Multi-hop questions are what graphs make cheap. The script's walk did the work of the neighbourhood it reached, 7 edges from asha and 3 from kabir, where tables add a join for every hop.

  12. Question 12 of 14 You add a search engine next to the orders database and feed it from the application. Which of these are real costs?

    Choose every answer that is right.

    Show the answer: Question 12 of 14

    Answer:

    • Search results can lag behind the latest change
    • A crash between the two writes can leave the stores disagreeing
    • Another system to back up, monitor and secure

    The orders database keeps its transactions. What the second store adds is a copy to keep in step, a delay readers can see, and the work of running one more system.

  13. Question 13 of 14 After a crash, the search index holds old names for some dishes. Because every fact has one source of truth, what can you do?

    Choose one answer.

    Show the answer: Question 13 of 14

    Answer: Rebuild the index from the orders database

    The rule "one source of truth, every other store a derived copy" is what makes a broken copy cheap: you throw it away and rebuild it from the source.

  14. Question 14 of 14 The team wants a document store just for restaurant menus, read 4,000 times a second, while orders stay in PostgreSQL. What should be checked first?

    Choose one answer.

    Show the answer: Question 14 of 14

    Answer: Whether PostgreSQL can serve the menus, for example as indexed jsonb documents, before adding a store with its own copy, delay and operations

    Before adding a store, check what the one you have can do, such as jsonb for documents, GIN indexes for text search and pgvector for vectors. A second store is worth its copy, delay and operations only when the first cannot serve the pattern well.

Interview questions

Warm-up (fresher to mid level): what is an access pattern, and why does it come before choosing a database? An access pattern is one way the system reads or writes data: what is read or written, by which key or filter, how often, how fresh it must be, and what must change together. It comes first because every data model makes some patterns cheap and others expensive: a document store reads an aggregate by id in one lookup but makes cross-document reports costly, while a relational database joins anything but needs care to scale writes. Choosing a store before listing the patterns means choosing the costs before knowing the workload.

Warm-up (fresher to mid level): why do many systems use more than one data store, and what does it cost? Because their access patterns differ: transactions, text search, time ranges and similarity search each have a shape that serves them best. The cost is that every extra store holds a copy that must be kept in step with its source of truth, lags behind it when fed asynchronously, and must be backed up, secured and operated. A good design names one source of truth per fact and treats every other store as a derived copy it can rebuild.

A data-model question in a design round names a product and its features, never a database. Make the first call on the two briefs below, then try the two questions after them:

Checkpoint

Your first decision

  1. Question 1 of 2 Design brief: the data layer of a ride app for one country, with trips, fares, payments and every online driver's position every 4 seconds. Which first decision would you defend?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Write the access patterns with their rates, keys and freshness, and keep trips, fares and payments, which change together, in a store with transactions

    Start from the patterns. The positions are many independent timestamped points; trips and payments are fewer records that must change together under rules. The first decision separates them by what each needs, before any product is named.

  2. Question 2 of 2 Design brief: dishes live in PostgreSQL, and product wants search by the words typed, with typo tolerance; minutes behind is fine. Which first decision would you defend?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Feed a search engine from PostgreSQL as a derived copy that can be rebuilt, and keep PostgreSQL the source of truth for dishes

    One source of truth and one derived copy. PostgreSQL keeps the dishes and their rules, and the search engine keeps a copy shaped for the words typed, fed from the source and rebuildable from it.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    You are designing the data layer of a ride-hailing app for one country: riders, drivers, trips, fares and payments, driver locations every 4 seconds and a "drivers near me" search. Which stores hold which data, and why?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Senior to staff

    A product began with one document per customer holding all of that customer's orders. Two years later finance wants monthly revenue per city and support wants to search orders by item. What went wrong, and how do you move on without downtime?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Write the access patterns first: what is read or written, by which key, how often, how fresh, and what must change together.
  • Relational suits joins, constraints and transactions; document suits aggregates read whole; wide-column suits huge write volumes read by partition; key-value suits lookups by key.
  • Graph suits multi-hop relationships; time-series suits appends read as ranges; search ranks text with an inverted index; vector finds nearest neighbours by meaning.
  • The same orders kept as rows, documents and a graph show the trade: rows answer new questions with joins, a document serves one screen in one lookup but copies its facts, and a graph walk pays for the links it follows.
  • Most systems use several stores. Give each fact one source of truth, treat every other store as a rebuildable copy, and check what your main database already covers before adding one.

Terms in this lesson

data model
The shape a store gives data: rows in tables, nested documents, values under keys, nodes and edges, timestamped points or vectors. Each shape makes some questions cheap to answer and others expensive.
derived copy
Data kept in a second store, such as a search index, that is computed from a source of truth. It can lag behind its source, and it can always be rebuilt from it.
polyglot persistence
Running several storage technologies in one system, each for the data and access patterns it suits, such as a relational database for orders beside a search engine for text.
source of truth
The one store whose copy of a fact is authoritative. Every other store that holds the fact copies it from there and can be rebuilt from it.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.