Data modelling across paradigms
Which facts an order copies and freezes, which it references, why a history screen made 141 queries, and what the same data looks like in a key-value store.
A customer opens an order from last month to claim a refund for a missing dish. The screen says “Paneer tikka × 2, ₹480”. Since then the restaurant has raised the price to ₹280. If the order only points at the menu item and looks its price up when displayed, the screen now says ₹560, the refund is computed on a price she never paid, and the tax invoice no longer matches the payment. Nothing was written to the order, and its history changed anyway.
Data modelling decides which facts are stored where, which are copied and frozen, and which are referenced and allowed to change. This chapter models Dabba’s restaurants, menus and orders in a relational database, works through a slow screen caused by the model, and then models the same data for a key-value store to see what that gains and what it costs.
Write the queries before the tables
A model is good or bad relative to the questions asked of it. So the first step is to list them, with the rate at which each is asked and how correct the answer must be.
| Question | Asked by | Rate at peak | Needs |
|---|---|---|---|
| The full menu of restaurant R | menu cache rebuilds | ~40 a second | consistent within one menu |
| Place an order | customers | ~150 a second | atomic; correct prices and stock |
| Order O with items and status | tracking screen, support | thousands a second, mostly cached | the customer’s own writes visible |
| Customer C’s recent orders | order history screen | tens a second | stable paging |
| Restaurant R’s active orders | kitchen tablets polling every 10 s | ~2,000 a second (20,000 open restaurants) | fresh within seconds |
| Restaurant R’s statement for a day | nightly payout job | once per restaurant per day | exact to the paisa |
| Who ordered dish D from R last week? | support, food safety | rare, unplanned | complete |
The last row is the kind of question that decides between paradigms later in the chapter. Nobody plans for it. It arrives the day a restaurant reports a bad batch of chicken and Dabba must contact everyone who ate it.
Restaurants and menus: normalised, because they are edited
Menus have a structure that is easy to get wrong. A restaurant has categories (starters, biryanis, breads), and each category has items. Items have option groups, such as “Spice level”, choose exactly one, or “Add-ons”, choose up to three, and each group has options with their own prices. The same group is often shared: “Choice of bread” applies to every curry on the menu.
CREATE TABLE restaurants (
restaurant_id bigint PRIMARY KEY,
name text NOT NULL,
zone_id int NOT NULL,
menu_version int NOT NULL DEFAULT 1
);
CREATE TABLE menu_items (
item_id bigint PRIMARY KEY,
restaurant_id bigint NOT NULL REFERENCES restaurants,
category_id bigint NOT NULL,
name text NOT NULL,
price_paise int NOT NULL CHECK (price_paise >= 0),
photo_url text,
is_veg boolean NOT NULL
);
CREATE TABLE option_groups (
group_id bigint PRIMARY KEY,
restaurant_id bigint NOT NULL REFERENCES restaurants,
name text NOT NULL, -- 'Choice of bread'
min_choices int NOT NULL,
max_choices int NOT NULL
);
CREATE TABLE options (
option_id bigint PRIMARY KEY,
group_id bigint NOT NULL REFERENCES option_groups,
name text NOT NULL, -- 'Butter naan'
price_paise int NOT NULL
);
CREATE TABLE item_option_groups ( -- which groups apply to which items
item_id bigint REFERENCES menu_items,
group_id bigint REFERENCES option_groups,
PRIMARY KEY (item_id, group_id)
);Each fact lives in one row. When the restaurant changes the price of butter naan, one row changes and every curry that offers it is correct. If the naan price were copied into each curry’s row, an edit would have to find and update every copy, and a missed copy would show two prices for the same naan.
Normalisation usually raises a worry about reads: building a menu now joins five tables. For Dabba that cost is paid only on a cache miss, about 40 times a second. The cached menu document from the reads chapter is the denormalised form, built from these tables whenever the version changes. The tables stay shaped for correct edits; the cache is shaped for fast reads. Keeping the two roles apart is what lets each be simple.
Orders record what was agreed
An order is different in kind. It is a record of an agreement at a moment: these dishes, with these options, at these prices, to this address, for this total. Those facts must not change when the menu or the customer’s profile changes later. So the order copies them.
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
restaurant_id bigint NOT NULL,
restaurant_name text NOT NULL, -- as it was when ordered
delivery_address jsonb NOT NULL, -- full snapshot, not an address_id
status text NOT NULL,
items_paise int NOT NULL,
delivery_paise int NOT NULL,
packaging_paise int NOT NULL,
discount_paise int NOT NULL,
tax_paise int NOT NULL,
total_paise int NOT NULL,
business_date date NOT NULL,
created_at timestamptz NOT NULL
);
CREATE TABLE order_items (
order_id bigint REFERENCES orders,
line_no int,
item_id bigint NOT NULL, -- reference, for analytics
item_name text NOT NULL, -- copy, for display and invoices
unit_price_paise int NOT NULL, -- the price agreed
quantity int NOT NULL CHECK (quantity > 0),
options jsonb NOT NULL, -- [{name, price_paise}], as chosen
photo_url text,
PRIMARY KEY (order_id, line_no)
);These copies are a different kind of denormalisation from the one database courses warn about. A copy made to save a join, such as storing a restaurant’s current rating on every order row so the history screen need not look it up, is a cache inside the database: when the rating changes, every copy is wrong until something updates it. The agreed price is a separate fact that happens to equal the menu price at one moment. When the menu price changes, the agreed price is still right, so the copy never needs updating. Keeping item_id as well lets analytics connect the order back to the menu without letting the menu rewrite the order.
The photo URL is safe to copy for a reason from the CDN chapter: photo URLs are content-hashed, so the URL will always mean the same image. Had Dabba reused photo URLs when restaurants replaced images, the copied URL would show whatever image the restaurant uploaded later.
A customer edits her saved “Home” address while her order is out for delivery. Suppose orders stored only an address_id pointing at her saved addresses. What happens?
Show the worked answer
The rider app loads the address through the ID and now shows the new one. Depending on when it refreshes, the rider is redirected mid-trip to a place the customer never intended for this order, perhaps across town. If the rider was already there, the delivery record now claims the food went somewhere it did not, and a later dispute is judged against the wrong address.
The order should hold a snapshot of the address as it was when the order was placed. If the product wants customers to change the destination of a live order, that becomes an explicit operation with its own rules (perhaps allowed only before pickup, and only within the same delivery zone), recorded as an event on the order. It should not happen as a side effect of editing a profile.
Money, state and time in the order row
Three details in that table repay attention. The first is money. Every amount is an integer number of paise, and the order stores each component (items, delivery, packaging, discount, tax) as well as the total. Recomputing tax later from the items would use whatever tax rules apply on the day of recomputation, not the day of the order. Rules change; a stored invoice must not.
The second is state. The status column holds the current state, which is what the tablet and the tracking screen query. On its own, though, it forgets how the order got there: when the restaurant accepted, how long the food sat at the pass, which rider dropped the order before another took it. Support needs those facts to settle disputes, and operations needs them to measure kitchen and delivery times. So every change of state also appends a row to an order_events table: order ID, sequence number, old and new state, who made the change, and when. The current state is kept for fast queries; the events are kept for history. Writing both in the same transaction keeps them consistent, and the writes chapter uses the same idea to publish events to other services reliably.
The third is time. Timestamps are stored as timestamptz, an absolute instant, and converted to Indian Standard Time only for display. But restaurants need something else too: a business day. A restaurant that closes at 1 am wants orders from 12:30 am on its statement for the previous evening, not split across two days. Dabba computes business_date once, when the order is placed, using a cut-off of 4 am IST, and stores it. Computing it later in reports from the timestamp would work until someone changed the cut-off and quietly moved last year’s orders between statements.
The order history screen that made 141 queries
The model can be right and the code that reads it still wrong. Here is a version of the order history screen that an object-relational mapper makes easy to write. It loads the customer’s 20 most recent orders. For each order, it reads order.items, which the mapper loads lazily with one query per order. For each item it reads item.menuItem.name and item.menuItem.photo to display the dish, one query per item. And for each order it reads order.restaurant.name, one more query per order.
With five items per order on average, the screen issues 1 + 20 + 100 + 20 = 141 queries. On a developer’s laptop with two test orders it issues 7 and feels instant. In production, each query is a round trip of about a millisecond inside the region plus its execution time, and the queries run one after another, so the screen takes well over 150 ms of database time and holds a connection from the pool the whole time. At tens of history screens a second, that is thousands of queries a second for a screen that should cost two. Worse, the screen shows today’s menu names, prices and photos for old orders, which is the bug from the opening of this chapter.
This pattern is known as the N+1 query problem: one query for a list, then one query per element. The fix has two parts. The snapshot columns mean the screen no longer needs the menu or restaurant tables at all. And the items for all 20 orders are fetched in one query, WHERE order_id = ANY($1), and grouped in code. The screen now makes two queries. Most mappers can do this with an explicit “load these relations eagerly” option. The habit that prevents the problem is to count queries per request in tests and logs, so a change from 2 to 141 is noticed in review rather than at peak.
The same data in a key-value store
A key-value or document store such as DynamoDB or Cassandra reads data by key, very quickly and at very large scale, and does not join. Modelling for it runs in the opposite direction from relational modelling. Instead of storing facts once and combining them at query time, we decide the questions first and arrange the data so each question is a single read of one key or one range of keys.
For Dabba’s orders in a DynamoDB-style table with a partition key and a sort key, that might look like this. The order, its items and its events share the partition key ORDER#9001, with sort keys META, ITEM#1, ITEM#2, EVENT#0001, so one read returns the whole order. A copy of each order’s summary is written under CUST#77 with sort key ORDER#2026-10-16T20:31:05#9001, so a customer’s recent orders are one range read in time order. For the tablet, active orders carry an extra attribute REST#48213#ACTIVE that a secondary index is built on; the attribute is removed on delivery, so the index holds only active orders.
Notice what this model asks of the application. The customer’s summary copy under CUST#77 is a second write for every order and every status change, and the application is responsible for making the copies agree. If the order write succeeds and the summary write fails, the order exists but is missing from the customer’s history. Stores of this kind offer transactions with limits (DynamoDB’s cover a bounded number of items, at extra cost per write), or the copy is made asynchronously from a change stream, in which case the history screen may lag the order by a second or two. In Postgres the history query reads the one order row through an index, so there is no copy to keep in step.
Each of the first five questions in the table is now one read, and the store can grow across many machines without the application changing. Then the food safety question arrives: who ordered the chicken biryani from restaurant 48213 between Monday and Wednesday? No key answers it. The options are to scan the whole table, which at hundreds of millions of items is slow and expensive, or to add a new index and backfill it, which takes hours or days. In Postgres the same question is one query:
SELECT DISTINCT o.customer_id
FROM orders o JOIN order_items i USING (order_id)
WHERE o.restaurant_id = 48213
AND i.item_id = 9001
AND o.created_at >= '2026-10-12' AND o.created_at < '2026-10-15';It might take a few seconds without a perfect index, and that is fine for a question asked twice a year.
| Need | Relational model | Key-value model |
|---|---|---|
| Known, frequent questions | fast with the right indexes | one read each, by design |
| A new question nobody planned | a new query, maybe a new index | a new index plus a backfill, or a scan |
| Changing several rows together | a transaction | limited transactions, often within one partition |
| Growing past one machine’s writes | hard; sharding is a project | built in |
| Keeping copies consistent | rarely needed | the application writes every copy |
For Dabba’s orders and menus, the questions are still changing and the write rate is modest, so the relational model’s flexibility is worth more than the key-value model’s scale. The key-value shape fits data with one or two fixed questions and high volume, such as rider positions and session data, and that is where Dabba uses it.
Changing the schema while orders keep arriving
Models change. Dabba starts charging for packaging and needs a packaging_paise column on a table that receives 150 inserts a second. Adding a column with a constant default is quick in modern Postgres (since version 11 it only updates the table’s metadata), but the change still needs a brief exclusive lock on the table. If a long report query is running on the primary, the ALTER TABLE waits for it, and every order insert queues behind the waiting ALTER. A change that takes milliseconds can stop order placement for as long as the report runs. Setting a short lock_timeout on migrations, and retrying, turns that outage into a failed migration that tries again a minute later.
Larger changes go in steps, because during a rolling deploy old and new versions of the code run at the same time against the same tables. Renaming a column, for example, becomes: add the new column; deploy code that writes both; backfill old rows in small batches (ten thousand rows at a time, so no single transaction locks much); deploy code that reads the new column; stop writing the old one; and finally drop it. Indexes on large live tables are built with CREATE INDEX CONCURRENTLY, which takes longer but does not block writes. The delivery chapter returns to this pattern, usually called expand and contract.
When not to copy
Snapshots are right for facts that describe the agreement. They are wrong for facts that must always be current. The restaurant’s phone number, which support uses to call the kitchen about a late order, must be the current one, so the order references the restaurant for it. The same goes for anything used to make a decision now, such as whether the restaurant is open, or whether a rider is still active.
We should revisit the model when a new question cannot be answered from it, such as analysts wanting to know how a menu looked on a past date (which calls for menu versions kept as history rather than overwritten), or when order volume grows to the point where the relational flexibility costs more than it returns. That last change is usually a sharding decision, made in the sharding chapter, and it is easier when the model already treats each order as a self-contained record, as this one does.
The tables are designed. The next chapter, Getting writes right, follows the moment an order is written into them: forty customers trying to buy the last twelve portions of a dish at once, and a payment provider that confirms payments on its own schedule.