DEV Community

OLTP, OLAP, and the source of truth: what DDIA taught me about data systems

Two kinds of systems

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.

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

Show the answer 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

Show the answer 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 sales table in the warehouse.

Why did ELT become popular? 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

Show the answer 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

Show the answer 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

Show the answer 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_stock holds the current quantity for each perfume and size. perfume_stock_logs records 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 moveme

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.