SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

OLTP vs OLAP

Many small updates for live apps, or a few huge questions for analysts: two very different workloads.

โฑ 12 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

OLTP and OLAP are two very different kinds of work for a database. Most systems end up needing both, in two separate places.

  • OLTP (Online Transaction Processing) is the live app: place an order, pay, update a profile. Many small reads and writes, each touching a few rows, and each needs to be fast.
  • OLAP (Online Analytical Processing) is the analyst: "total sales by region for the last 3 years". Fewer queries, but each one scans millions of rows to calculate a summary.
  • They want different designs: row-based storage with indexes for OLTP, column-based storage in a warehouse for OLAP. Data usually flows from the first to the second.

02Concept: What is it?

An OLTP database runs the business as it happens. A shopper clicks "Buy" and the system must find the cart, reduce the stock, write the order and take the payment, all in a few milliseconds, while thousands of other shoppers do the same. Every request touches only a handful of rows. What matters is low latency, high concurrency and correctness (ACID transactions).

An OLAP system answers questions about the business as a whole. "Which region grew fastest?" has to read one or two columns from every sale ever made. Such a query may run for seconds or minutes, and only a few analysts run them at once. What matters is scan speed and the ability to handle huge volumes.

Because the work is so different, the best design is different too. OLTP stores each row together, because the app wants the whole row, and uses indexes to jump to one row fast. OLAP stores each column together, because a report needs a few columns of all rows, and columns of similar values compress very well.

One company, two databases
OLTP: the live app
๐Ÿ›’Shop appthousands of tiny requests
โ†“read / write a few rows
๐Ÿ—„๏ธRelational databaserow store, indexes, ACID
โ†’โ†“CDC or nightly ETL
OLAP: the analysts
๐Ÿง‘โ€๐Ÿ’ผAnalysts, dashboardsfew, heavy questions
โ†‘scan millions of rows
๐ŸขData warehousecolumn store, star schema
Running heavy reports on the live database slows the shop for every customer. So a copy of the data is sent to a separate analytics system.
๐Ÿง HTAP: one system for both?
Some databases try to serve both kinds of work (this is called HTAP, hybrid transactional and analytical processing), often by keeping a row copy and a column copy of the same data. It is convenient, but for most teams two separate systems are still the safe and common choice.

03Real-Life Example

๐ŸตThe Cashier and the Accountant
In a supermarket, the cashier serves one customer at a time: scan a few items, take the money, print the receipt, next. Speed and accuracy for each small job is everything. At the end of the year the accountant needs a very different thing: all the receipts, to find total sales per product per month. If the accountant sat at the till and read every receipt there, the queue would stop. So the shop copies the receipts to the back office, where the accountant can work for hours without disturbing the tills.
Supermarket
Databases
The cashier's till
OLTP database
One customer, a few items
A transaction touching a few rows
The accountant's back office
OLAP system / data warehouse
All the year's receipts
Millions of rows scanned by one query
Copying receipts to the back office each night
ETL or CDC from OLTP to OLAP
Counting at the till during opening hours
Running reports on the live database
Why the queue stops
๐ŸงพOne huge reportreads everything
โ†’โ†“uses the disk and CPU
๐Ÿ—„๏ธLive databaseshared
โ†’โ†“slow answers
๐Ÿ˜คShoppers wait

04Why Do We Need It?

๐ŸงฉRight tool for each job
A database tuned for tiny lookups is bad at huge scans, and the other way round. Separating them lets each be excellent.
๐Ÿ›ก๏ธProtect the live app
A heavy report on the production database can use all the CPU and disk, and slow down every customer. Moving it away keeps the shop fast.
โšกFast analytics
Column storage reads only the columns needed and compresses well, so a report over billions of rows can finish in seconds.
๐ŸงนClean, shared view
A warehouse can join data from many systems (orders, support, ads) into one tidy model for the whole company.
๐Ÿ“œHistory
The live database often keeps only current data. The warehouse can keep years of history for trends.
๐Ÿ”’Safe experiments
Analysts can run any heavy query without any risk of breaking the production system.
OLTP keeps the business running. OLAP helps you understand it. Do not make one database do both jobs.

05Where Do We Use It?

