This is the second post in my series on Designing Data-Intensive Applications (DDIA) by Martin Kleppmann. In the last post I wrote about reliability. This time I read the first part of chapter 1, which is about the trade-offs behind how data systems are designed.
To keep it real, I'll use my own online perfume shop as the example: real queries, real tables, and one gap I found when I checked my own code. There are quizzes along the way, so you can test yourself as you read.
Two kinds of systems
The chapter starts by splitting data systems into two groups. Almost every company has both, even if it doesn't call them by these names.
Operational systems (OLTP)
OLTP means Online Transaction Processing. This is the backend of your app: the system that serves users while they click.
When a customer places an order on my shop, the backend runs queries like these (simplified):
-- Load one product page SELECT name, price, image_url FROM perfumes WHERE id = $1; -- Place an order INSERT INTO orders (customer_id, total, created_at) VALUES ($1, $2, now()); -- Take one bottle out of stock UPDATE perfume_size_stock SET quantity = quantity - 1 WHERE perfume_id = $1 AND size_label = '100ml'; Look at what they have in common:
- Each one touches one row, or a few rows.
- Each one finds its rows by a key (an id), usually through an index.
- They read and write the current state: the price now, the stock now.
- They must be fast. A real person is waiting for the page, so every millisecond counts.
Analytical systems (OLAP)
OLAP means Online Analytical Processing. Here the "user" is not a customer. It's me, as the business owner, or an analyst asking questions about the business:
-- Best-selling perfume per month, last year SELECT date_trunc('month', o.created_at) AS month, i.perfume_id, SUM(i.quantity) AS bottles_sold FROM orders o JOIN order_items i ON i.order_id = o.id WHERE o.created_at >= now() - interval '1 year' GROUP BY month, i.perfume_id ORDER BY month, bottles_sold DESC; This query is a different animal:
- It scans every order from a whole year, which could be millions of rows in a big shop.
- It reads only a few columns (date, product, quantity), not whole rows.
- It returns an aggregate: sums, counts, averages. Nobody wants to see a million raw rows.
- It looks at history, not just the current state.
- The questions are ad hoc. Tomorrow someone will ask a new question nobody planned for.
Side by side
| Operational (OLTP) | Analytical (OLAP) | |
|---|---|---|
| Who uses it | Customers, through the app | Analysts, managers, the owner |
| Read pattern | A few rows, found by key | Scan many rows, aggregate them |
| Write pattern | Many small writes, all day | Bulk imports or a stream of events |
| Data shows | The current state | History over time |
| Queries | Fixed, written by developers | Ad hoc, written by analysts |
| Main goal | Low latency per request | Fast scans over lots of data |
| Typical size | Gigabytes | Terabytes or more |
Where I was wrong
When I first tried to classify examples, I used the wrong rule. I thought: "If customers use it, it's OLTP. If the business owner uses it, it's OLAP."
Then I looked at one of my own examples: an admin changing the price of one perfume. The admin is the business owner, but this is clearly OLTP. It updates one row, by its id, and the change must happen right now.
The opposite also happens. A "Top 10 best sellers" box on the home page is seen by customers, but computing it means scanning and aggregating many orders. That part is analytical work, even though customers see the result.
★ Key idea: The real rule is the access pattern, not the person. A few rows by key and the current state means OLTP. Many rows, aggregated, over history means OLAP.
🧠 Quick check: An admin changes the price of one perfume from the dashboard. Which kind of workload is this?
- A. OLTP
- B. OLAP
OLTP
One row, found by its id, changed right now. Who does it doesn't matter.
🧠 Quick check: The home page shows "Top 10 best sellers this month", computed live from all orders. What kind of work is computing that list?
- A. OLTP, because customers see it
- B. OLAP, because it scans and aggregates many orders
OLAP, because it scans and aggregates many orders
The audience is customers, but the access pattern is a scan plus an aggregate. In practice you would compute it in the background and cache the result.
Why keep them apart?
If both kinds of queries can run on the same database, why do companies separate them? There are four good reasons.
1. Protecting the users. A heavy report that scans a year of orders uses a lot of CPU, memory, and disk. If it runs on the same database that handles checkout, customers feel it as a slow site, right when they are trying to pay.
2. Combining many sources. In a real company, the data lives in many systems: the website database, the shipping provider, the payment gateway, the marketing tool. The question "Do customers from Instagram ads get late deliveries more often?" needs all of them at once. No single operational database has that.
3. Different storage layouts. OLTP databases are built to find one row fast. Analytical systems are built to scan one column fast. Those are different designs (more on this in the deep dive below).
4. Access control. Analysts need to read a lot of data, but they should not be able to change orders, and they often should not see personal details like phone numbers and addresses. A separate system makes that easier to control.
Why do analytical databases store data by column?Most OLTP databases store data by row: all the fields of one order sit next to each other on disk. That's perfect for "load order 123": one read, and you have everything.
Now imagine an analytical query on a table with 10 million orders and 30 columns, where the query needs only 3 columns (date, product, quantity).
- Row storage has to read every row, which means all 30 columns, to pull out the 3 it needs. That's 100% of the data.
- Column storage keeps each column in its own file. The query reads only the 3 files it needs, which is about 10% of the data.
It gets better. Values inside one column look alike (lots of dates, lots of repeated product ids), so they compress very well. Less data on disk means even less to read.
That's why warehouses like BigQuery, Snowflake, Redshift, and ClickHouse are column-oriented. DDIA covers this in depth in a later chapter on storage.
The data warehouse
So larger companies copy their data into a separate system built for analytics: a data warehouse. Popular examples are Snowflake, Google BigQuery, Amazon Redshift, and ClickHouse.
The warehouse holds a read-only copy of data from many operational systems. Analysts can run any query they want on it, and the website never feels a thing.
How data gets there: ETL and ELT
Data moves into the warehouse through a pipeline:
- ETL: Extract → Transform → Load. Pull data out of the source, clean and reshape it, then load it.
- ELT: Extract → Load → Transform. Load the raw data first, then transform it inside the warehouse using SQL.
Here is what an ETL job for my shop could look like, running every night:
- Extract: read yesterday's new orders, order items, and stock movements from the shop database.
- Transform: remove customer phone numbers and addresses, convert all times to Cairo time, join each order item with its perfume name and brand.
- Load: append the result to a
salestable in the warehouse.
In the past, warehouses were expensive and limited, so you cleaned the data before loading it, on separate servers.
Modern cloud warehouses can scale their compute up and down on demand. So it became cheaper and simpler to load the raw data first and transform it inside the warehouse with SQL. Tools like dbt are built around this idea.
ELT has another advantage: you keep the raw data. If you later realise a transformation was wrong, you can run it again on the raw data. With ETL, whatever you threw away during the transform is gone.
The data lake
Not all data fits neatly into tables. Images, server logs, raw JSON events, and training data for machine learning are often just files.
A data lake is a place to store files in their raw form, usually in cheap object storage like Amazon S3. Each team reads the files and processes them in whatever way suits them.
A useful way to picture it:
- A warehouse is a library: every book is catalogued and on the right shelf.
- A lake is a storeroom full of boxes: you keep everything, and you sort it when you need it.
Today the line between the two is blurring. Columnar file formats like Parquet, and table formats like Apache Iceberg and Delta Lake, let you run warehouse-style SQL directly on files in a lake. This is often called a lakehouse.
Data can flow back, too
The flow is not only one way. Sometimes a result computed in the warehouse is sent back into an operational system. For example, a "customers likely to buy again" list computed in the warehouse could be pushed into the email marketing tool. This is sometimes called reverse ETL.
Do I need a warehouse?
Not yet. My shop is small and the load is low, so a report on the main database won't hurt anyone. Adding a warehouse today would only add cost and more things that can break.
But it helps to know the steps as a system grows. One of them is a read replica: a live copy of the database that only answers reads. Here is the ladder I would climb, one step at a time:
| Step | What it is | When to move up |
|---|---|---|
| 1. Same database | Run reports on the main database | Reports start slowing the site |
| 2. Read replica | A live copy of the database that only serves reads | Reports get slow even on the replica |
| 3. Summary tables | Pre-computed daily totals, refreshed by a job | You need data from other systems too |
| 4. Data warehouse | A separate analytical system fed by pipelines | (you're now a data-heavy company) |
✦ Tip: Every step up gives you something and costs you something. The right choice depends on your scale. That is the main message of the whole chapter: there is no "best" architecture, only trade-offs.
🧠 Quick check: Which of these is a real cost of adding a data warehouse?
- A. Customers see slower checkout
- B. Reports show data that is a little behind reality, and the pipelines need maintenance
- C. You can no longer run SQL on your data
Reports show data that is a little behind reality, and the pipelines need maintenance
The warehouse protects the operational database, but its data is only as fresh as the last pipeline run, and every pipeline is one more thing that can break.
🧠 Quick check: You need a dashboard with today's sales, and reports are starting to slow down your small shop's database. What is the simplest sensible next step?
- A. Move everything to a data lake
- B. Add a read replica and run reports there
- C. Build a full ETL pipeline into Snowflake
Add a read replica and run reports there
Climb the ladder one step at a time. A read replica keeps reports away from customers with almost no extra moving parts.
System of record vs derived data
The last idea in this part of the chapter is about a simple but important question: which copy of the data is the truth?
System of record (also called the source of truth): it holds the official version of the data. When something new happens, like a customer placing an order, it is written here first. Each fact is stored once, usually in a normalized form. If any other copy disagrees with it, the system of record wins.
Derived data: data created by taking data from another system and transforming or processing it. Examples:
- a cache of popular product pages
- a search index for finding perfumes by name or notes
- a materialized view or a pre-computed summary table
- the warehouse itself
- even a machine learning model trained on past orders
If you lose derived data, you can rebuild it from the source. It is redundant on purpose: it exists to make reads fast, or to look at the data in a different way.
Here is how data flows in a typical setup:
writes derived from Customer ─────────▶ Shop database ─────────────────▶ Search index (system of record) ─────────────────▶ Cache ─────────────────▶ Warehouse ──▶ Reports One important detail: the same tool can play either role. A Postgres database is not automatically the source of truth. It depends on how you use it in your system.
A small example: the star rating
Say I store each perfume's average star rating directly in the perfumes table, so the product page doesn't have to compute it.
- The individual reviews are the system of record.
- The stored average is derived data.
If they ever disagree, I trust the reviews. But I still show the stored average, because it's fast. When it's wrong, I don't edit the reviews. I rebuild the average from them.
🧠 Quick check: The stored average rating says 4.6, but the actual reviews average to 4.2. What should you do?
- A. Change some reviews so they match 4.6
- B. Show both numbers to the customer
- C. Recompute the stored average from the reviews
Recompute the stored average from the reviews
The reviews are the system of record. The average is derived, so you rebuild it from the source.
What I found in my own code
After reading this, I asked myself: is my stock count a system of record, or derived data? So I opened my code.
My shop uses two tables for stock:
-
perfume_size_stockholds the current quantity for each perfume and size. -
perfume_stock_logsrecords every movement: the change amount, the quantity before and after, the type (sale, restock, damage, correction), who did it, and why.
Every stock change goes through one database function that updates the quantity and writes the log row in the same transaction. So either both happen, or neither does.
That means the quantity table is the source of truth, and the log is an audit trail next to it.
There is another common design, the inventory ledger, where it's the other way around: the list of movements is the source of truth, and the quantity is just the sum of all movements.
| My design (current state + log) | Inventory ledger | |
|---|---|---|
| Source of truth | The quantity | The list of movements |
| Reading stock | Fast: one number | Sum of all movements (or a cached total) |
| History | Kept in the log | The history is the data |
| Risk | Quantity and log can drift apart | Hard to drift, but slower to read without a cache |
My design is a reasonable middle ground for a shop my size. Reading the stock is fast, I keep the full history, and I can reverse a movement without deleting anything.
! Watch out: But I also found a gap. If someone ever changes a quantity outside that function, for example by editing the table directly in the Supabase dashboard, the quantity changes but no log row is written. The two tables drift apart, and nothing in my system checks for that today.
The fix is a reconciliation check. This query compares each current quantity with the last quantity recorded in the log, and lists every mismatch:
SELECT s.perfume_id, s.size_label, s.quantity AS current_quantity, l.quantity_after AS last_logged_quantity FROM perfume_size_stock s LEFT JOIN LATERAL ( SELECT quantity_after FROM perfume_stock_logs g WHERE g.perfume_id = s.perfume_id AND g.size_label = s.size_label ORDER BY g.created_at DESC LIMIT 1 ) l ON true WHERE l.quantity_after IS DISTINCT FROM s.quantity; If this query returns no rows, the two tables agree. If it returns rows, something changed stock without leaving a trace, and now I know exactly where to look.
🧠 Quick check: In my shop, the quantity in perfume_size_stock and the latest row in perfume_stock_logs disagree. Based on my current design, which one is the source of truth?
- A. The quantity table
- B. The log table
- C. Neither, they are both derived
The quantity table
In my design the quantity is the source of truth and the log is an audit trail. In a full inventory ledger, the answer would flip.
Questions to think about
These don't have one right answer. Try them on your own project:
- Which of your tables is the source of truth, and which ones are derived? Could you rebuild every derived table if it disappeared tomorrow?
- Do you run any analytical queries on your operational database today? How big would your data need to be before that becomes a problem?
- If your cache and your database disagree, how would you find out? Do you have a check, or would a customer tell you first?
- What data would you remove or hide before sending it to analysts? Phone numbers, addresses, payment details?
Flashcards
🃏 Flashcards
OLTPOnline Transaction Processing. Few rows by key, current state, low latency. The app's backend.
OLAP
Online Analytical Processing. Scan many rows, read few columns, aggregate, look at history.
OLTP or OLAP: how to decide?
By the access pattern, not by who runs the query.
Why separate analytics?
Protect users from heavy queries, combine many sources, use column storage, control access.
Why column storage for analytics?
A query reads only the columns it needs, and similar values compress very well.
ETL vs ELT
ETL transforms before loading. ELT loads raw data and transforms it inside the warehouse.
Data lake
Raw files in cheap object storage (like S3), processed later by whoever needs them.
Reverse ETL
Sending results from the warehouse back into operational tools, like a marketing system.
System of record
The official copy of the data. Written first, wins any disagreement.
Derived data
Created from other data (cache, index, warehouse). Can always be rebuilt from the source.
Source and copy disagree?
Trust the source, then rebuild the derived data from it.
What's next
Next I'll finish chapter 1 and move on to chapter 2. I'll also add that reconciliation check to my shop's admin panel, and write about what it finds.
If you run a small app too, try this: pick one number your app shows, like a stock count, a rating, or a total, and ask yourself where its truth really lives.