๐Ÿ’ณOLTP
Payments, orders, bookings, user accounts, inventory, banking. Typical engines: PostgreSQL, MySQL, SQL Server, Oracle.
๐Ÿ“ŠOLAP
Sales reports, dashboards, business intelligence, finance, product analytics, machine-learning features. Typical systems: cloud data warehouses and column stores.
๐Ÿ”The pipeline between
ETL jobs or change data capture copy data from the OLTP side into the warehouse.
๐ŸงชData science
Models learn from the big historical tables in the OLAP side, not from the live database.
๐Ÿ“ˆReal-time dashboards
A stream of events feeds an analytics store that is queried while the data is still fresh.
๐ŸงพAudit and compliance
Long-term history and reports usually live in the analytics side.

06Types / Parts / How It Works

The two workloads side by side

OLTPOLAP
PurposeRun the businessUnderstand the business
Typical queryGet or change one orderTotal sales per region, per month
Rows touched per queryA fewMillions to billions
Queries per secondThousandsA few at a time
Speed targetMillisecondsSeconds to minutes
Storage layoutRow-orientedColumn-oriented
SchemaNormalized, many small tablesDenormalized: star or snowflake
Data freshnessAlways the latestLoaded in batches or near real time
WritesMany small inserts and updatesBig bulk loads, few updates
Helped most byIndexes, caching, ACIDCompression, scanning in parallel

The star schema in one picture

A fact table in the middle, dimension tables around it
๐Ÿ“…Dateday, month, year
๐Ÿ“ฆProductname, category
โ†“
๐ŸงพSales (fact)date_id, product_id, store_id, amount
โ†‘
๐ŸฌStorecity, region
๐Ÿง‘Customersegment, country
The big fact table holds one row per sale. Small dimension tables describe the who, what, where and when.
Fact table (huge) Dimension tables (small)
VisualizerRow store vs column store: one tiny job and one huge jobStart with 'Sum sales by region' and 100 million rows. Then pick 'Look up one order' and see the winner change. Try asking for more columns and watch the column store's advantage shrink.
What job does the database get?

SELECT region, SUM(amount) FROM sales GROUP BY region

Row store (OLTP style)
Column store (OLAP style)

Lit squares are the data each store has to read. The picture is scaled down: 6 columns stand for all 40.

Row store: time32.0 s
Column store: time600 ms
Row store reads
32.0 GB
one long scan
Column store reads
600 MB
3 columns, compressed
Faster store
Column
about 53x
The question needs 3 of 40 columns over 100 million rows. The row store must read every column of every row (32.0 GB). The column store reads only the 3 columns it needs, and they compress well (600 MB). It is about 53 times faster here. This is why analytics uses column stores.

A simplified, illustrative model. Every value takes 8 bytes, columns compress 4 to 1, a disk scans 1 GB per second and each separate place costs 0.1 ms. Real databases add indexes, caches and many more tricks, so use this for the idea, not for numbers.

07How to Use It / Steps / Implementation

Keeping both sides healthy

  1. 1
    Keep reports off the live database
    Never let analysts run heavy queries on the primary. Give them a warehouse, or at the very least a read replica.
  2. 2
    Copy data over with ETL or CDC
    Nightly batch jobs are simple. Change data capture streams every change and keeps the warehouse fresh within seconds or minutes.
  3. 3
    Model the data for questions
    In the warehouse, reshape normalized tables into a star schema with one big fact table and small dimension tables.
  4. 4
    Choose column storage for analytics
    A column store reads only the columns in the query, and similar values compress well.
  5. 5
    Partition big tables by date
    Queries often ask for a time range. Partitioning lets the engine skip the months it does not need.
  6. 6
    Agree on definitions
    Decide once what 'active user' or 'revenue' means, and build it into the warehouse so every dashboard agrees.
  7. 7
    Watch freshness
    Track how far the warehouse is behind the live database, and tell users how fresh each dashboard is.
๐Ÿ’กStart simple
For a small product, a read replica of the main database may be enough for reports. Move to a warehouse when queries get slow, or when you need to combine data from several systems.

08Key Terms to Know

TermMeaning in easy words
OLTPOnline Transaction Processing: many small, fast reads and writes for a live app
OLAPOnline Analytical Processing: heavy queries that summarise lots of data
Row storeStores all the values of one row together on disk. Good for fetching whole rows
Column storeStores all the values of one column together. Good for scanning a few columns
Data warehouseA database built for analysis, fed with data from other systems
Star schemaA big fact table surrounded by small dimension tables
Fact tableRecords events or measurements, such as one row per sale
Dimension tableDescribes the who, what, where and when of the facts
ETLExtract, Transform, Load: copy data from sources into the warehouse in batches
CDCChange data capture: stream every change from a database to other systems
HTAPHybrid transactional and analytical processing: one system serving both workloads

09Pros, Cons and Trade-offs

โœ… Pros
  • Each side is tuned for its own job
  • Reports cannot slow down the live app
  • Analytics is much faster on column storage
  • History can be kept for years in the warehouse
  • Data from many systems can be joined in one place
โš ๏ธ Cons
  • Two systems to run, pay for and secure
  • Data in the warehouse is a little behind
  • A pipeline that can break and needs monitoring
  • Data is copied, so there are two versions of the truth to keep in line
  • Extra skills needed: modelling, pipelines, tuning

Trade-offs

ChoiceWe gainWe lose
Separate OLAP systemFast reports and a protected live appDelay, cost and a pipeline to maintain
Reports on a read replicaSimple, no new systemStill row storage, so big scans are slow, and replica lag
Nightly batch (ETL)Simple and cheapDashboards are up to a day old
Streaming (CDC)Fresh data within secondsMore moving parts to run
Star schema (denormalized)Simple, fast queriesRepeated data, and updates are harder
HTAP single systemOne place, very fresh analyticsComplex engine, and often compromises on both sides

10Common Problems and Mistakes

Common mistakes

  1. Running reports on the production database. One big query can slow every customer.
  2. Using a warehouse for live lookups. Column stores are slow at fetching one row and poor at many tiny writes.
  3. Using the live database for years of history. It grows large and slow, and the indexes get heavy.
  4. Copying the OLTP schema as it is. Highly normalized tables need many joins, which makes analytics slow and hard to write.
  5. No definition of the numbers. Two dashboards show two different "revenue" values.
  6. Forgetting freshness. People trust a dashboard that quietly stopped updating three days ago.

Things to watch

โฑ๏ธPipeline delay
Measure how far behind the warehouse is, and alert when it grows.
๐ŸงฎDifferent numbers
OLTP and OLAP can disagree after late or failed loads. Reconcile them regularly.
๐Ÿ”Sensitive data copied
The warehouse now holds personal data too. Apply the same access rules and masking.
๐Ÿ’ธQuery cost
Cloud warehouses can charge by data scanned. One careless query can be costly.

11Real-World Examples

๐Ÿ›๏ธOnline shops
Orders live in a relational database. Sales and customer trends go to a warehouse for the business team.
๐ŸฆBanks
Transactions run on strict OLTP systems. Risk and fraud analysis run on separate analytical systems.
๐ŸŽฌStreaming services
Playback and billing are transactional. Viewing history across millions of users feeds analytics and recommendations.
๐Ÿš•Ride apps
Live trips need quick transactional updates. City-wide demand and pricing studies run on analytics data.
๐ŸฅHospitals
Patient records are updated in real time. Research and planning use a separate analytical copy.
๐Ÿ“ฑMobile apps
App events pour into an analytics store to measure which features people use.
๐Ÿ“Note
Product names and features change over time. Check current documentation before you choose an engine.
Mini case: from checkout to dashboard
๐Ÿ›’CheckoutOLTP write
โ†’โ†“log of changes
๐Ÿ”CDC / ETL
โ†’โ†“load
๐ŸขWarehouseOLAP
โ†’โ†“query
๐Ÿ“ŠDashboard
The shop stays fast, and the finance team still gets daily numbers.

12Related Topics to Read Next

Columnar Databasesโ†’

The storage layout that makes analytics fast.

Data Warehousingโ†’

The home of OLAP data, and how it is modelled.

ETL Pipelinesโ†’

The batch jobs that move data from OLTP to OLAP.

Change Data Capture (CDC)โ†’

A way to keep the warehouse fresh with every change.

Relational Databasesโ†’

The usual home of OLTP workloads.

Indexingโ†’

What makes tiny OLTP lookups fast.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”OLTP: many small, fast transactions on a few rows. Row store, indexes, ACID.
  • โœ”OLAP: few heavy queries over millions of rows. Column store, compression, warehouse.
  • โœ”Do not run big reports on the live database.
  • โœ”Flow: OLTP โ†’ ETL or CDC โ†’ warehouse โ†’ dashboards.
  • โœ”Schema: normalized for OLTP, star schema for OLAP.
  • โœ”Row lookup: row store wins. Big scan of few columns: column store wins.
  • โœ”Watch: pipeline delay and mismatched numbers.
  • โœ”One line: โ€œOLTP runs the business, OLAP explains it, and each deserves its own database.โ€
โ† Previous
Normalization
Next โ†’
BASE and PACELC